blob: b18060c3c5f41eeb067557c679cedc3cd729b0c9 [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"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/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,
33 const Expr *E,
34 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
Ted Kremenekebcb57a2012-03-06 20:05:56 +000054/// EmitObjCNumericLiteral - This routine generates code for
55/// the appropriate +[NSNumber numberWith<Type>:] method.
56///
57llvm::Value *CodeGenFunction::EmitObjCNumericLiteral(const ObjCNumericLiteral *E) {
58 // Generate the correct selector for this literal's concrete type.
59 const Expr *NL = E->getNumber();
60 // Get the method.
61 const ObjCMethodDecl *Method = E->getObjCNumericLiteralMethod();
62 assert(Method && "NSNumber method is null");
63 Selector Sel = Method->getSelector();
64
65 // Generate a reference to the class pointer, which will be the receiver.
66 QualType ResultType = E->getType(); // should be NSNumber *
67 const ObjCObjectPointerType *InterfacePointerType =
68 ResultType->getAsObjCInterfacePointerType();
69 ObjCInterfaceDecl *NSNumberDecl =
70 InterfacePointerType->getObjectType()->getInterface();
71 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
72 llvm::Value *Receiver = Runtime.GetClass(Builder, NSNumberDecl);
73
74 const ParmVarDecl *argDecl = *Method->param_begin();
75 QualType ArgQT = argDecl->getType().getUnqualifiedType();
76 RValue RV = EmitAnyExpr(NL);
77 CallArgList Args;
78 Args.add(RV, ArgQT);
79
80 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
81 ResultType, Sel, Receiver, Args,
82 NSNumberDecl, Method);
83 return Builder.CreateBitCast(result.getScalarVal(),
84 ConvertType(E->getType()));
85}
86
87llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
88 const ObjCMethodDecl *MethodWithObjects) {
89 ASTContext &Context = CGM.getContext();
90 const ObjCDictionaryLiteral *DLE = 0;
91 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
92 if (!ALE)
93 DLE = cast<ObjCDictionaryLiteral>(E);
94
95 // Compute the type of the array we're initializing.
96 uint64_t NumElements =
97 ALE ? ALE->getNumElements() : DLE->getNumElements();
98 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
99 NumElements);
100 QualType ElementType = Context.getObjCIdType().withConst();
101 QualType ElementArrayType
102 = Context.getConstantArrayType(ElementType, APNumElements,
103 ArrayType::Normal, /*IndexTypeQuals=*/0);
104
105 // Allocate the temporary array(s).
106 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
107 llvm::Value *Keys = 0;
108 if (DLE)
109 Keys = CreateMemTemp(ElementArrayType, "keys");
110
111 // Perform the actual initialialization of the array(s).
112 for (uint64_t i = 0; i < NumElements; i++) {
113 if (ALE) {
114 // Emit the initializer.
115 const Expr *Rhs = ALE->getElement(i);
116 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
117 ElementType,
118 Context.getTypeAlignInChars(Rhs->getType()),
119 Context);
120 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
121 } else {
122 // Emit the key initializer.
123 const Expr *Key = DLE->getKeyValueElement(i).Key;
124 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
125 ElementType,
126 Context.getTypeAlignInChars(Key->getType()),
127 Context);
128 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
129
130 // Emit the value initializer.
131 const Expr *Value = DLE->getKeyValueElement(i).Value;
132 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
133 ElementType,
134 Context.getTypeAlignInChars(Value->getType()),
135 Context);
136 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
137 }
138 }
139
140 // Generate the argument list.
141 CallArgList Args;
142 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
143 const ParmVarDecl *argDecl = *PI++;
144 QualType ArgQT = argDecl->getType().getUnqualifiedType();
145 Args.add(RValue::get(Objects), ArgQT);
146 if (DLE) {
147 argDecl = *PI++;
148 ArgQT = argDecl->getType().getUnqualifiedType();
149 Args.add(RValue::get(Keys), ArgQT);
150 }
151 argDecl = *PI;
152 ArgQT = argDecl->getType().getUnqualifiedType();
153 llvm::Value *Count =
154 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
155 Args.add(RValue::get(Count), ArgQT);
156
157 // Generate a reference to the class pointer, which will be the receiver.
158 Selector Sel = MethodWithObjects->getSelector();
159 QualType ResultType = E->getType();
160 const ObjCObjectPointerType *InterfacePointerType
161 = ResultType->getAsObjCInterfacePointerType();
162 ObjCInterfaceDecl *Class
163 = InterfacePointerType->getObjectType()->getInterface();
164 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
165 llvm::Value *Receiver = Runtime.GetClass(Builder, Class);
166
167 // Generate the message send.
168 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
169 MethodWithObjects->getResultType(),
170 Sel,
171 Receiver, Args, Class,
172 MethodWithObjects);
173 return Builder.CreateBitCast(result.getScalarVal(),
174 ConvertType(E->getType()));
175}
176
177llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
178 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
179}
180
181llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
182 const ObjCDictionaryLiteral *E) {
183 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
184}
185
Chris Lattner8fdf3282008-06-24 17:04:18 +0000186/// Emit a selector.
187llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
188 // Untyped selector.
189 // Note that this implementation allows for non-constant strings to be passed
190 // as arguments to @selector(). Currently, the only thing preventing this
191 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000192 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000193}
194
Daniel Dunbared7c6182008-08-20 00:28:19 +0000195llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
196 // FIXME: This should pass the Decl not the name.
197 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
198}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000199
Douglas Gregor926df6c2011-06-11 01:09:30 +0000200/// \brief Adjust the type of the result of an Objective-C message send
201/// expression when the method has a related result type.
202static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
203 const Expr *E,
204 const ObjCMethodDecl *Method,
205 RValue Result) {
206 if (!Method)
207 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000208
Douglas Gregor926df6c2011-06-11 01:09:30 +0000209 if (!Method->hasRelatedResultType() ||
210 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
211 !Result.isScalar())
212 return Result;
213
214 // We have applied a related result type. Cast the rvalue appropriately.
215 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
216 CGF.ConvertType(E->getType())));
217}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000218
John McCalldc7c5ad2011-07-22 08:53:00 +0000219/// Decide whether to extend the lifetime of the receiver of a
220/// returns-inner-pointer message.
221static bool
222shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
223 switch (message->getReceiverKind()) {
224
225 // For a normal instance message, we should extend unless the
226 // receiver is loaded from a variable with precise lifetime.
227 case ObjCMessageExpr::Instance: {
228 const Expr *receiver = message->getInstanceReceiver();
229 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
230 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
231 receiver = ice->getSubExpr()->IgnoreParens();
232
233 // Only __strong variables.
234 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
235 return true;
236
237 // All ivars and fields have precise lifetime.
238 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
239 return false;
240
241 // Otherwise, check for variables.
242 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
243 if (!declRef) return true;
244 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
245 if (!var) return true;
246
247 // All variables have precise lifetime except local variables with
248 // automatic storage duration that aren't specially marked.
249 return (var->hasLocalStorage() &&
250 !var->hasAttr<ObjCPreciseLifetimeAttr>());
251 }
252
253 case ObjCMessageExpr::Class:
254 case ObjCMessageExpr::SuperClass:
255 // It's never necessary for class objects.
256 return false;
257
258 case ObjCMessageExpr::SuperInstance:
259 // We generally assume that 'self' lives throughout a method call.
260 return false;
261 }
262
263 llvm_unreachable("invalid receiver kind");
264}
265
John McCallef072fd2010-05-22 01:48:05 +0000266RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
267 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000268 // Only the lookup mechanism and first two arguments of the method
269 // implementation vary between runtimes. We can get the receiver and
270 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000271
John McCallf85e1932011-06-15 23:02:42 +0000272 bool isDelegateInit = E->isDelegateInitCall();
273
John McCalldc7c5ad2011-07-22 08:53:00 +0000274 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000275
John McCallf85e1932011-06-15 23:02:42 +0000276 // We don't retain the receiver in delegate init calls, and this is
277 // safe because the receiver value is always loaded from 'self',
278 // which we zero out. We don't want to Block_copy block receivers,
279 // though.
280 bool retainSelf =
281 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000282 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000283 method &&
284 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000285
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000286 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000287 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000288 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000289 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000290 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000291 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000292 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000293 switch (E->getReceiverKind()) {
294 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000295 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000296 if (retainSelf) {
297 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
298 E->getInstanceReceiver());
299 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000300 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000301 } else
302 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000303 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000304
Douglas Gregor04badcf2010-04-21 00:45:42 +0000305 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000306 ReceiverType = E->getClassReceiver();
307 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000308 assert(ObjTy && "Invalid Objective-C class message send");
309 OID = ObjTy->getInterface();
310 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000311 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000312 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000313 break;
314 }
315
316 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000317 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000318 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000319 isSuperMessage = true;
320 break;
321
322 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000323 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000324 Receiver = LoadObjCSelf();
325 isSuperMessage = true;
326 isClassMessage = true;
327 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000328 }
329
John McCalldc7c5ad2011-07-22 08:53:00 +0000330 if (retainSelf)
331 Receiver = EmitARCRetainNonBlock(Receiver);
332
333 // In ARC, we sometimes want to "extend the lifetime"
334 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
335 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000336 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000337 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
338 shouldExtendReceiverForInnerPointerMessage(E))
339 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
340
John McCallf85e1932011-06-15 23:02:42 +0000341 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000342 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000343
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000344 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000345 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000346
John McCallf85e1932011-06-15 23:02:42 +0000347 // For delegate init calls in ARC, do an unsafe store of null into
348 // self. This represents the call taking direct ownership of that
349 // value. We have to do this after emitting the other call
350 // arguments because they might also reference self, but we don't
351 // have to worry about any of them modifying self because that would
352 // be an undefined read and write of an object in unordered
353 // expressions.
354 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000355 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000356 "delegate init calls should only be marked in ARC");
357
358 // Do an unsafe store of null into self.
359 llvm::Value *selfAddr =
360 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
361 assert(selfAddr && "no self entry for a delegate init call?");
362
363 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
364 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000365
Douglas Gregor926df6c2011-06-11 01:09:30 +0000366 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000367 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000368 // super is only valid in an Objective-C method
369 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000370 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000371 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
372 E->getSelector(),
373 OMD->getClassInterface(),
374 isCategoryImpl,
375 Receiver,
376 isClassMessage,
377 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000378 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000379 } else {
380 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
381 E->getSelector(),
382 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000383 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000384 }
John McCallf85e1932011-06-15 23:02:42 +0000385
386 // For delegate init calls in ARC, implicitly store the result of
387 // the call back into self. This takes ownership of the value.
388 if (isDelegateInit) {
389 llvm::Value *selfAddr =
390 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
391 llvm::Value *newSelf = result.getScalarVal();
392
393 // The delegate return type isn't necessarily a matching type; in
394 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000395 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000396 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
397 newSelf = Builder.CreateBitCast(newSelf, selfTy);
398
399 Builder.CreateStore(newSelf, selfAddr);
400 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000401
402 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000403}
404
John McCallf85e1932011-06-15 23:02:42 +0000405namespace {
406struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000407 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000408 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000409
410 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000411 const ObjCInterfaceDecl *iface = impl->getClassInterface();
412 if (!iface->getSuperClass()) return;
413
John McCall799d34e2011-07-13 18:26:47 +0000414 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
415
John McCallf85e1932011-06-15 23:02:42 +0000416 // Call [super dealloc] if we have a superclass.
417 llvm::Value *self = CGF.LoadObjCSelf();
418
419 CallArgList args;
420 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
421 CGF.getContext().VoidTy,
422 method->getSelector(),
423 iface,
John McCall799d34e2011-07-13 18:26:47 +0000424 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000425 self,
426 /*is class msg*/ false,
427 args,
428 method);
429 }
430};
431}
432
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000433/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
434/// the LLVM function and sets the other context used by
435/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000436void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000437 const ObjCContainerDecl *CD,
438 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000439 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000440 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000441 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
442 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000443
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000444 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000445
John McCallde5d3c72012-02-17 03:33:10 +0000446 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000447 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000448
John McCalld26bc762011-03-09 04:27:21 +0000449 args.push_back(OMD->getSelfDecl());
450 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000451
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000452 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Chris Lattner89951a82009-02-20 18:43:26 +0000453 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000454 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000455
Peter Collingbourne14110472011-01-13 18:57:25 +0000456 CurGD = OMD;
457
Devang Patel8d3f8972011-05-19 23:37:41 +0000458 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000459
460 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000461 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000462 OMD->isInstanceMethod() &&
463 OMD->getSelector().isUnarySelector()) {
464 const IdentifierInfo *ident =
465 OMD->getSelector().getIdentifierInfoForSlot(0);
466 if (ident->isStr("dealloc"))
467 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
468 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000469}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000470
John McCallf85e1932011-06-15 23:02:42 +0000471static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
472 LValue lvalue, QualType type);
473
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000474/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000475/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000476void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000477 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000478 EmitStmt(OMD->getBody());
479 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000480}
481
John McCall41bdde92011-09-12 23:06:44 +0000482/// emitStructGetterCall - Call the runtime function to load a property
483/// into the return value slot.
484static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
485 bool isAtomic, bool hasStrong) {
486 ASTContext &Context = CGF.getContext();
487
488 llvm::Value *src =
489 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
490 ivar, 0).getAddress();
491
492 // objc_copyStruct (ReturnValue, &structIvar,
493 // sizeof (Type of Ivar), isAtomic, false);
494 CallArgList args;
495
496 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
497 args.add(RValue::get(dest), Context.VoidPtrTy);
498
499 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
500 args.add(RValue::get(src), Context.VoidPtrTy);
501
502 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
503 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
504 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
505 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
506
507 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000508 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args,
509 FunctionType::ExtInfo(),
510 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000511 fn, ReturnValueSlot(), args);
512}
513
John McCall1e1f4872011-09-13 03:34:09 +0000514/// Determine whether the given architecture supports unaligned atomic
515/// accesses. They don't have to be fast, just faster than a function
516/// call and a mutex.
517static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000518 // FIXME: Allow unaligned atomic load/store on x86. (It is not
519 // currently supported by the backend.)
520 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000521}
522
523/// Return the maximum size that permits atomic accesses for the given
524/// architecture.
525static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
526 llvm::Triple::ArchType arch) {
527 // ARM has 8-byte atomic accesses, but it's not clear whether we
528 // want to rely on them here.
529
530 // In the default case, just assume that any size up to a pointer is
531 // fine given adequate alignment.
532 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
533}
534
535namespace {
536 class PropertyImplStrategy {
537 public:
538 enum StrategyKind {
539 /// The 'native' strategy is to use the architecture's provided
540 /// reads and writes.
541 Native,
542
543 /// Use objc_setProperty and objc_getProperty.
544 GetSetProperty,
545
546 /// Use objc_setProperty for the setter, but use expression
547 /// evaluation for the getter.
548 SetPropertyAndExpressionGet,
549
550 /// Use objc_copyStruct.
551 CopyStruct,
552
553 /// The 'expression' strategy is to emit normal assignment or
554 /// lvalue-to-rvalue expressions.
555 Expression
556 };
557
558 StrategyKind getKind() const { return StrategyKind(Kind); }
559
560 bool hasStrongMember() const { return HasStrong; }
561 bool isAtomic() const { return IsAtomic; }
562 bool isCopy() const { return IsCopy; }
563
564 CharUnits getIvarSize() const { return IvarSize; }
565 CharUnits getIvarAlignment() const { return IvarAlignment; }
566
567 PropertyImplStrategy(CodeGenModule &CGM,
568 const ObjCPropertyImplDecl *propImpl);
569
570 private:
571 unsigned Kind : 8;
572 unsigned IsAtomic : 1;
573 unsigned IsCopy : 1;
574 unsigned HasStrong : 1;
575
576 CharUnits IvarSize;
577 CharUnits IvarAlignment;
578 };
579}
580
581/// Pick an implementation strategy for the the given property synthesis.
582PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
583 const ObjCPropertyImplDecl *propImpl) {
584 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000585 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000586
John McCall265941b2011-09-13 18:31:23 +0000587 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
588 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000589 HasStrong = false; // doesn't matter here.
590
591 // Evaluate the ivar's size and alignment.
592 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
593 QualType ivarType = ivar->getType();
594 llvm::tie(IvarSize, IvarAlignment)
595 = CGM.getContext().getTypeInfoInChars(ivarType);
596
597 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000598 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000599 if (IsCopy) {
600 Kind = GetSetProperty;
601 return;
602 }
603
John McCall265941b2011-09-13 18:31:23 +0000604 // Handle retain.
605 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000606 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000607 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000608 // fallthrough
609
610 // In ARC, if the property is non-atomic, use expression emission,
611 // which translates to objc_storeStrong. This isn't required, but
612 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000613 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCall1e1f4872011-09-13 03:34:09 +0000614 Kind = Expression;
615 return;
616
617 // Otherwise, we need to at least use setProperty. However, if
618 // the property isn't atomic, we can use normal expression
619 // emission for the getter.
620 } else if (!IsAtomic) {
621 Kind = SetPropertyAndExpressionGet;
622 return;
623
624 // Otherwise, we have to use both setProperty and getProperty.
625 } else {
626 Kind = GetSetProperty;
627 return;
628 }
629 }
630
631 // If we're not atomic, just use expression accesses.
632 if (!IsAtomic) {
633 Kind = Expression;
634 return;
635 }
636
John McCall5889c602011-09-13 05:36:29 +0000637 // Properties on bitfield ivars need to be emitted using expression
638 // accesses even if they're nominally atomic.
639 if (ivar->isBitField()) {
640 Kind = Expression;
641 return;
642 }
643
John McCall1e1f4872011-09-13 03:34:09 +0000644 // GC-qualified or ARC-qualified ivars need to be emitted as
645 // expressions. This actually works out to being atomic anyway,
646 // except for ARC __strong, but that should trigger the above code.
647 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000649 CGM.getContext().getObjCGCAttrKind(ivarType))) {
650 Kind = Expression;
651 return;
652 }
653
654 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000655 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000656 if (const RecordType *recordType = ivarType->getAs<RecordType>())
657 HasStrong = recordType->getDecl()->hasObjectMember();
658
659 // We can never access structs with object members with a native
660 // access, because we need to use write barriers. This is what
661 // objc_copyStruct is for.
662 if (HasStrong) {
663 Kind = CopyStruct;
664 return;
665 }
666
667 // Otherwise, this is target-dependent and based on the size and
668 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000669
670 // If the size of the ivar is not a power of two, give up. We don't
671 // want to get into the business of doing compare-and-swaps.
672 if (!IvarSize.isPowerOfTwo()) {
673 Kind = CopyStruct;
674 return;
675 }
676
John McCall1e1f4872011-09-13 03:34:09 +0000677 llvm::Triple::ArchType arch =
678 CGM.getContext().getTargetInfo().getTriple().getArch();
679
680 // Most architectures require memory to fit within a single cache
681 // line, so the alignment has to be at least the size of the access.
682 // Otherwise we have to grab a lock.
683 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
684 Kind = CopyStruct;
685 return;
686 }
687
688 // If the ivar's size exceeds the architecture's maximum atomic
689 // access size, we have to use CopyStruct.
690 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
691 Kind = CopyStruct;
692 return;
693 }
694
695 // Otherwise, we can use native loads and stores.
696 Kind = Native;
697}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000698
699/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000700/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
701/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000702void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
703 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000704 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000705 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000706 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
707 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
708 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000709 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000711 generateObjCGetterBody(IMP, PID, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000712
713 FinishFunction();
714}
715
John McCall6c11f0b2011-09-13 06:00:03 +0000716static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
717 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000718 if (!getter) return true;
719
720 // Sema only makes only of these when the ivar has a C++ class type,
721 // so the form is pretty constrained.
722
John McCall6c11f0b2011-09-13 06:00:03 +0000723 // If the property has a reference type, we might just be binding a
724 // reference, in which case the result will be a gl-value. We should
725 // treat this as a non-trivial operation.
726 if (getter->isGLValue())
727 return false;
728
John McCall1e1f4872011-09-13 03:34:09 +0000729 // If we selected a trivial copy-constructor, we're okay.
730 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
731 return (construct->getConstructor()->isTrivial());
732
733 // The constructor might require cleanups (in which case it's never
734 // trivial).
735 assert(isa<ExprWithCleanups>(getter));
736 return false;
737}
738
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000739/// emitCPPObjectAtomicGetterCall - Call the runtime function to
740/// copy the ivar into the resturn slot.
741static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
742 llvm::Value *returnAddr,
743 ObjCIvarDecl *ivar,
744 llvm::Constant *AtomicHelperFn) {
745 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
746 // AtomicHelperFn);
747 CallArgList args;
748
749 // The 1st argument is the return Slot.
750 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
751
752 // The 2nd argument is the address of the ivar.
753 llvm::Value *ivarAddr =
754 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
755 CGF.LoadObjCSelf(), ivar, 0).getAddress();
756 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
757 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
758
759 // Third argument is the helper function.
760 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
761
762 llvm::Value *copyCppAtomicObjectFn =
763 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000764 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
765 FunctionType::ExtInfo(),
766 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000767 copyCppAtomicObjectFn, ReturnValueSlot(), args);
768}
769
John McCall1e1f4872011-09-13 03:34:09 +0000770void
771CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000772 const ObjCPropertyImplDecl *propImpl,
773 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000774 // If there's a non-trivial 'get' expression, we just have to emit that.
775 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000776 if (!AtomicHelperFn) {
777 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
778 /*nrvo*/ 0);
779 EmitReturnStmt(ret);
780 }
781 else {
782 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
783 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
784 ivar, AtomicHelperFn);
785 }
John McCall1e1f4872011-09-13 03:34:09 +0000786 return;
787 }
788
789 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
790 QualType propType = prop->getType();
791 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
792
793 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
794
795 // Pick an implementation strategy.
796 PropertyImplStrategy strategy(CGM, propImpl);
797 switch (strategy.getKind()) {
798 case PropertyImplStrategy::Native: {
799 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
800
801 // Currently, all atomic accesses have to be through integer
802 // types, so there's no point in trying to pick a prettier type.
803 llvm::Type *bitcastType =
804 llvm::Type::getIntNTy(getLLVMContext(),
805 getContext().toBits(strategy.getIvarSize()));
806 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
807
808 // Perform an atomic load. This does not impose ordering constraints.
809 llvm::Value *ivarAddr = LV.getAddress();
810 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
811 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
812 load->setAlignment(strategy.getIvarAlignment().getQuantity());
813 load->setAtomic(llvm::Unordered);
814
815 // Store that value into the return address. Doing this with a
816 // bitcast is likely to produce some pretty ugly IR, but it's not
817 // the *most* terrible thing in the world.
818 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
819
820 // Make sure we don't do an autorelease.
821 AutoreleaseResult = false;
822 return;
823 }
824
825 case PropertyImplStrategy::GetSetProperty: {
826 llvm::Value *getPropertyFn =
827 CGM.getObjCRuntime().GetPropertyGetFunction();
828 if (!getPropertyFn) {
829 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000830 return;
831 }
832
833 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
834 // FIXME: Can't this be simpler? This might even be worse than the
835 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000836 llvm::Value *cmd =
837 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
838 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
839 llvm::Value *ivarOffset =
840 EmitIvarOffset(classImpl->getClassInterface(), ivar);
841
842 CallArgList args;
843 args.add(RValue::get(self), getContext().getObjCIdType());
844 args.add(RValue::get(cmd), getContext().getObjCSelType());
845 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000846 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
847 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000848
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000849 // FIXME: We shouldn't need to get the function info here, the
850 // runtime already should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +0000851 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args,
852 FunctionType::ExtInfo(),
853 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000854 getPropertyFn, ReturnValueSlot(), args);
855
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000856 // We need to fix the type here. Ivars with copy & retain are
857 // always objects so we don't need to worry about complex or
858 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000859 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000860 getTypes().ConvertType(propType)));
861
862 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000863
864 // objc_getProperty does an autorelease, so we should suppress ours.
865 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000866
John McCall1e1f4872011-09-13 03:34:09 +0000867 return;
868 }
869
870 case PropertyImplStrategy::CopyStruct:
871 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
872 strategy.hasStrongMember());
873 return;
874
875 case PropertyImplStrategy::Expression:
876 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
877 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
878
879 QualType ivarType = ivar->getType();
880 if (ivarType->isAnyComplexType()) {
881 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
882 LV.isVolatileQualified());
883 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
884 } else if (hasAggregateLLVMType(ivarType)) {
885 // The return value slot is guaranteed to not be aliased, but
886 // that's not necessarily the same as "on the stack", so
887 // we still potentially need objc_memmove_collectable.
888 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
889 } else {
John McCallba3dd902011-07-22 05:23:13 +0000890 llvm::Value *value;
891 if (propType->isReferenceType()) {
892 value = LV.getAddress();
893 } else {
894 // We want to load and autoreleaseReturnValue ARC __weak ivars.
895 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000896 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000897
898 // Otherwise we want to do a simple load, suppressing the
899 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000900 } else {
John McCallba3dd902011-07-22 05:23:13 +0000901 value = EmitLoadOfLValue(LV).getScalarVal();
902 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000903 }
John McCallf85e1932011-06-15 23:02:42 +0000904
John McCallba3dd902011-07-22 05:23:13 +0000905 value = Builder.CreateBitCast(value, ConvertType(propType));
906 }
907
908 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000909 }
John McCall1e1f4872011-09-13 03:34:09 +0000910 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000911 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000912
John McCall1e1f4872011-09-13 03:34:09 +0000913 }
914 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000915}
916
John McCall41bdde92011-09-12 23:06:44 +0000917/// emitStructSetterCall - Call the runtime function to store the value
918/// from the first formal parameter into the given ivar.
919static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
920 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000921 // objc_copyStruct (&structIvar, &Arg,
922 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000923 CallArgList args;
924
925 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000926 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
927 CGF.LoadObjCSelf(), ivar, 0)
928 .getAddress();
929 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
930 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000931
932 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000933 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000934 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000935 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000936 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
937 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
938 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000939
940 // The third argument is the sizeof the type.
941 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000942 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
943 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000944
John McCall41bdde92011-09-12 23:06:44 +0000945 // The fourth argument is the 'isAtomic' flag.
946 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000947
John McCall41bdde92011-09-12 23:06:44 +0000948 // The fifth argument is the 'hasStrong' flag.
949 // FIXME: should this really always be false?
950 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
951
952 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000953 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
954 FunctionType::ExtInfo(),
955 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000956 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000957}
958
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000959/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
960/// the value from the first formal parameter into the given ivar, using
961/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
962static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
963 ObjCMethodDecl *OMD,
964 ObjCIvarDecl *ivar,
965 llvm::Constant *AtomicHelperFn) {
966 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
967 // AtomicHelperFn);
968 CallArgList args;
969
970 // The first argument is the address of the ivar.
971 llvm::Value *ivarAddr =
972 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
973 CGF.LoadObjCSelf(), ivar, 0).getAddress();
974 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
975 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
976
977 // The second argument is the address of the parameter variable.
978 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000979 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000980 VK_LValue, SourceLocation());
981 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
982 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
983 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
984
985 // Third argument is the helper function.
986 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
987
988 llvm::Value *copyCppAtomicObjectFn =
989 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000990 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
991 FunctionType::ExtInfo(),
992 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000993 copyCppAtomicObjectFn, ReturnValueSlot(), args);
994
995
996}
997
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000998
John McCall1e1f4872011-09-13 03:34:09 +0000999static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1000 Expr *setter = PID->getSetterCXXAssignment();
1001 if (!setter) return true;
1002
1003 // Sema only makes only of these when the ivar has a C++ class type,
1004 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001005
1006 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001007 // This also implies that there's nothing non-trivial going on with
1008 // the arguments, because operator= can only be trivial if it's a
1009 // synthesized assignment operator and therefore both parameters are
1010 // references.
1011 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001012 if (const FunctionDecl *callee
1013 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1014 if (callee->isTrivial())
1015 return true;
1016 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001017 }
John McCall71c758d2011-09-10 09:17:20 +00001018
John McCall1e1f4872011-09-13 03:34:09 +00001019 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001020 return false;
1021}
1022
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001023static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001024 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001025 return false;
1026 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001027
1028 if (Target.getPlatformName() != "macosx")
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001029 return false;
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001030
1031 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001032}
1033
John McCall71c758d2011-09-10 09:17:20 +00001034void
1035CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001036 const ObjCPropertyImplDecl *propImpl,
1037 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001038 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001039 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001040 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001041
1042 // Just use the setter expression if Sema gave us one and it's
1043 // non-trivial.
1044 if (!hasTrivialSetExpr(propImpl)) {
1045 if (!AtomicHelperFn)
1046 // If non-atomic, assignment is called directly.
1047 EmitStmt(propImpl->getSetterCXXAssignment());
1048 else
1049 // If atomic, assignment is called via a locking api.
1050 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1051 AtomicHelperFn);
1052 return;
1053 }
John McCall71c758d2011-09-10 09:17:20 +00001054
John McCall1e1f4872011-09-13 03:34:09 +00001055 PropertyImplStrategy strategy(CGM, propImpl);
1056 switch (strategy.getKind()) {
1057 case PropertyImplStrategy::Native: {
1058 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001059
John McCall1e1f4872011-09-13 03:34:09 +00001060 LValue ivarLValue =
1061 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1062 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001063
John McCall1e1f4872011-09-13 03:34:09 +00001064 // Currently, all atomic accesses have to be through integer
1065 // types, so there's no point in trying to pick a prettier type.
1066 llvm::Type *bitcastType =
1067 llvm::Type::getIntNTy(getLLVMContext(),
1068 getContext().toBits(strategy.getIvarSize()));
1069 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1070
1071 // Cast both arguments to the chosen operation type.
1072 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1073 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1074
1075 // This bitcast load is likely to cause some nasty IR.
1076 llvm::Value *load = Builder.CreateLoad(argAddr);
1077
1078 // Perform an atomic store. There are no memory ordering requirements.
1079 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1080 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1081 store->setAtomic(llvm::Unordered);
1082 return;
1083 }
1084
1085 case PropertyImplStrategy::GetSetProperty:
1086 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001087
1088 llvm::Value *setOptimizedPropertyFn = 0;
1089 llvm::Value *setPropertyFn = 0;
1090 if (UseOptimizedSetter(CGM)) {
1091 // 10.8 code and GC is off
1092 setOptimizedPropertyFn =
1093 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(strategy.isAtomic(),
1094 strategy.isCopy());
1095 if (!setOptimizedPropertyFn) {
1096 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1097 return;
1098 }
John McCall71c758d2011-09-10 09:17:20 +00001099 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001100 else {
1101 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1102 if (!setPropertyFn) {
1103 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1104 return;
1105 }
1106 }
1107
John McCall71c758d2011-09-10 09:17:20 +00001108 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1109 // <is-atomic>, <is-copy>).
1110 llvm::Value *cmd =
1111 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1112 llvm::Value *self =
1113 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1114 llvm::Value *ivarOffset =
1115 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1116 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1117 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1118
1119 CallArgList args;
1120 args.add(RValue::get(self), getContext().getObjCIdType());
1121 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001122 if (setOptimizedPropertyFn) {
1123 args.add(RValue::get(arg), getContext().getObjCIdType());
1124 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1125 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1126 FunctionType::ExtInfo(),
1127 RequiredArgs::All),
1128 setOptimizedPropertyFn, ReturnValueSlot(), args);
1129 } else {
1130 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1131 args.add(RValue::get(arg), getContext().getObjCIdType());
1132 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1133 getContext().BoolTy);
1134 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1135 getContext().BoolTy);
1136 // FIXME: We shouldn't need to get the function info here, the runtime
1137 // already should have computed it to build the function.
1138 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1139 FunctionType::ExtInfo(),
1140 RequiredArgs::All),
1141 setPropertyFn, ReturnValueSlot(), args);
1142 }
1143
John McCall71c758d2011-09-10 09:17:20 +00001144 return;
1145 }
1146
John McCall1e1f4872011-09-13 03:34:09 +00001147 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001148 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001149 return;
John McCall1e1f4872011-09-13 03:34:09 +00001150
1151 case PropertyImplStrategy::Expression:
1152 break;
John McCall71c758d2011-09-10 09:17:20 +00001153 }
1154
1155 // Otherwise, fake up some ASTs and emit a normal assignment.
1156 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001157 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1158 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001159 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1160 selfDecl->getType(), CK_LValueToRValue, &self,
1161 VK_RValue);
1162 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1163 SourceLocation(), &selfLoad, true, true);
1164
1165 ParmVarDecl *argDecl = *setterMethod->param_begin();
1166 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001167 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001168 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1169 argType.getUnqualifiedType(), CK_LValueToRValue,
1170 &arg, VK_RValue);
1171
1172 // The property type can differ from the ivar type in some situations with
1173 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1174 // The following absurdity is just to ensure well-formed IR.
1175 CastKind argCK = CK_NoOp;
1176 if (ivarRef.getType()->isObjCObjectPointerType()) {
1177 if (argLoad.getType()->isObjCObjectPointerType())
1178 argCK = CK_BitCast;
1179 else if (argLoad.getType()->isBlockPointerType())
1180 argCK = CK_BlockPointerToObjCPointerCast;
1181 else
1182 argCK = CK_CPointerToObjCPointerCast;
1183 } else if (ivarRef.getType()->isBlockPointerType()) {
1184 if (argLoad.getType()->isBlockPointerType())
1185 argCK = CK_BitCast;
1186 else
1187 argCK = CK_AnyPointerToBlockPointerCast;
1188 } else if (ivarRef.getType()->isPointerType()) {
1189 argCK = CK_BitCast;
1190 }
1191 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1192 ivarRef.getType(), argCK, &argLoad,
1193 VK_RValue);
1194 Expr *finalArg = &argLoad;
1195 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1196 argLoad.getType()))
1197 finalArg = &argCast;
1198
1199
1200 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1201 ivarRef.getType(), VK_RValue, OK_Ordinary,
1202 SourceLocation());
1203 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001204}
1205
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001206/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +00001207/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1208/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001209void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1210 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001211 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001212 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001213 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1214 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1215 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +00001216 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001217
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001218 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001219
1220 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001221}
1222
John McCalle81ac692011-03-22 07:05:39 +00001223namespace {
John McCall9928c482011-07-12 16:41:08 +00001224 struct DestroyIvar : EHScopeStack::Cleanup {
1225 private:
1226 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001227 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001228 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001229 bool useEHCleanupForArray;
1230 public:
1231 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1232 CodeGenFunction::Destroyer *destroyer,
1233 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001234 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001235 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001236
John McCallad346f42011-07-12 20:27:29 +00001237 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001238 LValue lvalue
1239 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1240 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001241 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001242 }
1243 };
1244}
1245
John McCall9928c482011-07-12 16:41:08 +00001246/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1247static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1248 llvm::Value *addr,
1249 QualType type) {
1250 llvm::Value *null = getNullForVariable(addr);
1251 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1252}
John McCallf85e1932011-06-15 23:02:42 +00001253
John McCalle81ac692011-03-22 07:05:39 +00001254static void emitCXXDestructMethod(CodeGenFunction &CGF,
1255 ObjCImplementationDecl *impl) {
1256 CodeGenFunction::RunCleanupsScope scope(CGF);
1257
1258 llvm::Value *self = CGF.LoadObjCSelf();
1259
Jordy Rosedb8264e2011-07-22 02:08:32 +00001260 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1261 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001262 ivar; ivar = ivar->getNextIvar()) {
1263 QualType type = ivar->getType();
1264
John McCalle81ac692011-03-22 07:05:39 +00001265 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001266 QualType::DestructionKind dtorKind = type.isDestructedType();
1267 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001268
John McCall9928c482011-07-12 16:41:08 +00001269 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001270
John McCall9928c482011-07-12 16:41:08 +00001271 // Use a call to objc_storeStrong to destroy strong ivars, for the
1272 // general benefit of the tools.
1273 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001274 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001275
John McCall9928c482011-07-12 16:41:08 +00001276 // Otherwise use the default for the destruction kind.
1277 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001278 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001279 }
John McCall9928c482011-07-12 16:41:08 +00001280
1281 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1282
1283 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1284 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001285 }
1286
1287 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1288}
1289
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001290void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1291 ObjCMethodDecl *MD,
1292 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001293 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001294 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001295
1296 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001297 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001298 // Suppress the final autorelease in ARC.
1299 AutoreleaseResult = false;
1300
Chris Lattner5f9e2722011-07-23 10:55:15 +00001301 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001302 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1303 E = IMP->init_end(); B != E; ++B) {
1304 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001305 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001306 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001307 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1308 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001309 EmitAggExpr(IvarInit->getInit(),
1310 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001311 AggValueSlot::DoesNotNeedGCBarriers,
1312 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001313 }
1314 // constructor returns 'self'.
1315 CodeGenTypes &Types = CGM.getTypes();
1316 QualType IdTy(CGM.getContext().getObjCIdType());
1317 llvm::Value *SelfAsId =
1318 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1319 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001320
1321 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001322 } else {
John McCalle81ac692011-03-22 07:05:39 +00001323 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001324 }
1325 FinishFunction();
1326}
1327
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001328bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1329 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1330 it++; it++;
1331 const ABIArgInfo &AI = it->info;
1332 // FIXME. Is this sufficient check?
1333 return (AI.getKind() == ABIArgInfo::Indirect);
1334}
1335
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001336bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001337 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001338 return false;
1339 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1340 return FDTTy->getDecl()->hasObjectMember();
1341 return false;
1342}
1343
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001344llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001345 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1346 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001347}
1348
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001349QualType CodeGenFunction::TypeOfSelfObject() {
1350 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1351 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001352 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1353 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001354 return PTy->getPointeeType();
1355}
1356
Chris Lattner74391b42009-03-22 21:03:39 +00001357void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001358 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001359 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001360
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001361 if (!EnumerationMutationFn) {
1362 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1363 return;
1364 }
1365
Devang Patelbcbd03a2011-01-19 01:36:36 +00001366 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001367 if (DI)
1368 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001369
Devang Patel9d99f2d2011-06-13 23:15:32 +00001370 // The local variable comes into scope immediately.
1371 AutoVarEmission variable = AutoVarEmission::invalid();
1372 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1373 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1374
John McCalld88687f2011-01-07 01:49:06 +00001375 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001376
Anders Carlssonf484c312008-08-31 02:33:12 +00001377 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001378 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001379 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001380 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Anders Carlssonf484c312008-08-31 02:33:12 +00001382 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001383 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001384
John McCalld88687f2011-01-07 01:49:06 +00001385 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001386 IdentifierInfo *II[] = {
1387 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1388 &CGM.getContext().Idents.get("objects"),
1389 &CGM.getContext().Idents.get("count")
1390 };
1391 Selector FastEnumSel =
1392 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001393
1394 QualType ItemsTy =
1395 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001396 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001397 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001398 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001399
John McCall990567c2011-07-27 01:07:15 +00001400 // Emit the collection pointer. In ARC, we do a retain.
1401 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001402 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001403 Collection = EmitARCRetainScalarExpr(S.getCollection());
1404
1405 // Enter a cleanup to do the release.
1406 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1407 } else {
1408 Collection = EmitScalarExpr(S.getCollection());
1409 }
Mike Stump1eb44332009-09-09 15:08:12 +00001410
John McCall4b302d32011-08-05 00:14:38 +00001411 // The 'continue' label needs to appear within the cleanup for the
1412 // collection object.
1413 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1414
John McCalld88687f2011-01-07 01:49:06 +00001415 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001416 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001417
1418 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001419 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001420
John McCalld88687f2011-01-07 01:49:06 +00001421 // The second argument is a temporary array with space for NumItems
1422 // pointers. We'll actually be loading elements from the array
1423 // pointer written into the control state; this buffer is so that
1424 // collections that *aren't* backed by arrays can still queue up
1425 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001426 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001427
John McCalld88687f2011-01-07 01:49:06 +00001428 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001429 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001430 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001431 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
John McCalld88687f2011-01-07 01:49:06 +00001433 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001434 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001435 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001436 getContext().UnsignedLongTy,
1437 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001438 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001439
John McCalld88687f2011-01-07 01:49:06 +00001440 // The initial number of objects that were returned in the buffer.
1441 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001442
John McCalld88687f2011-01-07 01:49:06 +00001443 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1444 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001445
John McCalld88687f2011-01-07 01:49:06 +00001446 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001447
John McCalld88687f2011-01-07 01:49:06 +00001448 // If the limit pointer was zero to begin with, the collection is
1449 // empty; skip all this.
1450 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1451 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001452
John McCalld88687f2011-01-07 01:49:06 +00001453 // Otherwise, initialize the loop.
1454 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001455
John McCalld88687f2011-01-07 01:49:06 +00001456 // Save the initial mutations value. This is the value at an
1457 // address that was written into the state object by
1458 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001459 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001460 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001461 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001462 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001463
John McCalld88687f2011-01-07 01:49:06 +00001464 llvm::Value *initialMutations =
1465 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001466
John McCalld88687f2011-01-07 01:49:06 +00001467 // Start looping. This is the point we return to whenever we have a
1468 // fresh, non-empty batch of objects.
1469 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1470 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001471
John McCalld88687f2011-01-07 01:49:06 +00001472 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001473 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001474 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001475
John McCalld88687f2011-01-07 01:49:06 +00001476 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001477 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001478 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
John McCalld88687f2011-01-07 01:49:06 +00001480 // Check whether the mutations value has changed from where it was
1481 // at start. StateMutationsPtr should actually be invariant between
1482 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001483 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001484 llvm::Value *currentMutations
1485 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001486
John McCalld88687f2011-01-07 01:49:06 +00001487 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001488 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001489
John McCalld88687f2011-01-07 01:49:06 +00001490 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1491 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
John McCalld88687f2011-01-07 01:49:06 +00001493 // If so, call the enumeration-mutation function.
1494 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001495 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001496 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001497 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001498 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001499 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001500 // FIXME: We shouldn't need to get the function info here, the runtime already
1501 // should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +00001502 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1503 FunctionType::ExtInfo(),
1504 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001505 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
John McCalld88687f2011-01-07 01:49:06 +00001507 // Otherwise, or if the mutation function returns, just continue.
1508 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
John McCalld88687f2011-01-07 01:49:06 +00001510 // Initialize the element variable.
1511 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001512 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001513 LValue elementLValue;
1514 QualType elementType;
1515 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001516 // Initialize the variable, in case it's a __block variable or something.
1517 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001518
John McCall57b3b6a2011-02-22 07:16:58 +00001519 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001520 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001521 VK_LValue, SourceLocation());
1522 elementLValue = EmitLValue(&tempDRE);
1523 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001524 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001525
1526 if (D->isARCPseudoStrong())
1527 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001528 } else {
1529 elementLValue = LValue(); // suppress warning
1530 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001531 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001532 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001533 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001534
1535 // Fetch the buffer out of the enumeration state.
1536 // TODO: this pointer should actually be invariant between
1537 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001538 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001539 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001540 llvm::Value *EnumStateItems =
1541 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001542
John McCalld88687f2011-01-07 01:49:06 +00001543 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001544 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001545 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1546 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001547
John McCalld88687f2011-01-07 01:49:06 +00001548 // Cast that value to the right type.
1549 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1550 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001551
John McCalld88687f2011-01-07 01:49:06 +00001552 // Make sure we have an l-value. Yes, this gets evaluated every
1553 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001554 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001555 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001556 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001557 } else {
1558 EmitScalarInit(CurrentItem, elementLValue);
1559 }
Mike Stump1eb44332009-09-09 15:08:12 +00001560
John McCall57b3b6a2011-02-22 07:16:58 +00001561 // If we do have an element variable, this assignment is the end of
1562 // its initialization.
1563 if (elementIsVariable)
1564 EmitAutoVarCleanups(variable);
1565
John McCalld88687f2011-01-07 01:49:06 +00001566 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001567 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001568 {
1569 RunCleanupsScope Scope(*this);
1570 EmitStmt(S.getBody());
1571 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001572 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001573
John McCalld88687f2011-01-07 01:49:06 +00001574 // Destroy the element variable now.
1575 elementVariableScope.ForceCleanup();
1576
1577 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001578 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001579
John McCalld88687f2011-01-07 01:49:06 +00001580 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001581
John McCalld88687f2011-01-07 01:49:06 +00001582 // First we check in the local buffer.
1583 llvm::Value *indexPlusOne
1584 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001585
John McCalld88687f2011-01-07 01:49:06 +00001586 // If we haven't overrun the buffer yet, we can continue.
1587 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1588 LoopBodyBB, FetchMoreBB);
1589
1590 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1591 count->addIncoming(count, AfterBody.getBlock());
1592
1593 // Otherwise, we have to fetch more elements.
1594 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
1596 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001597 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001598 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001599 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001600 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001601
John McCalld88687f2011-01-07 01:49:06 +00001602 // If we got a zero count, we're done.
1603 llvm::Value *refetchCount = CountRV.getScalarVal();
1604
1605 // (note that the message send might split FetchMoreBB)
1606 index->addIncoming(zero, Builder.GetInsertBlock());
1607 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1608
1609 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1610 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Anders Carlssonf484c312008-08-31 02:33:12 +00001612 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001613 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001614
John McCall57b3b6a2011-02-22 07:16:58 +00001615 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001616 // If the element was not a declaration, set it to be null.
1617
John McCalld88687f2011-01-07 01:49:06 +00001618 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1619 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001620 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001621 }
1622
Eric Christopher73fb3502011-10-13 21:45:18 +00001623 if (DI)
1624 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001625
John McCall990567c2011-07-27 01:07:15 +00001626 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001627 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001628 PopCleanupBlock();
1629
John McCallff8e1152010-07-23 21:56:41 +00001630 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001631}
1632
Mike Stump1eb44332009-09-09 15:08:12 +00001633void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001634 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001635}
1636
Mike Stump1eb44332009-09-09 15:08:12 +00001637void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001638 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1639}
1640
Chris Lattner10cac6f2008-11-15 21:26:17 +00001641void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001642 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001643 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001644}
1645
John McCall33e56f32011-09-10 06:18:15 +00001646/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001647/// primitive retain.
1648llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1649 llvm::Value *value) {
1650 return EmitARCRetain(type, value);
1651}
1652
1653namespace {
1654 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001655 CallObjCRelease(llvm::Value *object) : object(object) {}
1656 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001657
John McCallad346f42011-07-12 20:27:29 +00001658 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001659 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001660 }
1661 };
1662}
1663
John McCall33e56f32011-09-10 06:18:15 +00001664/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001665/// release at the end of the full-expression.
1666llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1667 llvm::Value *object) {
1668 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001669 // conditional.
1670 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001671 return object;
1672}
1673
1674llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1675 llvm::Value *value) {
1676 return EmitARCRetainAutorelease(type, value);
1677}
1678
1679
1680static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001681 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001682 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001683 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1684
1685 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1686 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001687 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001688 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1689 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1690
1691 return fn;
1692}
1693
1694/// Perform an operation having the signature
1695/// i8* (i8*)
1696/// where a null input causes a no-op and returns null.
1697static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1698 llvm::Value *value,
1699 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001700 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001701 if (isa<llvm::ConstantPointerNull>(value)) return value;
1702
1703 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001704 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001705 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001706 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1707 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1708 }
1709
1710 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001711 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001712 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1713
1714 // Call the function.
1715 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1716 call->setDoesNotThrow();
1717
1718 // Cast the result back to the original type.
1719 return CGF.Builder.CreateBitCast(call, origType);
1720}
1721
1722/// Perform an operation having the following signature:
1723/// i8* (i8**)
1724static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1725 llvm::Value *addr,
1726 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001727 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001728 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001729 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001730 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001731 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1732 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1733 }
1734
1735 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001736 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001737 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1738
1739 // Call the function.
1740 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1741 call->setDoesNotThrow();
1742
1743 // Cast the result back to a dereference of the original type.
1744 llvm::Value *result = call;
1745 if (origType != CGF.Int8PtrPtrTy)
1746 result = CGF.Builder.CreateBitCast(result,
1747 cast<llvm::PointerType>(origType)->getElementType());
1748
1749 return result;
1750}
1751
1752/// Perform an operation having the following signature:
1753/// i8* (i8**, i8*)
1754static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1755 llvm::Value *addr,
1756 llvm::Value *value,
1757 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001758 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001759 bool ignored) {
1760 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1761 == value->getType());
1762
1763 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001764 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001765
Chris Lattner2acc6e32011-07-18 04:24:23 +00001766 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001767 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1768 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1769 }
1770
Chris Lattner2acc6e32011-07-18 04:24:23 +00001771 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001772
1773 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1774 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1775
1776 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1777 result->setDoesNotThrow();
1778
1779 if (ignored) return 0;
1780
1781 return CGF.Builder.CreateBitCast(result, origType);
1782}
1783
1784/// Perform an operation having the following signature:
1785/// void (i8**, i8**)
1786static void emitARCCopyOperation(CodeGenFunction &CGF,
1787 llvm::Value *dst,
1788 llvm::Value *src,
1789 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001790 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001791 assert(dst->getType() == src->getType());
1792
1793 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001794 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001795 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001796 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1797 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1798 }
1799
1800 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1801 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1802
1803 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1804 result->setDoesNotThrow();
1805}
1806
1807/// Produce the code to do a retain. Based on the type, calls one of:
1808/// call i8* @objc_retain(i8* %value)
1809/// call i8* @objc_retainBlock(i8* %value)
1810llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1811 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001812 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001813 else
1814 return EmitARCRetainNonBlock(value);
1815}
1816
1817/// Retain the given object, with normal retain semantics.
1818/// call i8* @objc_retain(i8* %value)
1819llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1820 return emitARCValueOperation(*this, value,
1821 CGM.getARCEntrypoints().objc_retain,
1822 "objc_retain");
1823}
1824
1825/// Retain the given block, with _Block_copy semantics.
1826/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001827///
1828/// \param mandatory - If false, emit the call with metadata
1829/// indicating that it's okay for the optimizer to eliminate this call
1830/// if it can prove that the block never escapes except down the stack.
1831llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1832 bool mandatory) {
1833 llvm::Value *result
1834 = emitARCValueOperation(*this, value,
1835 CGM.getARCEntrypoints().objc_retainBlock,
1836 "objc_retainBlock");
1837
1838 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1839 // tell the optimizer that it doesn't need to do this copy if the
1840 // block doesn't escape, where being passed as an argument doesn't
1841 // count as escaping.
1842 if (!mandatory && isa<llvm::Instruction>(result)) {
1843 llvm::CallInst *call
1844 = cast<llvm::CallInst>(result->stripPointerCasts());
1845 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1846
1847 SmallVector<llvm::Value*,1> args;
1848 call->setMetadata("clang.arc.copy_on_escape",
1849 llvm::MDNode::get(Builder.getContext(), args));
1850 }
1851
1852 return result;
John McCallf85e1932011-06-15 23:02:42 +00001853}
1854
1855/// Retain the given object which is the result of a function call.
1856/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1857///
1858/// Yes, this function name is one character away from a different
1859/// call with completely different semantics.
1860llvm::Value *
1861CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1862 // Fetch the void(void) inline asm which marks that we're going to
1863 // retain the autoreleased return value.
1864 llvm::InlineAsm *&marker
1865 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1866 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001867 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001868 = CGM.getTargetCodeGenInfo()
1869 .getARCRetainAutoreleasedReturnValueMarker();
1870
1871 // If we have an empty assembly string, there's nothing to do.
1872 if (assembly.empty()) {
1873
1874 // Otherwise, at -O0, build an inline asm that we're going to call
1875 // in a moment.
1876 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1877 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001878 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001879
1880 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1881
1882 // If we're at -O1 and above, we don't want to litter the code
1883 // with this marker yet, so leave a breadcrumb for the ARC
1884 // optimizer to pick up.
1885 } else {
1886 llvm::NamedMDNode *metadata =
1887 CGM.getModule().getOrInsertNamedMetadata(
1888 "clang.arc.retainAutoreleasedReturnValueMarker");
1889 assert(metadata->getNumOperands() <= 1);
1890 if (metadata->getNumOperands() == 0) {
1891 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001892 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001893 }
1894 }
1895 }
1896
1897 // Call the marker asm if we made one, which we do only at -O0.
1898 if (marker) Builder.CreateCall(marker);
1899
1900 return emitARCValueOperation(*this, value,
1901 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1902 "objc_retainAutoreleasedReturnValue");
1903}
1904
1905/// Release the given object.
1906/// call void @objc_release(i8* %value)
1907void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1908 if (isa<llvm::ConstantPointerNull>(value)) return;
1909
1910 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1911 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001912 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001913 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001914 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1915 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1916 }
1917
1918 // Cast the argument to 'id'.
1919 value = Builder.CreateBitCast(value, Int8PtrTy);
1920
1921 // Call objc_release.
1922 llvm::CallInst *call = Builder.CreateCall(fn, value);
1923 call->setDoesNotThrow();
1924
1925 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001926 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001927 call->setMetadata("clang.imprecise_release",
1928 llvm::MDNode::get(Builder.getContext(), args));
1929 }
1930}
1931
1932/// Store into a strong object. Always calls this:
1933/// call void @objc_storeStrong(i8** %addr, i8* %value)
1934llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1935 llvm::Value *value,
1936 bool ignored) {
1937 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1938 == value->getType());
1939
1940 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1941 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001942 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001943 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001944 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1945 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1946 }
1947
1948 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1949 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1950
1951 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1952
1953 if (ignored) return 0;
1954 return value;
1955}
1956
1957/// Store into a strong object. Sometimes calls this:
1958/// call void @objc_storeStrong(i8** %addr, i8* %value)
1959/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001960llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001961 llvm::Value *newValue,
1962 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001963 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001964 bool isBlock = type->isBlockPointerType();
1965
1966 // Use a store barrier at -O0 unless this is a block type or the
1967 // lvalue is inadequately aligned.
1968 if (shouldUseFusedARCCalls() &&
1969 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001970 (dst.getAlignment().isZero() ||
1971 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001972 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1973 }
1974
1975 // Otherwise, split it out.
1976
1977 // Retain the new value.
1978 newValue = EmitARCRetain(type, newValue);
1979
1980 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001981 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001982
1983 // Store. We do this before the release so that any deallocs won't
1984 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001985 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001986
1987 // Finally, release the old value.
1988 EmitARCRelease(oldValue, /*precise*/ false);
1989
1990 return newValue;
1991}
1992
1993/// Autorelease the given object.
1994/// call i8* @objc_autorelease(i8* %value)
1995llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1996 return emitARCValueOperation(*this, value,
1997 CGM.getARCEntrypoints().objc_autorelease,
1998 "objc_autorelease");
1999}
2000
2001/// Autorelease the given object.
2002/// call i8* @objc_autoreleaseReturnValue(i8* %value)
2003llvm::Value *
2004CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2005 return emitARCValueOperation(*this, value,
2006 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2007 "objc_autoreleaseReturnValue");
2008}
2009
2010/// Do a fused retain/autorelease of the given object.
2011/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
2012llvm::Value *
2013CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2014 return emitARCValueOperation(*this, value,
2015 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2016 "objc_retainAutoreleaseReturnValue");
2017}
2018
2019/// Do a fused retain/autorelease of the given object.
2020/// call i8* @objc_retainAutorelease(i8* %value)
2021/// or
2022/// %retain = call i8* @objc_retainBlock(i8* %value)
2023/// call i8* @objc_autorelease(i8* %retain)
2024llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2025 llvm::Value *value) {
2026 if (!type->isBlockPointerType())
2027 return EmitARCRetainAutoreleaseNonBlock(value);
2028
2029 if (isa<llvm::ConstantPointerNull>(value)) return value;
2030
Chris Lattner2acc6e32011-07-18 04:24:23 +00002031 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002032 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002033 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002034 value = EmitARCAutorelease(value);
2035 return Builder.CreateBitCast(value, origType);
2036}
2037
2038/// Do a fused retain/autorelease of the given object.
2039/// call i8* @objc_retainAutorelease(i8* %value)
2040llvm::Value *
2041CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2042 return emitARCValueOperation(*this, value,
2043 CGM.getARCEntrypoints().objc_retainAutorelease,
2044 "objc_retainAutorelease");
2045}
2046
2047/// i8* @objc_loadWeak(i8** %addr)
2048/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2049llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2050 return emitARCLoadOperation(*this, addr,
2051 CGM.getARCEntrypoints().objc_loadWeak,
2052 "objc_loadWeak");
2053}
2054
2055/// i8* @objc_loadWeakRetained(i8** %addr)
2056llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2057 return emitARCLoadOperation(*this, addr,
2058 CGM.getARCEntrypoints().objc_loadWeakRetained,
2059 "objc_loadWeakRetained");
2060}
2061
2062/// i8* @objc_storeWeak(i8** %addr, i8* %value)
2063/// Returns %value.
2064llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2065 llvm::Value *value,
2066 bool ignored) {
2067 return emitARCStoreOperation(*this, addr, value,
2068 CGM.getARCEntrypoints().objc_storeWeak,
2069 "objc_storeWeak", ignored);
2070}
2071
2072/// i8* @objc_initWeak(i8** %addr, i8* %value)
2073/// Returns %value. %addr is known to not have a current weak entry.
2074/// Essentially equivalent to:
2075/// *addr = nil; objc_storeWeak(addr, value);
2076void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2077 // If we're initializing to null, just write null to memory; no need
2078 // to get the runtime involved. But don't do this if optimization
2079 // is enabled, because accounting for this would make the optimizer
2080 // much more complicated.
2081 if (isa<llvm::ConstantPointerNull>(value) &&
2082 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2083 Builder.CreateStore(value, addr);
2084 return;
2085 }
2086
2087 emitARCStoreOperation(*this, addr, value,
2088 CGM.getARCEntrypoints().objc_initWeak,
2089 "objc_initWeak", /*ignored*/ true);
2090}
2091
2092/// void @objc_destroyWeak(i8** %addr)
2093/// Essentially objc_storeWeak(addr, nil).
2094void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2095 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2096 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002097 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002098 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002099 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2100 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2101 }
2102
2103 // Cast the argument to 'id*'.
2104 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2105
2106 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2107 call->setDoesNotThrow();
2108}
2109
2110/// void @objc_moveWeak(i8** %dest, i8** %src)
2111/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2112/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2113void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2114 emitARCCopyOperation(*this, dst, src,
2115 CGM.getARCEntrypoints().objc_moveWeak,
2116 "objc_moveWeak");
2117}
2118
2119/// void @objc_copyWeak(i8** %dest, i8** %src)
2120/// Disregards the current value in %dest. Essentially
2121/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2122void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2123 emitARCCopyOperation(*this, dst, src,
2124 CGM.getARCEntrypoints().objc_copyWeak,
2125 "objc_copyWeak");
2126}
2127
2128/// Produce the code to do a objc_autoreleasepool_push.
2129/// call i8* @objc_autoreleasePoolPush(void)
2130llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2131 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2132 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002133 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002134 llvm::FunctionType::get(Int8PtrTy, false);
2135 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2136 }
2137
2138 llvm::CallInst *call = Builder.CreateCall(fn);
2139 call->setDoesNotThrow();
2140
2141 return call;
2142}
2143
2144/// Produce the code to do a primitive release.
2145/// call void @objc_autoreleasePoolPop(i8* %ptr)
2146void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2147 assert(value->getType() == Int8PtrTy);
2148
2149 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2150 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002151 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002152 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002153 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2154
2155 // We don't want to use a weak import here; instead we should not
2156 // fall into this path.
2157 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2158 }
2159
2160 llvm::CallInst *call = Builder.CreateCall(fn, value);
2161 call->setDoesNotThrow();
2162}
2163
2164/// Produce the code to do an MRR version objc_autoreleasepool_push.
2165/// Which is: [[NSAutoreleasePool alloc] init];
2166/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2167/// init is declared as: - (id) init; in its NSObject super class.
2168///
2169llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2170 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2171 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2172 // [NSAutoreleasePool alloc]
2173 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2174 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2175 CallArgList Args;
2176 RValue AllocRV =
2177 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2178 getContext().getObjCIdType(),
2179 AllocSel, Receiver, Args);
2180
2181 // [Receiver init]
2182 Receiver = AllocRV.getScalarVal();
2183 II = &CGM.getContext().Idents.get("init");
2184 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2185 RValue InitRV =
2186 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2187 getContext().getObjCIdType(),
2188 InitSel, Receiver, Args);
2189 return InitRV.getScalarVal();
2190}
2191
2192/// Produce the code to do a primitive release.
2193/// [tmp drain];
2194void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2195 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2196 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2197 CallArgList Args;
2198 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2199 getContext().VoidTy, DrainSel, Arg, Args);
2200}
2201
John McCallbdc4d802011-07-09 01:37:26 +00002202void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2203 llvm::Value *addr,
2204 QualType type) {
2205 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2206 CGF.EmitARCRelease(ptr, /*precise*/ true);
2207}
2208
2209void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2210 llvm::Value *addr,
2211 QualType type) {
2212 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2213 CGF.EmitARCRelease(ptr, /*precise*/ false);
2214}
2215
2216void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2217 llvm::Value *addr,
2218 QualType type) {
2219 CGF.EmitARCDestroyWeak(addr);
2220}
2221
John McCallf85e1932011-06-15 23:02:42 +00002222namespace {
John McCallf85e1932011-06-15 23:02:42 +00002223 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2224 llvm::Value *Token;
2225
2226 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2227
John McCallad346f42011-07-12 20:27:29 +00002228 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002229 CGF.EmitObjCAutoreleasePoolPop(Token);
2230 }
2231 };
2232 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2233 llvm::Value *Token;
2234
2235 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2236
John McCallad346f42011-07-12 20:27:29 +00002237 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002238 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2239 }
2240 };
2241}
2242
2243void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002244 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002245 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2246 else
2247 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2248}
2249
John McCallf85e1932011-06-15 23:02:42 +00002250static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2251 LValue lvalue,
2252 QualType type) {
2253 switch (type.getObjCLifetime()) {
2254 case Qualifiers::OCL_None:
2255 case Qualifiers::OCL_ExplicitNone:
2256 case Qualifiers::OCL_Strong:
2257 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002258 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002259 false);
2260
2261 case Qualifiers::OCL_Weak:
2262 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2263 true);
2264 }
2265
2266 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002267}
2268
2269static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2270 const Expr *e) {
2271 e = e->IgnoreParens();
2272 QualType type = e->getType();
2273
John McCall21480112011-08-30 00:57:29 +00002274 // If we're loading retained from a __strong xvalue, we can avoid
2275 // an extra retain/release pair by zeroing out the source of this
2276 // "move" operation.
2277 if (e->isXValue() &&
2278 !type.isConstQualified() &&
2279 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2280 // Emit the lvalue.
2281 LValue lv = CGF.EmitLValue(e);
2282
2283 // Load the object pointer.
2284 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2285
2286 // Set the source pointer to NULL.
2287 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2288
2289 return TryEmitResult(result, true);
2290 }
2291
John McCallf85e1932011-06-15 23:02:42 +00002292 // As a very special optimization, in ARC++, if the l-value is the
2293 // result of a non-volatile assignment, do a simple retain of the
2294 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002295 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002296 !type.isVolatileQualified() &&
2297 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2298 isa<BinaryOperator>(e) &&
2299 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2300 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2301
2302 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2303}
2304
2305static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2306 llvm::Value *value);
2307
2308/// Given that the given expression is some sort of call (which does
2309/// not return retained), emit a retain following it.
2310static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2311 llvm::Value *value = CGF.EmitScalarExpr(e);
2312 return emitARCRetainAfterCall(CGF, value);
2313}
2314
2315static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2316 llvm::Value *value) {
2317 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2318 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2319
2320 // Place the retain immediately following the call.
2321 CGF.Builder.SetInsertPoint(call->getParent(),
2322 ++llvm::BasicBlock::iterator(call));
2323 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2324
2325 CGF.Builder.restoreIP(ip);
2326 return value;
2327 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2328 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2329
2330 // Place the retain at the beginning of the normal destination block.
2331 llvm::BasicBlock *BB = invoke->getNormalDest();
2332 CGF.Builder.SetInsertPoint(BB, BB->begin());
2333 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2334
2335 CGF.Builder.restoreIP(ip);
2336 return value;
2337
2338 // Bitcasts can arise because of related-result returns. Rewrite
2339 // the operand.
2340 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2341 llvm::Value *operand = bitcast->getOperand(0);
2342 operand = emitARCRetainAfterCall(CGF, operand);
2343 bitcast->setOperand(0, operand);
2344 return bitcast;
2345
2346 // Generic fall-back case.
2347 } else {
2348 // Retain using the non-block variant: we never need to do a copy
2349 // of a block that's been returned to us.
2350 return CGF.EmitARCRetainNonBlock(value);
2351 }
2352}
2353
John McCalldc05b112011-09-10 01:16:55 +00002354/// Determine whether it might be important to emit a separate
2355/// objc_retain_block on the result of the given expression, or
2356/// whether it's okay to just emit it in a +1 context.
2357static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2358 assert(e->getType()->isBlockPointerType());
2359 e = e->IgnoreParens();
2360
2361 // For future goodness, emit block expressions directly in +1
2362 // contexts if we can.
2363 if (isa<BlockExpr>(e))
2364 return false;
2365
2366 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2367 switch (cast->getCastKind()) {
2368 // Emitting these operations in +1 contexts is goodness.
2369 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002370 case CK_ARCReclaimReturnedObject:
2371 case CK_ARCConsumeObject:
2372 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002373 return false;
2374
2375 // These operations preserve a block type.
2376 case CK_NoOp:
2377 case CK_BitCast:
2378 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2379
2380 // These operations are known to be bad (or haven't been considered).
2381 case CK_AnyPointerToBlockPointerCast:
2382 default:
2383 return true;
2384 }
2385 }
2386
2387 return true;
2388}
2389
John McCall4b9c2d22011-11-06 09:01:30 +00002390/// Try to emit a PseudoObjectExpr at +1.
2391///
2392/// This massively duplicates emitPseudoObjectRValue.
2393static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2394 const PseudoObjectExpr *E) {
2395 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2396
2397 // Find the result expression.
2398 const Expr *resultExpr = E->getResultExpr();
2399 assert(resultExpr);
2400 TryEmitResult result;
2401
2402 for (PseudoObjectExpr::const_semantics_iterator
2403 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2404 const Expr *semantic = *i;
2405
2406 // If this semantic expression is an opaque value, bind it
2407 // to the result of its source expression.
2408 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2409 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2410 OVMA opaqueData;
2411
2412 // If this semantic is the result of the pseudo-object
2413 // expression, try to evaluate the source as +1.
2414 if (ov == resultExpr) {
2415 assert(!OVMA::shouldBindAsLValue(ov));
2416 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2417 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2418
2419 // Otherwise, just bind it.
2420 } else {
2421 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2422 }
2423 opaques.push_back(opaqueData);
2424
2425 // Otherwise, if the expression is the result, evaluate it
2426 // and remember the result.
2427 } else if (semantic == resultExpr) {
2428 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2429
2430 // Otherwise, evaluate the expression in an ignored context.
2431 } else {
2432 CGF.EmitIgnoredExpr(semantic);
2433 }
2434 }
2435
2436 // Unbind all the opaques now.
2437 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2438 opaques[i].unbind(CGF);
2439
2440 return result;
2441}
2442
John McCallf85e1932011-06-15 23:02:42 +00002443static TryEmitResult
2444tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002445 // Look through cleanups.
2446 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002447 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002448 CodeGenFunction::RunCleanupsScope scope(CGF);
2449 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2450 }
2451
John McCallf85e1932011-06-15 23:02:42 +00002452 // The desired result type, if it differs from the type of the
2453 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002454 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002455
2456 while (true) {
2457 e = e->IgnoreParens();
2458
2459 // There's a break at the end of this if-chain; anything
2460 // that wants to keep looping has to explicitly continue.
2461 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2462 switch (ce->getCastKind()) {
2463 // No-op casts don't change the type, so we just ignore them.
2464 case CK_NoOp:
2465 e = ce->getSubExpr();
2466 continue;
2467
2468 case CK_LValueToRValue: {
2469 TryEmitResult loadResult
2470 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2471 if (resultType) {
2472 llvm::Value *value = loadResult.getPointer();
2473 value = CGF.Builder.CreateBitCast(value, resultType);
2474 loadResult.setPointer(value);
2475 }
2476 return loadResult;
2477 }
2478
2479 // These casts can change the type, so remember that and
2480 // soldier on. We only need to remember the outermost such
2481 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002482 case CK_CPointerToObjCPointerCast:
2483 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002484 case CK_AnyPointerToBlockPointerCast:
2485 case CK_BitCast:
2486 if (!resultType)
2487 resultType = CGF.ConvertType(ce->getType());
2488 e = ce->getSubExpr();
2489 assert(e->getType()->hasPointerRepresentation());
2490 continue;
2491
2492 // For consumptions, just emit the subexpression and thus elide
2493 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002494 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002495 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2496 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2497 return TryEmitResult(result, true);
2498 }
2499
John McCalldc05b112011-09-10 01:16:55 +00002500 // Block extends are net +0. Naively, we could just recurse on
2501 // the subexpression, but actually we need to ensure that the
2502 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002503 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002504 llvm::Value *result; // will be a +0 value
2505
2506 // If we can't safely assume the sub-expression will produce a
2507 // block-copied value, emit the sub-expression at +0.
2508 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2509 result = CGF.EmitScalarExpr(ce->getSubExpr());
2510
2511 // Otherwise, try to emit the sub-expression at +1 recursively.
2512 } else {
2513 TryEmitResult subresult
2514 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2515 result = subresult.getPointer();
2516
2517 // If that produced a retained value, just use that,
2518 // possibly casting down.
2519 if (subresult.getInt()) {
2520 if (resultType)
2521 result = CGF.Builder.CreateBitCast(result, resultType);
2522 return TryEmitResult(result, true);
2523 }
2524
2525 // Otherwise it's +0.
2526 }
2527
2528 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002529 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002530 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2531 return TryEmitResult(result, true);
2532 }
2533
John McCall7e5e5f42011-07-07 06:58:02 +00002534 // For reclaims, emit the subexpression as a retained call and
2535 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002536 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002537 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2538 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2539 return TryEmitResult(result, true);
2540 }
2541
John McCallf85e1932011-06-15 23:02:42 +00002542 default:
2543 break;
2544 }
2545
2546 // Skip __extension__.
2547 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2548 if (op->getOpcode() == UO_Extension) {
2549 e = op->getSubExpr();
2550 continue;
2551 }
2552
2553 // For calls and message sends, use the retained-call logic.
2554 // Delegate inits are a special case in that they're the only
2555 // returns-retained expression that *isn't* surrounded by
2556 // a consume.
2557 } else if (isa<CallExpr>(e) ||
2558 (isa<ObjCMessageExpr>(e) &&
2559 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2560 llvm::Value *result = emitARCRetainCall(CGF, e);
2561 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2562 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002563
2564 // Look through pseudo-object expressions.
2565 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2566 TryEmitResult result
2567 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2568 if (resultType) {
2569 llvm::Value *value = result.getPointer();
2570 value = CGF.Builder.CreateBitCast(value, resultType);
2571 result.setPointer(value);
2572 }
2573 return result;
John McCallf85e1932011-06-15 23:02:42 +00002574 }
2575
2576 // Conservatively halt the search at any other expression kind.
2577 break;
2578 }
2579
2580 // We didn't find an obvious production, so emit what we've got and
2581 // tell the caller that we didn't manage to retain.
2582 llvm::Value *result = CGF.EmitScalarExpr(e);
2583 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2584 return TryEmitResult(result, false);
2585}
2586
2587static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2588 LValue lvalue,
2589 QualType type) {
2590 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2591 llvm::Value *value = result.getPointer();
2592 if (!result.getInt())
2593 value = CGF.EmitARCRetain(type, value);
2594 return value;
2595}
2596
2597/// EmitARCRetainScalarExpr - Semantically equivalent to
2598/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2599/// best-effort attempt to peephole expressions that naturally produce
2600/// retained objects.
2601llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2602 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2603 llvm::Value *value = result.getPointer();
2604 if (!result.getInt())
2605 value = EmitARCRetain(e->getType(), value);
2606 return value;
2607}
2608
2609llvm::Value *
2610CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2611 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2612 llvm::Value *value = result.getPointer();
2613 if (result.getInt())
2614 value = EmitARCAutorelease(value);
2615 else
2616 value = EmitARCRetainAutorelease(e->getType(), value);
2617 return value;
2618}
2619
John McCall348f16f2011-10-04 06:23:45 +00002620llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2621 llvm::Value *result;
2622 bool doRetain;
2623
2624 if (shouldEmitSeparateBlockRetain(e)) {
2625 result = EmitScalarExpr(e);
2626 doRetain = true;
2627 } else {
2628 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2629 result = subresult.getPointer();
2630 doRetain = !subresult.getInt();
2631 }
2632
2633 if (doRetain)
2634 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2635 return EmitObjCConsumeObject(e->getType(), result);
2636}
2637
John McCall2b014d62011-10-01 10:32:24 +00002638llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2639 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002640 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002641 // Do so before running any cleanups for the full-expression.
2642 // tryEmitARCRetainScalarExpr does make an effort to do things
2643 // inside cleanups, but there are crazy cases like
2644 // @throw A().foo;
2645 // where a full retain+autorelease is required and would
2646 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002647 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2648 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002649 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002650 }
John McCall2b014d62011-10-01 10:32:24 +00002651
John McCall1a343eb2011-11-10 08:15:53 +00002652 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002653 return EmitARCRetainAutoreleaseScalarExpr(expr);
2654 }
2655
2656 // Otherwise, use the normal scalar-expression emission. The
2657 // exception machinery doesn't do anything special with the
2658 // exception like retaining it, so there's no safety associated with
2659 // only running cleanups after the throw has started, and when it
2660 // matters it tends to be substantially inferior code.
2661 return EmitScalarExpr(expr);
2662}
2663
John McCallf85e1932011-06-15 23:02:42 +00002664std::pair<LValue,llvm::Value*>
2665CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2666 bool ignored) {
2667 // Evaluate the RHS first.
2668 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2669 llvm::Value *value = result.getPointer();
2670
John McCallfb720812011-07-28 07:23:35 +00002671 bool hasImmediateRetain = result.getInt();
2672
2673 // If we didn't emit a retained object, and the l-value is of block
2674 // type, then we need to emit the block-retain immediately in case
2675 // it invalidates the l-value.
2676 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002677 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002678 hasImmediateRetain = true;
2679 }
2680
John McCallf85e1932011-06-15 23:02:42 +00002681 LValue lvalue = EmitLValue(e->getLHS());
2682
2683 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002684 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002685 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002686 EmitLoadOfScalar(lvalue);
2687 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002688 EmitARCRelease(oldValue, /*precise*/ false);
2689 } else {
John McCall545d9962011-06-25 02:11:03 +00002690 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002691 }
2692
2693 return std::pair<LValue,llvm::Value*>(lvalue, value);
2694}
2695
2696std::pair<LValue,llvm::Value*>
2697CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2698 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2699 LValue lvalue = EmitLValue(e->getLHS());
2700
Eli Friedman6da2c712011-12-03 04:14:32 +00002701 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002702
2703 return std::pair<LValue,llvm::Value*>(lvalue, value);
2704}
2705
2706void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2707 const ObjCAutoreleasePoolStmt &ARPS) {
2708 const Stmt *subStmt = ARPS.getSubStmt();
2709 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2710
2711 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002712 if (DI)
2713 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002714
2715 // Keep track of the current cleanup stack depth.
2716 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002717 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002718 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2719 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2720 } else {
2721 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2722 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2723 }
2724
2725 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2726 E = S.body_end(); I != E; ++I)
2727 EmitStmt(*I);
2728
Eric Christopher73fb3502011-10-13 21:45:18 +00002729 if (DI)
2730 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002731}
John McCall0c24c802011-06-24 23:21:27 +00002732
2733/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2734/// make sure it survives garbage collection until this point.
2735void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2736 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002737 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002738 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002739 llvm::Value *extender
2740 = llvm::InlineAsm::get(extenderType,
2741 /* assembly */ "",
2742 /* constraints */ "r",
2743 /* side effects */ true);
2744
2745 object = Builder.CreateBitCast(object, VoidPtrTy);
2746 Builder.CreateCall(extender, object)->setDoesNotThrow();
2747}
2748
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002749/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002750/// non-trivial copy assignment function, produce following helper function.
2751/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2752///
2753llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002754CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2755 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002756 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002757 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002758 return 0;
2759 QualType Ty = PID->getPropertyIvarDecl()->getType();
2760 if (!Ty->isRecordType())
2761 return 0;
2762 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002763 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002764 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002765 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002766 if (hasTrivialSetExpr(PID))
2767 return 0;
2768 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2769 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2770 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002771
2772 ASTContext &C = getContext();
2773 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002774 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002775 FunctionDecl *FD = FunctionDecl::Create(C,
2776 C.getTranslationUnitDecl(),
2777 SourceLocation(),
2778 SourceLocation(), II, C.VoidTy, 0,
2779 SC_Static,
2780 SC_None,
2781 false,
2782 true);
2783
2784 QualType DestTy = C.getPointerType(Ty);
2785 QualType SrcTy = Ty;
2786 SrcTy.addConst();
2787 SrcTy = C.getPointerType(SrcTy);
2788
2789 FunctionArgList args;
2790 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2791 args.push_back(&dstDecl);
2792 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2793 args.push_back(&srcDecl);
2794
2795 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002796 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2797 FunctionType::ExtInfo(),
2798 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002799
John McCallde5d3c72012-02-17 03:33:10 +00002800 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002801
2802 llvm::Function *Fn =
2803 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002804 "__assign_helper_atomic_property_", &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002805
2806 if (CGM.getModuleDebugInfo())
2807 DebugInfo = CGM.getModuleDebugInfo();
2808
2809
2810 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2811
John McCallf4b88a42012-03-10 09:33:50 +00002812 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2813 VK_RValue, SourceLocation());
2814 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2815 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002816
John McCallf4b88a42012-03-10 09:33:50 +00002817 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2818 VK_RValue, SourceLocation());
2819 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2820 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002821
John McCallf4b88a42012-03-10 09:33:50 +00002822 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002823 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002824 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2825 Args, 2, DestTy->getPointeeType(),
2826 VK_LValue, SourceLocation());
2827
2828 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002829
2830 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002831 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002832 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002833 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002834}
2835
2836llvm::Constant *
2837CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2838 const ObjCPropertyImplDecl *PID) {
2839 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002840 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002841 return 0;
2842 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2843 QualType Ty = PD->getType();
2844 if (!Ty->isRecordType())
2845 return 0;
2846 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2847 return 0;
2848 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002849
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002850 if (hasTrivialGetExpr(PID))
2851 return 0;
2852 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2853 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2854 return HelperFn;
2855
2856
2857 ASTContext &C = getContext();
2858 IdentifierInfo *II
2859 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2860 FunctionDecl *FD = FunctionDecl::Create(C,
2861 C.getTranslationUnitDecl(),
2862 SourceLocation(),
2863 SourceLocation(), II, C.VoidTy, 0,
2864 SC_Static,
2865 SC_None,
2866 false,
2867 true);
2868
2869 QualType DestTy = C.getPointerType(Ty);
2870 QualType SrcTy = Ty;
2871 SrcTy.addConst();
2872 SrcTy = C.getPointerType(SrcTy);
2873
2874 FunctionArgList args;
2875 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2876 args.push_back(&dstDecl);
2877 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2878 args.push_back(&srcDecl);
2879
2880 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002881 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2882 FunctionType::ExtInfo(),
2883 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002884
John McCallde5d3c72012-02-17 03:33:10 +00002885 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002886
2887 llvm::Function *Fn =
2888 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2889 "__copy_helper_atomic_property_", &CGM.getModule());
2890
2891 if (CGM.getModuleDebugInfo())
2892 DebugInfo = CGM.getModuleDebugInfo();
2893
2894
2895 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2896
John McCallf4b88a42012-03-10 09:33:50 +00002897 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002898 VK_RValue, SourceLocation());
2899
John McCallf4b88a42012-03-10 09:33:50 +00002900 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2901 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002902
2903 CXXConstructExpr *CXXConstExpr =
2904 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2905
2906 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002907 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002908 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2909 ++A;
2910
2911 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2912 A != AEnd; ++A)
2913 ConstructorArgs.push_back(*A);
2914
2915 CXXConstructExpr *TheCXXConstructExpr =
2916 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2917 CXXConstExpr->getConstructor(),
2918 CXXConstExpr->isElidable(),
2919 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002920 CXXConstExpr->hadMultipleCandidates(),
2921 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002922 CXXConstExpr->requiresZeroInitialization(),
2923 CXXConstExpr->getConstructionKind(), SourceRange());
2924
John McCallf4b88a42012-03-10 09:33:50 +00002925 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2926 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002927
John McCallf4b88a42012-03-10 09:33:50 +00002928 RValue DV = EmitAnyExpr(&DstExpr);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002929 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
2930 EmitAggExpr(TheCXXConstructExpr,
2931 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2932 AggValueSlot::IsDestructed,
2933 AggValueSlot::DoesNotNeedGCBarriers,
2934 AggValueSlot::IsNotAliased));
2935
2936 FinishFunction();
2937 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2938 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2939 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002940}
2941
Eli Friedmancae40c42012-02-28 01:08:45 +00002942llvm::Value *
2943CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2944 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002945 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2946 Selector CopySelector =
2947 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002948 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2949 Selector AutoreleaseSelector =
2950 getContext().Selectors.getNullarySelector(AutoreleaseID);
2951
2952 // Emit calls to retain/autorelease.
2953 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2954 llvm::Value *Val = Block;
2955 RValue Result;
2956 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002957 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002958 Val, CallArgList(), 0, 0);
2959 Val = Result.getScalarVal();
2960 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2961 Ty, AutoreleaseSelector,
2962 Val, CallArgList(), 0, 0);
2963 Val = Result.getScalarVal();
2964 return Val;
2965}
2966
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002967
Ted Kremenek2979ec72008-04-09 15:51:31 +00002968CGObjCRuntime::~CGObjCRuntime() {}