blob: 3f675627517a724ea9e1a2cf1dfb790011d18298 [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.
John McCall57cd1b82012-03-28 23:30:44 +0000888 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType,
889 /*volatile*/ false, 0, /*destIsCompleteObject*/ true);
John McCall1e1f4872011-09-13 03:34:09 +0000890 } else {
John McCallba3dd902011-07-22 05:23:13 +0000891 llvm::Value *value;
892 if (propType->isReferenceType()) {
893 value = LV.getAddress();
894 } else {
895 // We want to load and autoreleaseReturnValue ARC __weak ivars.
896 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000897 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000898
899 // Otherwise we want to do a simple load, suppressing the
900 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000901 } else {
John McCallba3dd902011-07-22 05:23:13 +0000902 value = EmitLoadOfLValue(LV).getScalarVal();
903 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000904 }
John McCallf85e1932011-06-15 23:02:42 +0000905
John McCallba3dd902011-07-22 05:23:13 +0000906 value = Builder.CreateBitCast(value, ConvertType(propType));
907 }
908
909 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000910 }
John McCall1e1f4872011-09-13 03:34:09 +0000911 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000912 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000913
John McCall1e1f4872011-09-13 03:34:09 +0000914 }
915 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000916}
917
John McCall41bdde92011-09-12 23:06:44 +0000918/// emitStructSetterCall - Call the runtime function to store the value
919/// from the first formal parameter into the given ivar.
920static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
921 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000922 // objc_copyStruct (&structIvar, &Arg,
923 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000924 CallArgList args;
925
926 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000927 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
928 CGF.LoadObjCSelf(), ivar, 0)
929 .getAddress();
930 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
931 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000932
933 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000934 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000935 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000936 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000937 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
938 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
939 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000940
941 // The third argument is the sizeof the type.
942 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000943 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
944 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000945
John McCall41bdde92011-09-12 23:06:44 +0000946 // The fourth argument is the 'isAtomic' flag.
947 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000948
John McCall41bdde92011-09-12 23:06:44 +0000949 // The fifth argument is the 'hasStrong' flag.
950 // FIXME: should this really always be false?
951 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
952
953 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000954 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
955 FunctionType::ExtInfo(),
956 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000957 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000958}
959
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000960/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
961/// the value from the first formal parameter into the given ivar, using
962/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
963static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
964 ObjCMethodDecl *OMD,
965 ObjCIvarDecl *ivar,
966 llvm::Constant *AtomicHelperFn) {
967 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
968 // AtomicHelperFn);
969 CallArgList args;
970
971 // The first argument is the address of the ivar.
972 llvm::Value *ivarAddr =
973 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
974 CGF.LoadObjCSelf(), ivar, 0).getAddress();
975 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
976 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
977
978 // The second argument is the address of the parameter variable.
979 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000980 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000981 VK_LValue, SourceLocation());
982 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
983 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
984 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
985
986 // Third argument is the helper function.
987 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
988
989 llvm::Value *copyCppAtomicObjectFn =
990 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000991 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
992 FunctionType::ExtInfo(),
993 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000994 copyCppAtomicObjectFn, ReturnValueSlot(), args);
995
996
997}
998
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000999
John McCall1e1f4872011-09-13 03:34:09 +00001000static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1001 Expr *setter = PID->getSetterCXXAssignment();
1002 if (!setter) return true;
1003
1004 // Sema only makes only of these when the ivar has a C++ class type,
1005 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001006
1007 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001008 // This also implies that there's nothing non-trivial going on with
1009 // the arguments, because operator= can only be trivial if it's a
1010 // synthesized assignment operator and therefore both parameters are
1011 // references.
1012 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001013 if (const FunctionDecl *callee
1014 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1015 if (callee->isTrivial())
1016 return true;
1017 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001018 }
John McCall71c758d2011-09-10 09:17:20 +00001019
John McCall1e1f4872011-09-13 03:34:09 +00001020 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001021 return false;
1022}
1023
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001024static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001025 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001026 return false;
1027 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001028
1029 if (Target.getPlatformName() != "macosx")
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001030 return false;
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001031
1032 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001033}
1034
John McCall71c758d2011-09-10 09:17:20 +00001035void
1036CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001037 const ObjCPropertyImplDecl *propImpl,
1038 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001039 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001040 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001041 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001042
1043 // Just use the setter expression if Sema gave us one and it's
1044 // non-trivial.
1045 if (!hasTrivialSetExpr(propImpl)) {
1046 if (!AtomicHelperFn)
1047 // If non-atomic, assignment is called directly.
1048 EmitStmt(propImpl->getSetterCXXAssignment());
1049 else
1050 // If atomic, assignment is called via a locking api.
1051 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1052 AtomicHelperFn);
1053 return;
1054 }
John McCall71c758d2011-09-10 09:17:20 +00001055
John McCall1e1f4872011-09-13 03:34:09 +00001056 PropertyImplStrategy strategy(CGM, propImpl);
1057 switch (strategy.getKind()) {
1058 case PropertyImplStrategy::Native: {
1059 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001060
John McCall1e1f4872011-09-13 03:34:09 +00001061 LValue ivarLValue =
1062 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1063 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001064
John McCall1e1f4872011-09-13 03:34:09 +00001065 // Currently, all atomic accesses have to be through integer
1066 // types, so there's no point in trying to pick a prettier type.
1067 llvm::Type *bitcastType =
1068 llvm::Type::getIntNTy(getLLVMContext(),
1069 getContext().toBits(strategy.getIvarSize()));
1070 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1071
1072 // Cast both arguments to the chosen operation type.
1073 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1074 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1075
1076 // This bitcast load is likely to cause some nasty IR.
1077 llvm::Value *load = Builder.CreateLoad(argAddr);
1078
1079 // Perform an atomic store. There are no memory ordering requirements.
1080 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1081 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1082 store->setAtomic(llvm::Unordered);
1083 return;
1084 }
1085
1086 case PropertyImplStrategy::GetSetProperty:
1087 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001088
1089 llvm::Value *setOptimizedPropertyFn = 0;
1090 llvm::Value *setPropertyFn = 0;
1091 if (UseOptimizedSetter(CGM)) {
1092 // 10.8 code and GC is off
1093 setOptimizedPropertyFn =
1094 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(strategy.isAtomic(),
1095 strategy.isCopy());
1096 if (!setOptimizedPropertyFn) {
1097 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1098 return;
1099 }
John McCall71c758d2011-09-10 09:17:20 +00001100 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001101 else {
1102 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1103 if (!setPropertyFn) {
1104 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1105 return;
1106 }
1107 }
1108
John McCall71c758d2011-09-10 09:17:20 +00001109 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1110 // <is-atomic>, <is-copy>).
1111 llvm::Value *cmd =
1112 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1113 llvm::Value *self =
1114 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1115 llvm::Value *ivarOffset =
1116 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1117 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1118 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1119
1120 CallArgList args;
1121 args.add(RValue::get(self), getContext().getObjCIdType());
1122 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001123 if (setOptimizedPropertyFn) {
1124 args.add(RValue::get(arg), getContext().getObjCIdType());
1125 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1126 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1127 FunctionType::ExtInfo(),
1128 RequiredArgs::All),
1129 setOptimizedPropertyFn, ReturnValueSlot(), args);
1130 } else {
1131 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1132 args.add(RValue::get(arg), getContext().getObjCIdType());
1133 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1134 getContext().BoolTy);
1135 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1136 getContext().BoolTy);
1137 // FIXME: We shouldn't need to get the function info here, the runtime
1138 // already should have computed it to build the function.
1139 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1140 FunctionType::ExtInfo(),
1141 RequiredArgs::All),
1142 setPropertyFn, ReturnValueSlot(), args);
1143 }
1144
John McCall71c758d2011-09-10 09:17:20 +00001145 return;
1146 }
1147
John McCall1e1f4872011-09-13 03:34:09 +00001148 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001149 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001150 return;
John McCall1e1f4872011-09-13 03:34:09 +00001151
1152 case PropertyImplStrategy::Expression:
1153 break;
John McCall71c758d2011-09-10 09:17:20 +00001154 }
1155
1156 // Otherwise, fake up some ASTs and emit a normal assignment.
1157 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001158 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1159 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001160 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1161 selfDecl->getType(), CK_LValueToRValue, &self,
1162 VK_RValue);
1163 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1164 SourceLocation(), &selfLoad, true, true);
1165
1166 ParmVarDecl *argDecl = *setterMethod->param_begin();
1167 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001168 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001169 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1170 argType.getUnqualifiedType(), CK_LValueToRValue,
1171 &arg, VK_RValue);
1172
1173 // The property type can differ from the ivar type in some situations with
1174 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1175 // The following absurdity is just to ensure well-formed IR.
1176 CastKind argCK = CK_NoOp;
1177 if (ivarRef.getType()->isObjCObjectPointerType()) {
1178 if (argLoad.getType()->isObjCObjectPointerType())
1179 argCK = CK_BitCast;
1180 else if (argLoad.getType()->isBlockPointerType())
1181 argCK = CK_BlockPointerToObjCPointerCast;
1182 else
1183 argCK = CK_CPointerToObjCPointerCast;
1184 } else if (ivarRef.getType()->isBlockPointerType()) {
1185 if (argLoad.getType()->isBlockPointerType())
1186 argCK = CK_BitCast;
1187 else
1188 argCK = CK_AnyPointerToBlockPointerCast;
1189 } else if (ivarRef.getType()->isPointerType()) {
1190 argCK = CK_BitCast;
1191 }
1192 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1193 ivarRef.getType(), argCK, &argLoad,
1194 VK_RValue);
1195 Expr *finalArg = &argLoad;
1196 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1197 argLoad.getType()))
1198 finalArg = &argCast;
1199
1200
1201 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1202 ivarRef.getType(), VK_RValue, OK_Ordinary,
1203 SourceLocation());
1204 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001205}
1206
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001207/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +00001208/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1209/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001210void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1211 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001212 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001213 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001214 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1215 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1216 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +00001217 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001218
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001219 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001220
1221 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001222}
1223
John McCalle81ac692011-03-22 07:05:39 +00001224namespace {
John McCall9928c482011-07-12 16:41:08 +00001225 struct DestroyIvar : EHScopeStack::Cleanup {
1226 private:
1227 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001228 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001229 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001230 bool useEHCleanupForArray;
1231 public:
1232 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1233 CodeGenFunction::Destroyer *destroyer,
1234 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001235 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001236 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001237
John McCallad346f42011-07-12 20:27:29 +00001238 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001239 LValue lvalue
1240 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1241 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001242 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001243 }
1244 };
1245}
1246
John McCall9928c482011-07-12 16:41:08 +00001247/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1248static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1249 llvm::Value *addr,
1250 QualType type) {
1251 llvm::Value *null = getNullForVariable(addr);
1252 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1253}
John McCallf85e1932011-06-15 23:02:42 +00001254
John McCalle81ac692011-03-22 07:05:39 +00001255static void emitCXXDestructMethod(CodeGenFunction &CGF,
1256 ObjCImplementationDecl *impl) {
1257 CodeGenFunction::RunCleanupsScope scope(CGF);
1258
1259 llvm::Value *self = CGF.LoadObjCSelf();
1260
Jordy Rosedb8264e2011-07-22 02:08:32 +00001261 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1262 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001263 ivar; ivar = ivar->getNextIvar()) {
1264 QualType type = ivar->getType();
1265
John McCalle81ac692011-03-22 07:05:39 +00001266 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001267 QualType::DestructionKind dtorKind = type.isDestructedType();
1268 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001269
John McCall9928c482011-07-12 16:41:08 +00001270 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001271
John McCall9928c482011-07-12 16:41:08 +00001272 // Use a call to objc_storeStrong to destroy strong ivars, for the
1273 // general benefit of the tools.
1274 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001275 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001276
John McCall9928c482011-07-12 16:41:08 +00001277 // Otherwise use the default for the destruction kind.
1278 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001279 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001280 }
John McCall9928c482011-07-12 16:41:08 +00001281
1282 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1283
1284 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1285 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001286 }
1287
1288 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1289}
1290
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001291void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1292 ObjCMethodDecl *MD,
1293 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001294 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001295 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001296
1297 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001298 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001299 // Suppress the final autorelease in ARC.
1300 AutoreleaseResult = false;
1301
Chris Lattner5f9e2722011-07-23 10:55:15 +00001302 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001303 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1304 E = IMP->init_end(); B != E; ++B) {
1305 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001306 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001307 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001308 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1309 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001310 EmitAggExpr(IvarInit->getInit(),
1311 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001312 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +00001313 AggValueSlot::IsNotAliased,
1314 AggValueSlot::IsCompleteObject));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001315 }
1316 // constructor returns 'self'.
1317 CodeGenTypes &Types = CGM.getTypes();
1318 QualType IdTy(CGM.getContext().getObjCIdType());
1319 llvm::Value *SelfAsId =
1320 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1321 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001322
1323 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001324 } else {
John McCalle81ac692011-03-22 07:05:39 +00001325 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001326 }
1327 FinishFunction();
1328}
1329
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001330bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1331 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1332 it++; it++;
1333 const ABIArgInfo &AI = it->info;
1334 // FIXME. Is this sufficient check?
1335 return (AI.getKind() == ABIArgInfo::Indirect);
1336}
1337
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001338bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001339 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001340 return false;
1341 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1342 return FDTTy->getDecl()->hasObjectMember();
1343 return false;
1344}
1345
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001346llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001347 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1348 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001349}
1350
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001351QualType CodeGenFunction::TypeOfSelfObject() {
1352 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1353 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001354 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1355 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001356 return PTy->getPointeeType();
1357}
1358
Chris Lattner74391b42009-03-22 21:03:39 +00001359void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001360 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001361 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001362
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001363 if (!EnumerationMutationFn) {
1364 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1365 return;
1366 }
1367
Devang Patelbcbd03a2011-01-19 01:36:36 +00001368 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001369 if (DI)
1370 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001371
Devang Patel9d99f2d2011-06-13 23:15:32 +00001372 // The local variable comes into scope immediately.
1373 AutoVarEmission variable = AutoVarEmission::invalid();
1374 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1375 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1376
John McCalld88687f2011-01-07 01:49:06 +00001377 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Anders Carlssonf484c312008-08-31 02:33:12 +00001379 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001380 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001381 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001382 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Anders Carlssonf484c312008-08-31 02:33:12 +00001384 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001385 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001386
John McCalld88687f2011-01-07 01:49:06 +00001387 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001388 IdentifierInfo *II[] = {
1389 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1390 &CGM.getContext().Idents.get("objects"),
1391 &CGM.getContext().Idents.get("count")
1392 };
1393 Selector FastEnumSel =
1394 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001395
1396 QualType ItemsTy =
1397 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001398 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001399 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001400 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001401
John McCall990567c2011-07-27 01:07:15 +00001402 // Emit the collection pointer. In ARC, we do a retain.
1403 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001404 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001405 Collection = EmitARCRetainScalarExpr(S.getCollection());
1406
1407 // Enter a cleanup to do the release.
1408 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1409 } else {
1410 Collection = EmitScalarExpr(S.getCollection());
1411 }
Mike Stump1eb44332009-09-09 15:08:12 +00001412
John McCall4b302d32011-08-05 00:14:38 +00001413 // The 'continue' label needs to appear within the cleanup for the
1414 // collection object.
1415 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1416
John McCalld88687f2011-01-07 01:49:06 +00001417 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001418 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001419
1420 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001421 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001422
John McCalld88687f2011-01-07 01:49:06 +00001423 // The second argument is a temporary array with space for NumItems
1424 // pointers. We'll actually be loading elements from the array
1425 // pointer written into the control state; this buffer is so that
1426 // collections that *aren't* backed by arrays can still queue up
1427 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001428 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001429
John McCalld88687f2011-01-07 01:49:06 +00001430 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001431 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001432 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001433 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001434
John McCalld88687f2011-01-07 01:49:06 +00001435 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001436 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001437 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001438 getContext().UnsignedLongTy,
1439 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001440 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001441
John McCalld88687f2011-01-07 01:49:06 +00001442 // The initial number of objects that were returned in the buffer.
1443 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001444
John McCalld88687f2011-01-07 01:49:06 +00001445 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1446 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCalld88687f2011-01-07 01:49:06 +00001448 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001449
John McCalld88687f2011-01-07 01:49:06 +00001450 // If the limit pointer was zero to begin with, the collection is
1451 // empty; skip all this.
1452 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1453 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001454
John McCalld88687f2011-01-07 01:49:06 +00001455 // Otherwise, initialize the loop.
1456 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCalld88687f2011-01-07 01:49:06 +00001458 // Save the initial mutations value. This is the value at an
1459 // address that was written into the state object by
1460 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001461 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001462 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001463 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001464 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001465
John McCalld88687f2011-01-07 01:49:06 +00001466 llvm::Value *initialMutations =
1467 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001468
John McCalld88687f2011-01-07 01:49:06 +00001469 // Start looping. This is the point we return to whenever we have a
1470 // fresh, non-empty batch of objects.
1471 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1472 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001473
John McCalld88687f2011-01-07 01:49:06 +00001474 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001475 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001476 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001477
John McCalld88687f2011-01-07 01:49:06 +00001478 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001479 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001480 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001481
John McCalld88687f2011-01-07 01:49:06 +00001482 // Check whether the mutations value has changed from where it was
1483 // at start. StateMutationsPtr should actually be invariant between
1484 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001485 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001486 llvm::Value *currentMutations
1487 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001488
John McCalld88687f2011-01-07 01:49:06 +00001489 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001490 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCalld88687f2011-01-07 01:49:06 +00001492 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1493 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
John McCalld88687f2011-01-07 01:49:06 +00001495 // If so, call the enumeration-mutation function.
1496 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001497 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001498 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001499 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001500 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001501 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001502 // FIXME: We shouldn't need to get the function info here, the runtime already
1503 // should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +00001504 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1505 FunctionType::ExtInfo(),
1506 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001507 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001508
John McCalld88687f2011-01-07 01:49:06 +00001509 // Otherwise, or if the mutation function returns, just continue.
1510 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001511
John McCalld88687f2011-01-07 01:49:06 +00001512 // Initialize the element variable.
1513 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001514 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001515 LValue elementLValue;
1516 QualType elementType;
1517 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001518 // Initialize the variable, in case it's a __block variable or something.
1519 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001520
John McCall57b3b6a2011-02-22 07:16:58 +00001521 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001522 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001523 VK_LValue, SourceLocation());
1524 elementLValue = EmitLValue(&tempDRE);
1525 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001526 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001527
1528 if (D->isARCPseudoStrong())
1529 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001530 } else {
1531 elementLValue = LValue(); // suppress warning
1532 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001533 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001534 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001535 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001536
1537 // Fetch the buffer out of the enumeration state.
1538 // TODO: this pointer should actually be invariant between
1539 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001540 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001541 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001542 llvm::Value *EnumStateItems =
1543 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001544
John McCalld88687f2011-01-07 01:49:06 +00001545 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001546 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001547 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1548 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001549
John McCalld88687f2011-01-07 01:49:06 +00001550 // Cast that value to the right type.
1551 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1552 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCalld88687f2011-01-07 01:49:06 +00001554 // Make sure we have an l-value. Yes, this gets evaluated every
1555 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001556 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001557 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001558 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001559 } else {
1560 EmitScalarInit(CurrentItem, elementLValue);
1561 }
Mike Stump1eb44332009-09-09 15:08:12 +00001562
John McCall57b3b6a2011-02-22 07:16:58 +00001563 // If we do have an element variable, this assignment is the end of
1564 // its initialization.
1565 if (elementIsVariable)
1566 EmitAutoVarCleanups(variable);
1567
John McCalld88687f2011-01-07 01:49:06 +00001568 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001569 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001570 {
1571 RunCleanupsScope Scope(*this);
1572 EmitStmt(S.getBody());
1573 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001574 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001575
John McCalld88687f2011-01-07 01:49:06 +00001576 // Destroy the element variable now.
1577 elementVariableScope.ForceCleanup();
1578
1579 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001580 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001581
John McCalld88687f2011-01-07 01:49:06 +00001582 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001583
John McCalld88687f2011-01-07 01:49:06 +00001584 // First we check in the local buffer.
1585 llvm::Value *indexPlusOne
1586 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001587
John McCalld88687f2011-01-07 01:49:06 +00001588 // If we haven't overrun the buffer yet, we can continue.
1589 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1590 LoopBodyBB, FetchMoreBB);
1591
1592 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1593 count->addIncoming(count, AfterBody.getBlock());
1594
1595 // Otherwise, we have to fetch more elements.
1596 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001597
1598 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001599 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001600 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001601 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001602 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
John McCalld88687f2011-01-07 01:49:06 +00001604 // If we got a zero count, we're done.
1605 llvm::Value *refetchCount = CountRV.getScalarVal();
1606
1607 // (note that the message send might split FetchMoreBB)
1608 index->addIncoming(zero, Builder.GetInsertBlock());
1609 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1610
1611 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1612 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Anders Carlssonf484c312008-08-31 02:33:12 +00001614 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001615 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001616
John McCall57b3b6a2011-02-22 07:16:58 +00001617 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001618 // If the element was not a declaration, set it to be null.
1619
John McCalld88687f2011-01-07 01:49:06 +00001620 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1621 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001622 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001623 }
1624
Eric Christopher73fb3502011-10-13 21:45:18 +00001625 if (DI)
1626 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001627
John McCall990567c2011-07-27 01:07:15 +00001628 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001629 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001630 PopCleanupBlock();
1631
John McCallff8e1152010-07-23 21:56:41 +00001632 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001633}
1634
Mike Stump1eb44332009-09-09 15:08:12 +00001635void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001636 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001637}
1638
Mike Stump1eb44332009-09-09 15:08:12 +00001639void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001640 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1641}
1642
Chris Lattner10cac6f2008-11-15 21:26:17 +00001643void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001644 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001645 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001646}
1647
John McCall33e56f32011-09-10 06:18:15 +00001648/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001649/// primitive retain.
1650llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1651 llvm::Value *value) {
1652 return EmitARCRetain(type, value);
1653}
1654
1655namespace {
1656 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001657 CallObjCRelease(llvm::Value *object) : object(object) {}
1658 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001659
John McCallad346f42011-07-12 20:27:29 +00001660 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001661 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001662 }
1663 };
1664}
1665
John McCall33e56f32011-09-10 06:18:15 +00001666/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001667/// release at the end of the full-expression.
1668llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1669 llvm::Value *object) {
1670 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001671 // conditional.
1672 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001673 return object;
1674}
1675
1676llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1677 llvm::Value *value) {
1678 return EmitARCRetainAutorelease(type, value);
1679}
1680
1681
1682static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001683 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001684 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001685 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1686
1687 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1688 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001689 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001690 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1691 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1692
1693 return fn;
1694}
1695
1696/// Perform an operation having the signature
1697/// i8* (i8*)
1698/// where a null input causes a no-op and returns null.
1699static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1700 llvm::Value *value,
1701 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001702 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001703 if (isa<llvm::ConstantPointerNull>(value)) return value;
1704
1705 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001706 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001707 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001708 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1709 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1710 }
1711
1712 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001713 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001714 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1715
1716 // Call the function.
1717 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1718 call->setDoesNotThrow();
1719
1720 // Cast the result back to the original type.
1721 return CGF.Builder.CreateBitCast(call, origType);
1722}
1723
1724/// Perform an operation having the following signature:
1725/// i8* (i8**)
1726static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1727 llvm::Value *addr,
1728 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001729 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001730 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001731 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001732 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001733 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1734 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1735 }
1736
1737 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001738 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001739 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1740
1741 // Call the function.
1742 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1743 call->setDoesNotThrow();
1744
1745 // Cast the result back to a dereference of the original type.
1746 llvm::Value *result = call;
1747 if (origType != CGF.Int8PtrPtrTy)
1748 result = CGF.Builder.CreateBitCast(result,
1749 cast<llvm::PointerType>(origType)->getElementType());
1750
1751 return result;
1752}
1753
1754/// Perform an operation having the following signature:
1755/// i8* (i8**, i8*)
1756static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1757 llvm::Value *addr,
1758 llvm::Value *value,
1759 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001760 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001761 bool ignored) {
1762 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1763 == value->getType());
1764
1765 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001766 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001767
Chris Lattner2acc6e32011-07-18 04:24:23 +00001768 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001769 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1770 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1771 }
1772
Chris Lattner2acc6e32011-07-18 04:24:23 +00001773 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001774
1775 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1776 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1777
1778 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1779 result->setDoesNotThrow();
1780
1781 if (ignored) return 0;
1782
1783 return CGF.Builder.CreateBitCast(result, origType);
1784}
1785
1786/// Perform an operation having the following signature:
1787/// void (i8**, i8**)
1788static void emitARCCopyOperation(CodeGenFunction &CGF,
1789 llvm::Value *dst,
1790 llvm::Value *src,
1791 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001792 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001793 assert(dst->getType() == src->getType());
1794
1795 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001796 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001797 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001798 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1799 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1800 }
1801
1802 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1803 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1804
1805 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1806 result->setDoesNotThrow();
1807}
1808
1809/// Produce the code to do a retain. Based on the type, calls one of:
1810/// call i8* @objc_retain(i8* %value)
1811/// call i8* @objc_retainBlock(i8* %value)
1812llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1813 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001814 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001815 else
1816 return EmitARCRetainNonBlock(value);
1817}
1818
1819/// Retain the given object, with normal retain semantics.
1820/// call i8* @objc_retain(i8* %value)
1821llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1822 return emitARCValueOperation(*this, value,
1823 CGM.getARCEntrypoints().objc_retain,
1824 "objc_retain");
1825}
1826
1827/// Retain the given block, with _Block_copy semantics.
1828/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001829///
1830/// \param mandatory - If false, emit the call with metadata
1831/// indicating that it's okay for the optimizer to eliminate this call
1832/// if it can prove that the block never escapes except down the stack.
1833llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1834 bool mandatory) {
1835 llvm::Value *result
1836 = emitARCValueOperation(*this, value,
1837 CGM.getARCEntrypoints().objc_retainBlock,
1838 "objc_retainBlock");
1839
1840 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1841 // tell the optimizer that it doesn't need to do this copy if the
1842 // block doesn't escape, where being passed as an argument doesn't
1843 // count as escaping.
1844 if (!mandatory && isa<llvm::Instruction>(result)) {
1845 llvm::CallInst *call
1846 = cast<llvm::CallInst>(result->stripPointerCasts());
1847 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1848
1849 SmallVector<llvm::Value*,1> args;
1850 call->setMetadata("clang.arc.copy_on_escape",
1851 llvm::MDNode::get(Builder.getContext(), args));
1852 }
1853
1854 return result;
John McCallf85e1932011-06-15 23:02:42 +00001855}
1856
1857/// Retain the given object which is the result of a function call.
1858/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1859///
1860/// Yes, this function name is one character away from a different
1861/// call with completely different semantics.
1862llvm::Value *
1863CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1864 // Fetch the void(void) inline asm which marks that we're going to
1865 // retain the autoreleased return value.
1866 llvm::InlineAsm *&marker
1867 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1868 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001869 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001870 = CGM.getTargetCodeGenInfo()
1871 .getARCRetainAutoreleasedReturnValueMarker();
1872
1873 // If we have an empty assembly string, there's nothing to do.
1874 if (assembly.empty()) {
1875
1876 // Otherwise, at -O0, build an inline asm that we're going to call
1877 // in a moment.
1878 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1879 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001880 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001881
1882 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1883
1884 // If we're at -O1 and above, we don't want to litter the code
1885 // with this marker yet, so leave a breadcrumb for the ARC
1886 // optimizer to pick up.
1887 } else {
1888 llvm::NamedMDNode *metadata =
1889 CGM.getModule().getOrInsertNamedMetadata(
1890 "clang.arc.retainAutoreleasedReturnValueMarker");
1891 assert(metadata->getNumOperands() <= 1);
1892 if (metadata->getNumOperands() == 0) {
1893 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001894 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001895 }
1896 }
1897 }
1898
1899 // Call the marker asm if we made one, which we do only at -O0.
1900 if (marker) Builder.CreateCall(marker);
1901
1902 return emitARCValueOperation(*this, value,
1903 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1904 "objc_retainAutoreleasedReturnValue");
1905}
1906
1907/// Release the given object.
1908/// call void @objc_release(i8* %value)
1909void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1910 if (isa<llvm::ConstantPointerNull>(value)) return;
1911
1912 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1913 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001914 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001915 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001916 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1917 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1918 }
1919
1920 // Cast the argument to 'id'.
1921 value = Builder.CreateBitCast(value, Int8PtrTy);
1922
1923 // Call objc_release.
1924 llvm::CallInst *call = Builder.CreateCall(fn, value);
1925 call->setDoesNotThrow();
1926
1927 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001928 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001929 call->setMetadata("clang.imprecise_release",
1930 llvm::MDNode::get(Builder.getContext(), args));
1931 }
1932}
1933
1934/// Store into a strong object. Always calls this:
1935/// call void @objc_storeStrong(i8** %addr, i8* %value)
1936llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1937 llvm::Value *value,
1938 bool ignored) {
1939 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1940 == value->getType());
1941
1942 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1943 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001944 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001945 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001946 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1947 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1948 }
1949
1950 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1951 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1952
1953 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1954
1955 if (ignored) return 0;
1956 return value;
1957}
1958
1959/// Store into a strong object. Sometimes calls this:
1960/// call void @objc_storeStrong(i8** %addr, i8* %value)
1961/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001962llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001963 llvm::Value *newValue,
1964 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001965 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001966 bool isBlock = type->isBlockPointerType();
1967
1968 // Use a store barrier at -O0 unless this is a block type or the
1969 // lvalue is inadequately aligned.
1970 if (shouldUseFusedARCCalls() &&
1971 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001972 (dst.getAlignment().isZero() ||
1973 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001974 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1975 }
1976
1977 // Otherwise, split it out.
1978
1979 // Retain the new value.
1980 newValue = EmitARCRetain(type, newValue);
1981
1982 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001983 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001984
1985 // Store. We do this before the release so that any deallocs won't
1986 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001987 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001988
1989 // Finally, release the old value.
1990 EmitARCRelease(oldValue, /*precise*/ false);
1991
1992 return newValue;
1993}
1994
1995/// Autorelease the given object.
1996/// call i8* @objc_autorelease(i8* %value)
1997llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1998 return emitARCValueOperation(*this, value,
1999 CGM.getARCEntrypoints().objc_autorelease,
2000 "objc_autorelease");
2001}
2002
2003/// Autorelease the given object.
2004/// call i8* @objc_autoreleaseReturnValue(i8* %value)
2005llvm::Value *
2006CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2007 return emitARCValueOperation(*this, value,
2008 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2009 "objc_autoreleaseReturnValue");
2010}
2011
2012/// Do a fused retain/autorelease of the given object.
2013/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
2014llvm::Value *
2015CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2016 return emitARCValueOperation(*this, value,
2017 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2018 "objc_retainAutoreleaseReturnValue");
2019}
2020
2021/// Do a fused retain/autorelease of the given object.
2022/// call i8* @objc_retainAutorelease(i8* %value)
2023/// or
2024/// %retain = call i8* @objc_retainBlock(i8* %value)
2025/// call i8* @objc_autorelease(i8* %retain)
2026llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2027 llvm::Value *value) {
2028 if (!type->isBlockPointerType())
2029 return EmitARCRetainAutoreleaseNonBlock(value);
2030
2031 if (isa<llvm::ConstantPointerNull>(value)) return value;
2032
Chris Lattner2acc6e32011-07-18 04:24:23 +00002033 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002034 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002035 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002036 value = EmitARCAutorelease(value);
2037 return Builder.CreateBitCast(value, origType);
2038}
2039
2040/// Do a fused retain/autorelease of the given object.
2041/// call i8* @objc_retainAutorelease(i8* %value)
2042llvm::Value *
2043CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2044 return emitARCValueOperation(*this, value,
2045 CGM.getARCEntrypoints().objc_retainAutorelease,
2046 "objc_retainAutorelease");
2047}
2048
2049/// i8* @objc_loadWeak(i8** %addr)
2050/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2051llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2052 return emitARCLoadOperation(*this, addr,
2053 CGM.getARCEntrypoints().objc_loadWeak,
2054 "objc_loadWeak");
2055}
2056
2057/// i8* @objc_loadWeakRetained(i8** %addr)
2058llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2059 return emitARCLoadOperation(*this, addr,
2060 CGM.getARCEntrypoints().objc_loadWeakRetained,
2061 "objc_loadWeakRetained");
2062}
2063
2064/// i8* @objc_storeWeak(i8** %addr, i8* %value)
2065/// Returns %value.
2066llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2067 llvm::Value *value,
2068 bool ignored) {
2069 return emitARCStoreOperation(*this, addr, value,
2070 CGM.getARCEntrypoints().objc_storeWeak,
2071 "objc_storeWeak", ignored);
2072}
2073
2074/// i8* @objc_initWeak(i8** %addr, i8* %value)
2075/// Returns %value. %addr is known to not have a current weak entry.
2076/// Essentially equivalent to:
2077/// *addr = nil; objc_storeWeak(addr, value);
2078void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2079 // If we're initializing to null, just write null to memory; no need
2080 // to get the runtime involved. But don't do this if optimization
2081 // is enabled, because accounting for this would make the optimizer
2082 // much more complicated.
2083 if (isa<llvm::ConstantPointerNull>(value) &&
2084 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2085 Builder.CreateStore(value, addr);
2086 return;
2087 }
2088
2089 emitARCStoreOperation(*this, addr, value,
2090 CGM.getARCEntrypoints().objc_initWeak,
2091 "objc_initWeak", /*ignored*/ true);
2092}
2093
2094/// void @objc_destroyWeak(i8** %addr)
2095/// Essentially objc_storeWeak(addr, nil).
2096void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2097 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2098 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002099 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002100 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002101 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2102 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2103 }
2104
2105 // Cast the argument to 'id*'.
2106 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2107
2108 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2109 call->setDoesNotThrow();
2110}
2111
2112/// void @objc_moveWeak(i8** %dest, i8** %src)
2113/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2114/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2115void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2116 emitARCCopyOperation(*this, dst, src,
2117 CGM.getARCEntrypoints().objc_moveWeak,
2118 "objc_moveWeak");
2119}
2120
2121/// void @objc_copyWeak(i8** %dest, i8** %src)
2122/// Disregards the current value in %dest. Essentially
2123/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2124void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2125 emitARCCopyOperation(*this, dst, src,
2126 CGM.getARCEntrypoints().objc_copyWeak,
2127 "objc_copyWeak");
2128}
2129
2130/// Produce the code to do a objc_autoreleasepool_push.
2131/// call i8* @objc_autoreleasePoolPush(void)
2132llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2133 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2134 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002135 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002136 llvm::FunctionType::get(Int8PtrTy, false);
2137 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2138 }
2139
2140 llvm::CallInst *call = Builder.CreateCall(fn);
2141 call->setDoesNotThrow();
2142
2143 return call;
2144}
2145
2146/// Produce the code to do a primitive release.
2147/// call void @objc_autoreleasePoolPop(i8* %ptr)
2148void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2149 assert(value->getType() == Int8PtrTy);
2150
2151 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2152 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002153 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002154 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002155 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2156
2157 // We don't want to use a weak import here; instead we should not
2158 // fall into this path.
2159 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2160 }
2161
2162 llvm::CallInst *call = Builder.CreateCall(fn, value);
2163 call->setDoesNotThrow();
2164}
2165
2166/// Produce the code to do an MRR version objc_autoreleasepool_push.
2167/// Which is: [[NSAutoreleasePool alloc] init];
2168/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2169/// init is declared as: - (id) init; in its NSObject super class.
2170///
2171llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2172 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2173 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2174 // [NSAutoreleasePool alloc]
2175 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2176 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2177 CallArgList Args;
2178 RValue AllocRV =
2179 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2180 getContext().getObjCIdType(),
2181 AllocSel, Receiver, Args);
2182
2183 // [Receiver init]
2184 Receiver = AllocRV.getScalarVal();
2185 II = &CGM.getContext().Idents.get("init");
2186 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2187 RValue InitRV =
2188 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2189 getContext().getObjCIdType(),
2190 InitSel, Receiver, Args);
2191 return InitRV.getScalarVal();
2192}
2193
2194/// Produce the code to do a primitive release.
2195/// [tmp drain];
2196void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2197 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2198 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2199 CallArgList Args;
2200 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2201 getContext().VoidTy, DrainSel, Arg, Args);
2202}
2203
John McCallbdc4d802011-07-09 01:37:26 +00002204void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2205 llvm::Value *addr,
2206 QualType type) {
2207 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2208 CGF.EmitARCRelease(ptr, /*precise*/ true);
2209}
2210
2211void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2212 llvm::Value *addr,
2213 QualType type) {
2214 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2215 CGF.EmitARCRelease(ptr, /*precise*/ false);
2216}
2217
2218void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2219 llvm::Value *addr,
2220 QualType type) {
2221 CGF.EmitARCDestroyWeak(addr);
2222}
2223
John McCallf85e1932011-06-15 23:02:42 +00002224namespace {
John McCallf85e1932011-06-15 23:02:42 +00002225 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2226 llvm::Value *Token;
2227
2228 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2229
John McCallad346f42011-07-12 20:27:29 +00002230 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002231 CGF.EmitObjCAutoreleasePoolPop(Token);
2232 }
2233 };
2234 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2235 llvm::Value *Token;
2236
2237 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2238
John McCallad346f42011-07-12 20:27:29 +00002239 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002240 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2241 }
2242 };
2243}
2244
2245void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002246 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002247 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2248 else
2249 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2250}
2251
John McCallf85e1932011-06-15 23:02:42 +00002252static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2253 LValue lvalue,
2254 QualType type) {
2255 switch (type.getObjCLifetime()) {
2256 case Qualifiers::OCL_None:
2257 case Qualifiers::OCL_ExplicitNone:
2258 case Qualifiers::OCL_Strong:
2259 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002260 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002261 false);
2262
2263 case Qualifiers::OCL_Weak:
2264 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2265 true);
2266 }
2267
2268 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002269}
2270
2271static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2272 const Expr *e) {
2273 e = e->IgnoreParens();
2274 QualType type = e->getType();
2275
John McCall21480112011-08-30 00:57:29 +00002276 // If we're loading retained from a __strong xvalue, we can avoid
2277 // an extra retain/release pair by zeroing out the source of this
2278 // "move" operation.
2279 if (e->isXValue() &&
2280 !type.isConstQualified() &&
2281 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2282 // Emit the lvalue.
2283 LValue lv = CGF.EmitLValue(e);
2284
2285 // Load the object pointer.
2286 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2287
2288 // Set the source pointer to NULL.
2289 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2290
2291 return TryEmitResult(result, true);
2292 }
2293
John McCallf85e1932011-06-15 23:02:42 +00002294 // As a very special optimization, in ARC++, if the l-value is the
2295 // result of a non-volatile assignment, do a simple retain of the
2296 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002297 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002298 !type.isVolatileQualified() &&
2299 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2300 isa<BinaryOperator>(e) &&
2301 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2302 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2303
2304 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2305}
2306
2307static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2308 llvm::Value *value);
2309
2310/// Given that the given expression is some sort of call (which does
2311/// not return retained), emit a retain following it.
2312static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2313 llvm::Value *value = CGF.EmitScalarExpr(e);
2314 return emitARCRetainAfterCall(CGF, value);
2315}
2316
2317static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2318 llvm::Value *value) {
2319 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2320 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2321
2322 // Place the retain immediately following the call.
2323 CGF.Builder.SetInsertPoint(call->getParent(),
2324 ++llvm::BasicBlock::iterator(call));
2325 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2326
2327 CGF.Builder.restoreIP(ip);
2328 return value;
2329 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2330 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2331
2332 // Place the retain at the beginning of the normal destination block.
2333 llvm::BasicBlock *BB = invoke->getNormalDest();
2334 CGF.Builder.SetInsertPoint(BB, BB->begin());
2335 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2336
2337 CGF.Builder.restoreIP(ip);
2338 return value;
2339
2340 // Bitcasts can arise because of related-result returns. Rewrite
2341 // the operand.
2342 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2343 llvm::Value *operand = bitcast->getOperand(0);
2344 operand = emitARCRetainAfterCall(CGF, operand);
2345 bitcast->setOperand(0, operand);
2346 return bitcast;
2347
2348 // Generic fall-back case.
2349 } else {
2350 // Retain using the non-block variant: we never need to do a copy
2351 // of a block that's been returned to us.
2352 return CGF.EmitARCRetainNonBlock(value);
2353 }
2354}
2355
John McCalldc05b112011-09-10 01:16:55 +00002356/// Determine whether it might be important to emit a separate
2357/// objc_retain_block on the result of the given expression, or
2358/// whether it's okay to just emit it in a +1 context.
2359static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2360 assert(e->getType()->isBlockPointerType());
2361 e = e->IgnoreParens();
2362
2363 // For future goodness, emit block expressions directly in +1
2364 // contexts if we can.
2365 if (isa<BlockExpr>(e))
2366 return false;
2367
2368 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2369 switch (cast->getCastKind()) {
2370 // Emitting these operations in +1 contexts is goodness.
2371 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002372 case CK_ARCReclaimReturnedObject:
2373 case CK_ARCConsumeObject:
2374 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002375 return false;
2376
2377 // These operations preserve a block type.
2378 case CK_NoOp:
2379 case CK_BitCast:
2380 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2381
2382 // These operations are known to be bad (or haven't been considered).
2383 case CK_AnyPointerToBlockPointerCast:
2384 default:
2385 return true;
2386 }
2387 }
2388
2389 return true;
2390}
2391
John McCall4b9c2d22011-11-06 09:01:30 +00002392/// Try to emit a PseudoObjectExpr at +1.
2393///
2394/// This massively duplicates emitPseudoObjectRValue.
2395static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2396 const PseudoObjectExpr *E) {
2397 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2398
2399 // Find the result expression.
2400 const Expr *resultExpr = E->getResultExpr();
2401 assert(resultExpr);
2402 TryEmitResult result;
2403
2404 for (PseudoObjectExpr::const_semantics_iterator
2405 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2406 const Expr *semantic = *i;
2407
2408 // If this semantic expression is an opaque value, bind it
2409 // to the result of its source expression.
2410 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2411 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2412 OVMA opaqueData;
2413
2414 // If this semantic is the result of the pseudo-object
2415 // expression, try to evaluate the source as +1.
2416 if (ov == resultExpr) {
2417 assert(!OVMA::shouldBindAsLValue(ov));
2418 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2419 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2420
2421 // Otherwise, just bind it.
2422 } else {
2423 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2424 }
2425 opaques.push_back(opaqueData);
2426
2427 // Otherwise, if the expression is the result, evaluate it
2428 // and remember the result.
2429 } else if (semantic == resultExpr) {
2430 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2431
2432 // Otherwise, evaluate the expression in an ignored context.
2433 } else {
2434 CGF.EmitIgnoredExpr(semantic);
2435 }
2436 }
2437
2438 // Unbind all the opaques now.
2439 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2440 opaques[i].unbind(CGF);
2441
2442 return result;
2443}
2444
John McCallf85e1932011-06-15 23:02:42 +00002445static TryEmitResult
2446tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002447 // Look through cleanups.
2448 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002449 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002450 CodeGenFunction::RunCleanupsScope scope(CGF);
2451 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2452 }
2453
John McCallf85e1932011-06-15 23:02:42 +00002454 // The desired result type, if it differs from the type of the
2455 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002456 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002457
2458 while (true) {
2459 e = e->IgnoreParens();
2460
2461 // There's a break at the end of this if-chain; anything
2462 // that wants to keep looping has to explicitly continue.
2463 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2464 switch (ce->getCastKind()) {
2465 // No-op casts don't change the type, so we just ignore them.
2466 case CK_NoOp:
2467 e = ce->getSubExpr();
2468 continue;
2469
2470 case CK_LValueToRValue: {
2471 TryEmitResult loadResult
2472 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2473 if (resultType) {
2474 llvm::Value *value = loadResult.getPointer();
2475 value = CGF.Builder.CreateBitCast(value, resultType);
2476 loadResult.setPointer(value);
2477 }
2478 return loadResult;
2479 }
2480
2481 // These casts can change the type, so remember that and
2482 // soldier on. We only need to remember the outermost such
2483 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002484 case CK_CPointerToObjCPointerCast:
2485 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002486 case CK_AnyPointerToBlockPointerCast:
2487 case CK_BitCast:
2488 if (!resultType)
2489 resultType = CGF.ConvertType(ce->getType());
2490 e = ce->getSubExpr();
2491 assert(e->getType()->hasPointerRepresentation());
2492 continue;
2493
2494 // For consumptions, just emit the subexpression and thus elide
2495 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002496 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002497 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2498 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2499 return TryEmitResult(result, true);
2500 }
2501
John McCalldc05b112011-09-10 01:16:55 +00002502 // Block extends are net +0. Naively, we could just recurse on
2503 // the subexpression, but actually we need to ensure that the
2504 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002505 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002506 llvm::Value *result; // will be a +0 value
2507
2508 // If we can't safely assume the sub-expression will produce a
2509 // block-copied value, emit the sub-expression at +0.
2510 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2511 result = CGF.EmitScalarExpr(ce->getSubExpr());
2512
2513 // Otherwise, try to emit the sub-expression at +1 recursively.
2514 } else {
2515 TryEmitResult subresult
2516 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2517 result = subresult.getPointer();
2518
2519 // If that produced a retained value, just use that,
2520 // possibly casting down.
2521 if (subresult.getInt()) {
2522 if (resultType)
2523 result = CGF.Builder.CreateBitCast(result, resultType);
2524 return TryEmitResult(result, true);
2525 }
2526
2527 // Otherwise it's +0.
2528 }
2529
2530 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002531 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002532 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2533 return TryEmitResult(result, true);
2534 }
2535
John McCall7e5e5f42011-07-07 06:58:02 +00002536 // For reclaims, emit the subexpression as a retained call and
2537 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002538 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002539 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2540 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2541 return TryEmitResult(result, true);
2542 }
2543
John McCallf85e1932011-06-15 23:02:42 +00002544 default:
2545 break;
2546 }
2547
2548 // Skip __extension__.
2549 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2550 if (op->getOpcode() == UO_Extension) {
2551 e = op->getSubExpr();
2552 continue;
2553 }
2554
2555 // For calls and message sends, use the retained-call logic.
2556 // Delegate inits are a special case in that they're the only
2557 // returns-retained expression that *isn't* surrounded by
2558 // a consume.
2559 } else if (isa<CallExpr>(e) ||
2560 (isa<ObjCMessageExpr>(e) &&
2561 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2562 llvm::Value *result = emitARCRetainCall(CGF, e);
2563 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2564 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002565
2566 // Look through pseudo-object expressions.
2567 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2568 TryEmitResult result
2569 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2570 if (resultType) {
2571 llvm::Value *value = result.getPointer();
2572 value = CGF.Builder.CreateBitCast(value, resultType);
2573 result.setPointer(value);
2574 }
2575 return result;
John McCallf85e1932011-06-15 23:02:42 +00002576 }
2577
2578 // Conservatively halt the search at any other expression kind.
2579 break;
2580 }
2581
2582 // We didn't find an obvious production, so emit what we've got and
2583 // tell the caller that we didn't manage to retain.
2584 llvm::Value *result = CGF.EmitScalarExpr(e);
2585 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2586 return TryEmitResult(result, false);
2587}
2588
2589static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2590 LValue lvalue,
2591 QualType type) {
2592 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2593 llvm::Value *value = result.getPointer();
2594 if (!result.getInt())
2595 value = CGF.EmitARCRetain(type, value);
2596 return value;
2597}
2598
2599/// EmitARCRetainScalarExpr - Semantically equivalent to
2600/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2601/// best-effort attempt to peephole expressions that naturally produce
2602/// retained objects.
2603llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2604 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2605 llvm::Value *value = result.getPointer();
2606 if (!result.getInt())
2607 value = EmitARCRetain(e->getType(), value);
2608 return value;
2609}
2610
2611llvm::Value *
2612CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2613 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2614 llvm::Value *value = result.getPointer();
2615 if (result.getInt())
2616 value = EmitARCAutorelease(value);
2617 else
2618 value = EmitARCRetainAutorelease(e->getType(), value);
2619 return value;
2620}
2621
John McCall348f16f2011-10-04 06:23:45 +00002622llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2623 llvm::Value *result;
2624 bool doRetain;
2625
2626 if (shouldEmitSeparateBlockRetain(e)) {
2627 result = EmitScalarExpr(e);
2628 doRetain = true;
2629 } else {
2630 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2631 result = subresult.getPointer();
2632 doRetain = !subresult.getInt();
2633 }
2634
2635 if (doRetain)
2636 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2637 return EmitObjCConsumeObject(e->getType(), result);
2638}
2639
John McCall2b014d62011-10-01 10:32:24 +00002640llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2641 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002642 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002643 // Do so before running any cleanups for the full-expression.
2644 // tryEmitARCRetainScalarExpr does make an effort to do things
2645 // inside cleanups, but there are crazy cases like
2646 // @throw A().foo;
2647 // where a full retain+autorelease is required and would
2648 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002649 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2650 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002651 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002652 }
John McCall2b014d62011-10-01 10:32:24 +00002653
John McCall1a343eb2011-11-10 08:15:53 +00002654 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002655 return EmitARCRetainAutoreleaseScalarExpr(expr);
2656 }
2657
2658 // Otherwise, use the normal scalar-expression emission. The
2659 // exception machinery doesn't do anything special with the
2660 // exception like retaining it, so there's no safety associated with
2661 // only running cleanups after the throw has started, and when it
2662 // matters it tends to be substantially inferior code.
2663 return EmitScalarExpr(expr);
2664}
2665
John McCallf85e1932011-06-15 23:02:42 +00002666std::pair<LValue,llvm::Value*>
2667CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2668 bool ignored) {
2669 // Evaluate the RHS first.
2670 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2671 llvm::Value *value = result.getPointer();
2672
John McCallfb720812011-07-28 07:23:35 +00002673 bool hasImmediateRetain = result.getInt();
2674
2675 // If we didn't emit a retained object, and the l-value is of block
2676 // type, then we need to emit the block-retain immediately in case
2677 // it invalidates the l-value.
2678 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002679 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002680 hasImmediateRetain = true;
2681 }
2682
John McCallf85e1932011-06-15 23:02:42 +00002683 LValue lvalue = EmitLValue(e->getLHS());
2684
2685 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002686 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002687 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002688 EmitLoadOfScalar(lvalue);
2689 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002690 EmitARCRelease(oldValue, /*precise*/ false);
2691 } else {
John McCall545d9962011-06-25 02:11:03 +00002692 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002693 }
2694
2695 return std::pair<LValue,llvm::Value*>(lvalue, value);
2696}
2697
2698std::pair<LValue,llvm::Value*>
2699CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2700 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2701 LValue lvalue = EmitLValue(e->getLHS());
2702
Eli Friedman6da2c712011-12-03 04:14:32 +00002703 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002704
2705 return std::pair<LValue,llvm::Value*>(lvalue, value);
2706}
2707
2708void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2709 const ObjCAutoreleasePoolStmt &ARPS) {
2710 const Stmt *subStmt = ARPS.getSubStmt();
2711 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2712
2713 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002714 if (DI)
2715 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002716
2717 // Keep track of the current cleanup stack depth.
2718 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002719 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002720 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2721 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2722 } else {
2723 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2724 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2725 }
2726
2727 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2728 E = S.body_end(); I != E; ++I)
2729 EmitStmt(*I);
2730
Eric Christopher73fb3502011-10-13 21:45:18 +00002731 if (DI)
2732 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002733}
John McCall0c24c802011-06-24 23:21:27 +00002734
2735/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2736/// make sure it survives garbage collection until this point.
2737void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2738 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002739 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002740 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002741 llvm::Value *extender
2742 = llvm::InlineAsm::get(extenderType,
2743 /* assembly */ "",
2744 /* constraints */ "r",
2745 /* side effects */ true);
2746
2747 object = Builder.CreateBitCast(object, VoidPtrTy);
2748 Builder.CreateCall(extender, object)->setDoesNotThrow();
2749}
2750
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002751/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002752/// non-trivial copy assignment function, produce following helper function.
2753/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2754///
2755llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002756CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2757 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002758 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002759 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002760 return 0;
2761 QualType Ty = PID->getPropertyIvarDecl()->getType();
2762 if (!Ty->isRecordType())
2763 return 0;
2764 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002765 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002766 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002767 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002768 if (hasTrivialSetExpr(PID))
2769 return 0;
2770 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2771 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2772 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002773
2774 ASTContext &C = getContext();
2775 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002776 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002777 FunctionDecl *FD = FunctionDecl::Create(C,
2778 C.getTranslationUnitDecl(),
2779 SourceLocation(),
2780 SourceLocation(), II, C.VoidTy, 0,
2781 SC_Static,
2782 SC_None,
2783 false,
2784 true);
2785
2786 QualType DestTy = C.getPointerType(Ty);
2787 QualType SrcTy = Ty;
2788 SrcTy.addConst();
2789 SrcTy = C.getPointerType(SrcTy);
2790
2791 FunctionArgList args;
2792 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2793 args.push_back(&dstDecl);
2794 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2795 args.push_back(&srcDecl);
2796
2797 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002798 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2799 FunctionType::ExtInfo(),
2800 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002801
John McCallde5d3c72012-02-17 03:33:10 +00002802 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002803
2804 llvm::Function *Fn =
2805 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002806 "__assign_helper_atomic_property_", &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002807
2808 if (CGM.getModuleDebugInfo())
2809 DebugInfo = CGM.getModuleDebugInfo();
2810
2811
2812 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2813
John McCallf4b88a42012-03-10 09:33:50 +00002814 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2815 VK_RValue, SourceLocation());
2816 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2817 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002818
John McCallf4b88a42012-03-10 09:33:50 +00002819 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2820 VK_RValue, SourceLocation());
2821 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2822 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002823
John McCallf4b88a42012-03-10 09:33:50 +00002824 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002825 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002826 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2827 Args, 2, DestTy->getPointeeType(),
2828 VK_LValue, SourceLocation());
2829
2830 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002831
2832 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002833 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002834 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002835 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002836}
2837
2838llvm::Constant *
2839CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2840 const ObjCPropertyImplDecl *PID) {
2841 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002842 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002843 return 0;
2844 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2845 QualType Ty = PD->getType();
2846 if (!Ty->isRecordType())
2847 return 0;
2848 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2849 return 0;
2850 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002851
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002852 if (hasTrivialGetExpr(PID))
2853 return 0;
2854 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2855 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2856 return HelperFn;
2857
2858
2859 ASTContext &C = getContext();
2860 IdentifierInfo *II
2861 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2862 FunctionDecl *FD = FunctionDecl::Create(C,
2863 C.getTranslationUnitDecl(),
2864 SourceLocation(),
2865 SourceLocation(), II, C.VoidTy, 0,
2866 SC_Static,
2867 SC_None,
2868 false,
2869 true);
2870
2871 QualType DestTy = C.getPointerType(Ty);
2872 QualType SrcTy = Ty;
2873 SrcTy.addConst();
2874 SrcTy = C.getPointerType(SrcTy);
2875
2876 FunctionArgList args;
2877 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2878 args.push_back(&dstDecl);
2879 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2880 args.push_back(&srcDecl);
2881
2882 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002883 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2884 FunctionType::ExtInfo(),
2885 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002886
John McCallde5d3c72012-02-17 03:33:10 +00002887 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002888
2889 llvm::Function *Fn =
2890 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2891 "__copy_helper_atomic_property_", &CGM.getModule());
2892
2893 if (CGM.getModuleDebugInfo())
2894 DebugInfo = CGM.getModuleDebugInfo();
2895
2896
2897 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2898
John McCallf4b88a42012-03-10 09:33:50 +00002899 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002900 VK_RValue, SourceLocation());
2901
John McCallf4b88a42012-03-10 09:33:50 +00002902 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2903 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002904
2905 CXXConstructExpr *CXXConstExpr =
2906 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2907
2908 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002909 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002910 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2911 ++A;
2912
2913 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2914 A != AEnd; ++A)
2915 ConstructorArgs.push_back(*A);
2916
2917 CXXConstructExpr *TheCXXConstructExpr =
2918 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2919 CXXConstExpr->getConstructor(),
2920 CXXConstExpr->isElidable(),
2921 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002922 CXXConstExpr->hadMultipleCandidates(),
2923 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002924 CXXConstExpr->requiresZeroInitialization(),
2925 CXXConstExpr->getConstructionKind(), SourceRange());
2926
John McCallf4b88a42012-03-10 09:33:50 +00002927 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2928 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002929
John McCallf4b88a42012-03-10 09:33:50 +00002930 RValue DV = EmitAnyExpr(&DstExpr);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002931 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
2932 EmitAggExpr(TheCXXConstructExpr,
2933 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2934 AggValueSlot::IsDestructed,
2935 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +00002936 AggValueSlot::IsNotAliased,
2937 AggValueSlot::IsCompleteObject));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002938
2939 FinishFunction();
2940 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2941 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2942 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002943}
2944
Eli Friedmancae40c42012-02-28 01:08:45 +00002945llvm::Value *
2946CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2947 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002948 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2949 Selector CopySelector =
2950 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002951 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2952 Selector AutoreleaseSelector =
2953 getContext().Selectors.getNullarySelector(AutoreleaseID);
2954
2955 // Emit calls to retain/autorelease.
2956 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2957 llvm::Value *Val = Block;
2958 RValue Result;
2959 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002960 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002961 Val, CallArgList(), 0, 0);
2962 Val = Result.getScalarVal();
2963 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2964 Ty, AutoreleaseSelector,
2965 Val, CallArgList(), 0, 0);
2966 Val = Result.getScalarVal();
2967 return Val;
2968}
2969
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002970
Ted Kremenek2979ec72008-04-09 15:51:31 +00002971CGObjCRuntime::~CGObjCRuntime() {}