blob: d0aa0f5567a59a8e7492e5262bd520089ad66e88 [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///
Eric Christopher16098f32012-03-29 17:31:31 +000057llvm::Value *
58CodeGenFunction::EmitObjCNumericLiteral(const ObjCNumericLiteral *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000059 // Generate the correct selector for this literal's concrete type.
60 const Expr *NL = E->getNumber();
61 // Get the method.
62 const ObjCMethodDecl *Method = E->getObjCNumericLiteralMethod();
63 assert(Method && "NSNumber method is null");
64 Selector Sel = Method->getSelector();
65
66 // Generate a reference to the class pointer, which will be the receiver.
67 QualType ResultType = E->getType(); // should be NSNumber *
68 const ObjCObjectPointerType *InterfacePointerType =
69 ResultType->getAsObjCInterfacePointerType();
70 ObjCInterfaceDecl *NSNumberDecl =
71 InterfacePointerType->getObjectType()->getInterface();
72 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
73 llvm::Value *Receiver = Runtime.GetClass(Builder, NSNumberDecl);
74
75 const ParmVarDecl *argDecl = *Method->param_begin();
76 QualType ArgQT = argDecl->getType().getUnqualifiedType();
77 RValue RV = EmitAnyExpr(NL);
78 CallArgList Args;
79 Args.add(RV, ArgQT);
80
81 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
82 ResultType, Sel, Receiver, Args,
83 NSNumberDecl, Method);
84 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86}
87
88llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
112 // Perform the actual initialialization of the array(s).
113 for (uint64_t i = 0; i < NumElements; i++) {
114 if (ALE) {
115 // Emit the initializer.
116 const Expr *Rhs = ALE->getElement(i);
117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
118 ElementType,
119 Context.getTypeAlignInChars(Rhs->getType()),
120 Context);
121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
122 } else {
123 // Emit the key initializer.
124 const Expr *Key = DLE->getKeyValueElement(i).Key;
125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
126 ElementType,
127 Context.getTypeAlignInChars(Key->getType()),
128 Context);
129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
130
131 // Emit the value initializer.
132 const Expr *Value = DLE->getKeyValueElement(i).Value;
133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
134 ElementType,
135 Context.getTypeAlignInChars(Value->getType()),
136 Context);
137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
138 }
139 }
140
141 // Generate the argument list.
142 CallArgList Args;
143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
144 const ParmVarDecl *argDecl = *PI++;
145 QualType ArgQT = argDecl->getType().getUnqualifiedType();
146 Args.add(RValue::get(Objects), ArgQT);
147 if (DLE) {
148 argDecl = *PI++;
149 ArgQT = argDecl->getType().getUnqualifiedType();
150 Args.add(RValue::get(Keys), ArgQT);
151 }
152 argDecl = *PI;
153 ArgQT = argDecl->getType().getUnqualifiedType();
154 llvm::Value *Count =
155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
156 Args.add(RValue::get(Count), ArgQT);
157
158 // Generate a reference to the class pointer, which will be the receiver.
159 Selector Sel = MethodWithObjects->getSelector();
160 QualType ResultType = E->getType();
161 const ObjCObjectPointerType *InterfacePointerType
162 = ResultType->getAsObjCInterfacePointerType();
163 ObjCInterfaceDecl *Class
164 = InterfacePointerType->getObjectType()->getInterface();
165 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
166 llvm::Value *Receiver = Runtime.GetClass(Builder, Class);
167
168 // Generate the message send.
Eric Christopher16098f32012-03-29 17:31:31 +0000169 RValue result
170 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
171 MethodWithObjects->getResultType(),
172 Sel,
173 Receiver, Args, Class,
174 MethodWithObjects);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000175 return Builder.CreateBitCast(result.getScalarVal(),
176 ConvertType(E->getType()));
177}
178
179llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
180 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
181}
182
183llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
184 const ObjCDictionaryLiteral *E) {
185 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
186}
187
Chris Lattner8fdf3282008-06-24 17:04:18 +0000188/// Emit a selector.
189llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
190 // Untyped selector.
191 // Note that this implementation allows for non-constant strings to be passed
192 // as arguments to @selector(). Currently, the only thing preventing this
193 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000194 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000195}
196
Daniel Dunbared7c6182008-08-20 00:28:19 +0000197llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
198 // FIXME: This should pass the Decl not the name.
199 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
200}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000201
Douglas Gregor926df6c2011-06-11 01:09:30 +0000202/// \brief Adjust the type of the result of an Objective-C message send
203/// expression when the method has a related result type.
204static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
205 const Expr *E,
206 const ObjCMethodDecl *Method,
207 RValue Result) {
208 if (!Method)
209 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000210
Douglas Gregor926df6c2011-06-11 01:09:30 +0000211 if (!Method->hasRelatedResultType() ||
212 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
213 !Result.isScalar())
214 return Result;
215
216 // We have applied a related result type. Cast the rvalue appropriately.
217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
218 CGF.ConvertType(E->getType())));
219}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000220
John McCalldc7c5ad2011-07-22 08:53:00 +0000221/// Decide whether to extend the lifetime of the receiver of a
222/// returns-inner-pointer message.
223static bool
224shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
225 switch (message->getReceiverKind()) {
226
227 // For a normal instance message, we should extend unless the
228 // receiver is loaded from a variable with precise lifetime.
229 case ObjCMessageExpr::Instance: {
230 const Expr *receiver = message->getInstanceReceiver();
231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
233 receiver = ice->getSubExpr()->IgnoreParens();
234
235 // Only __strong variables.
236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
237 return true;
238
239 // All ivars and fields have precise lifetime.
240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
241 return false;
242
243 // Otherwise, check for variables.
244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
245 if (!declRef) return true;
246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
247 if (!var) return true;
248
249 // All variables have precise lifetime except local variables with
250 // automatic storage duration that aren't specially marked.
251 return (var->hasLocalStorage() &&
252 !var->hasAttr<ObjCPreciseLifetimeAttr>());
253 }
254
255 case ObjCMessageExpr::Class:
256 case ObjCMessageExpr::SuperClass:
257 // It's never necessary for class objects.
258 return false;
259
260 case ObjCMessageExpr::SuperInstance:
261 // We generally assume that 'self' lives throughout a method call.
262 return false;
263 }
264
265 llvm_unreachable("invalid receiver kind");
266}
267
John McCallef072fd2010-05-22 01:48:05 +0000268RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
269 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000270 // Only the lookup mechanism and first two arguments of the method
271 // implementation vary between runtimes. We can get the receiver and
272 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000273
John McCallf85e1932011-06-15 23:02:42 +0000274 bool isDelegateInit = E->isDelegateInitCall();
275
John McCalldc7c5ad2011-07-22 08:53:00 +0000276 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000277
John McCallf85e1932011-06-15 23:02:42 +0000278 // We don't retain the receiver in delegate init calls, and this is
279 // safe because the receiver value is always loaded from 'self',
280 // which we zero out. We don't want to Block_copy block receivers,
281 // though.
282 bool retainSelf =
283 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000284 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000285 method &&
286 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000287
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000288 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000289 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000290 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000291 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000292 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000293 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000294 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000295 switch (E->getReceiverKind()) {
296 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000297 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000298 if (retainSelf) {
299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
300 E->getInstanceReceiver());
301 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000302 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000303 } else
304 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000305 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000306
Douglas Gregor04badcf2010-04-21 00:45:42 +0000307 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000308 ReceiverType = E->getClassReceiver();
309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000310 assert(ObjTy && "Invalid Objective-C class message send");
311 OID = ObjTy->getInterface();
312 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000313 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000314 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000315 break;
316 }
317
318 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000319 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000320 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000321 isSuperMessage = true;
322 break;
323
324 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000325 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000326 Receiver = LoadObjCSelf();
327 isSuperMessage = true;
328 isClassMessage = true;
329 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000330 }
331
John McCalldc7c5ad2011-07-22 08:53:00 +0000332 if (retainSelf)
333 Receiver = EmitARCRetainNonBlock(Receiver);
334
335 // In ARC, we sometimes want to "extend the lifetime"
336 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
337 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000338 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000339 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
340 shouldExtendReceiverForInnerPointerMessage(E))
341 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
342
John McCallf85e1932011-06-15 23:02:42 +0000343 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000344 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000345
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000346 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000347 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
John McCallf85e1932011-06-15 23:02:42 +0000349 // For delegate init calls in ARC, do an unsafe store of null into
350 // self. This represents the call taking direct ownership of that
351 // value. We have to do this after emitting the other call
352 // arguments because they might also reference self, but we don't
353 // have to worry about any of them modifying self because that would
354 // be an undefined read and write of an object in unordered
355 // expressions.
356 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000357 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000358 "delegate init calls should only be marked in ARC");
359
360 // Do an unsafe store of null into self.
361 llvm::Value *selfAddr =
362 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
363 assert(selfAddr && "no self entry for a delegate init call?");
364
365 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
366 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000367
Douglas Gregor926df6c2011-06-11 01:09:30 +0000368 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000369 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000370 // super is only valid in an Objective-C method
371 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000372 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000373 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
374 E->getSelector(),
375 OMD->getClassInterface(),
376 isCategoryImpl,
377 Receiver,
378 isClassMessage,
379 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000380 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000381 } else {
382 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
383 E->getSelector(),
384 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000385 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000386 }
John McCallf85e1932011-06-15 23:02:42 +0000387
388 // For delegate init calls in ARC, implicitly store the result of
389 // the call back into self. This takes ownership of the value.
390 if (isDelegateInit) {
391 llvm::Value *selfAddr =
392 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
393 llvm::Value *newSelf = result.getScalarVal();
394
395 // The delegate return type isn't necessarily a matching type; in
396 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000397 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000398 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
399 newSelf = Builder.CreateBitCast(newSelf, selfTy);
400
401 Builder.CreateStore(newSelf, selfAddr);
402 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000403
404 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000405}
406
John McCallf85e1932011-06-15 23:02:42 +0000407namespace {
408struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000409 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000411
412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000413 const ObjCInterfaceDecl *iface = impl->getClassInterface();
414 if (!iface->getSuperClass()) return;
415
John McCall799d34e2011-07-13 18:26:47 +0000416 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
417
John McCallf85e1932011-06-15 23:02:42 +0000418 // Call [super dealloc] if we have a superclass.
419 llvm::Value *self = CGF.LoadObjCSelf();
420
421 CallArgList args;
422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
423 CGF.getContext().VoidTy,
424 method->getSelector(),
425 iface,
John McCall799d34e2011-07-13 18:26:47 +0000426 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000427 self,
428 /*is class msg*/ false,
429 args,
430 method);
431 }
432};
433}
434
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000435/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
436/// the LLVM function and sets the other context used by
437/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000438void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000439 const ObjCContainerDecl *CD,
440 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000441 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000442 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000443 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
444 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000445
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000446 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000447
John McCallde5d3c72012-02-17 03:33:10 +0000448 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000449 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000450
John McCalld26bc762011-03-09 04:27:21 +0000451 args.push_back(OMD->getSelfDecl());
452 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000453
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000454 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher16098f32012-03-29 17:31:31 +0000455 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000456 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000457
Peter Collingbourne14110472011-01-13 18:57:25 +0000458 CurGD = OMD;
459
Devang Patel8d3f8972011-05-19 23:37:41 +0000460 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000461
462 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000463 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000464 OMD->isInstanceMethod() &&
465 OMD->getSelector().isUnarySelector()) {
466 const IdentifierInfo *ident =
467 OMD->getSelector().getIdentifierInfoForSlot(0);
468 if (ident->isStr("dealloc"))
469 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
470 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000471}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000472
John McCallf85e1932011-06-15 23:02:42 +0000473static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
474 LValue lvalue, QualType type);
475
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000476/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000477/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000478void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000479 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000480 EmitStmt(OMD->getBody());
481 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000482}
483
John McCall41bdde92011-09-12 23:06:44 +0000484/// emitStructGetterCall - Call the runtime function to load a property
485/// into the return value slot.
486static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
487 bool isAtomic, bool hasStrong) {
488 ASTContext &Context = CGF.getContext();
489
490 llvm::Value *src =
491 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
492 ivar, 0).getAddress();
493
494 // objc_copyStruct (ReturnValue, &structIvar,
495 // sizeof (Type of Ivar), isAtomic, false);
496 CallArgList args;
497
498 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
499 args.add(RValue::get(dest), Context.VoidPtrTy);
500
501 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
502 args.add(RValue::get(src), Context.VoidPtrTy);
503
504 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
505 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
506 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
507 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
508
509 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000510 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args,
511 FunctionType::ExtInfo(),
512 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000513 fn, ReturnValueSlot(), args);
514}
515
John McCall1e1f4872011-09-13 03:34:09 +0000516/// Determine whether the given architecture supports unaligned atomic
517/// accesses. They don't have to be fast, just faster than a function
518/// call and a mutex.
519static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000520 // FIXME: Allow unaligned atomic load/store on x86. (It is not
521 // currently supported by the backend.)
522 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000523}
524
525/// Return the maximum size that permits atomic accesses for the given
526/// architecture.
527static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
528 llvm::Triple::ArchType arch) {
529 // ARM has 8-byte atomic accesses, but it's not clear whether we
530 // want to rely on them here.
531
532 // In the default case, just assume that any size up to a pointer is
533 // fine given adequate alignment.
534 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
535}
536
537namespace {
538 class PropertyImplStrategy {
539 public:
540 enum StrategyKind {
541 /// The 'native' strategy is to use the architecture's provided
542 /// reads and writes.
543 Native,
544
545 /// Use objc_setProperty and objc_getProperty.
546 GetSetProperty,
547
548 /// Use objc_setProperty for the setter, but use expression
549 /// evaluation for the getter.
550 SetPropertyAndExpressionGet,
551
552 /// Use objc_copyStruct.
553 CopyStruct,
554
555 /// The 'expression' strategy is to emit normal assignment or
556 /// lvalue-to-rvalue expressions.
557 Expression
558 };
559
560 StrategyKind getKind() const { return StrategyKind(Kind); }
561
562 bool hasStrongMember() const { return HasStrong; }
563 bool isAtomic() const { return IsAtomic; }
564 bool isCopy() const { return IsCopy; }
565
566 CharUnits getIvarSize() const { return IvarSize; }
567 CharUnits getIvarAlignment() const { return IvarAlignment; }
568
569 PropertyImplStrategy(CodeGenModule &CGM,
570 const ObjCPropertyImplDecl *propImpl);
571
572 private:
573 unsigned Kind : 8;
574 unsigned IsAtomic : 1;
575 unsigned IsCopy : 1;
576 unsigned HasStrong : 1;
577
578 CharUnits IvarSize;
579 CharUnits IvarAlignment;
580 };
581}
582
583/// Pick an implementation strategy for the the given property synthesis.
584PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
585 const ObjCPropertyImplDecl *propImpl) {
586 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000587 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000588
John McCall265941b2011-09-13 18:31:23 +0000589 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
590 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000591 HasStrong = false; // doesn't matter here.
592
593 // Evaluate the ivar's size and alignment.
594 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
595 QualType ivarType = ivar->getType();
596 llvm::tie(IvarSize, IvarAlignment)
597 = CGM.getContext().getTypeInfoInChars(ivarType);
598
599 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000600 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000601 if (IsCopy) {
602 Kind = GetSetProperty;
603 return;
604 }
605
John McCall265941b2011-09-13 18:31:23 +0000606 // Handle retain.
607 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000608 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000609 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000610 // fallthrough
611
612 // In ARC, if the property is non-atomic, use expression emission,
613 // which translates to objc_storeStrong. This isn't required, but
614 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000615 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCall1e1f4872011-09-13 03:34:09 +0000616 Kind = Expression;
617 return;
618
619 // Otherwise, we need to at least use setProperty. However, if
620 // the property isn't atomic, we can use normal expression
621 // emission for the getter.
622 } else if (!IsAtomic) {
623 Kind = SetPropertyAndExpressionGet;
624 return;
625
626 // Otherwise, we have to use both setProperty and getProperty.
627 } else {
628 Kind = GetSetProperty;
629 return;
630 }
631 }
632
633 // If we're not atomic, just use expression accesses.
634 if (!IsAtomic) {
635 Kind = Expression;
636 return;
637 }
638
John McCall5889c602011-09-13 05:36:29 +0000639 // Properties on bitfield ivars need to be emitted using expression
640 // accesses even if they're nominally atomic.
641 if (ivar->isBitField()) {
642 Kind = Expression;
643 return;
644 }
645
John McCall1e1f4872011-09-13 03:34:09 +0000646 // GC-qualified or ARC-qualified ivars need to be emitted as
647 // expressions. This actually works out to being atomic anyway,
648 // except for ARC __strong, but that should trigger the above code.
649 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000650 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000651 CGM.getContext().getObjCGCAttrKind(ivarType))) {
652 Kind = Expression;
653 return;
654 }
655
656 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000657 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000658 if (const RecordType *recordType = ivarType->getAs<RecordType>())
659 HasStrong = recordType->getDecl()->hasObjectMember();
660
661 // We can never access structs with object members with a native
662 // access, because we need to use write barriers. This is what
663 // objc_copyStruct is for.
664 if (HasStrong) {
665 Kind = CopyStruct;
666 return;
667 }
668
669 // Otherwise, this is target-dependent and based on the size and
670 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000671
672 // If the size of the ivar is not a power of two, give up. We don't
673 // want to get into the business of doing compare-and-swaps.
674 if (!IvarSize.isPowerOfTwo()) {
675 Kind = CopyStruct;
676 return;
677 }
678
John McCall1e1f4872011-09-13 03:34:09 +0000679 llvm::Triple::ArchType arch =
680 CGM.getContext().getTargetInfo().getTriple().getArch();
681
682 // Most architectures require memory to fit within a single cache
683 // line, so the alignment has to be at least the size of the access.
684 // Otherwise we have to grab a lock.
685 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
686 Kind = CopyStruct;
687 return;
688 }
689
690 // If the ivar's size exceeds the architecture's maximum atomic
691 // access size, we have to use CopyStruct.
692 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
693 Kind = CopyStruct;
694 return;
695 }
696
697 // Otherwise, we can use native loads and stores.
698 Kind = Native;
699}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000700
701/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000702/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
703/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000704void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
705 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000706 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000707 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000708 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
709 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
710 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000711 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000713 generateObjCGetterBody(IMP, PID, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000714
715 FinishFunction();
716}
717
John McCall6c11f0b2011-09-13 06:00:03 +0000718static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
719 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000720 if (!getter) return true;
721
722 // Sema only makes only of these when the ivar has a C++ class type,
723 // so the form is pretty constrained.
724
John McCall6c11f0b2011-09-13 06:00:03 +0000725 // If the property has a reference type, we might just be binding a
726 // reference, in which case the result will be a gl-value. We should
727 // treat this as a non-trivial operation.
728 if (getter->isGLValue())
729 return false;
730
John McCall1e1f4872011-09-13 03:34:09 +0000731 // If we selected a trivial copy-constructor, we're okay.
732 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
733 return (construct->getConstructor()->isTrivial());
734
735 // The constructor might require cleanups (in which case it's never
736 // trivial).
737 assert(isa<ExprWithCleanups>(getter));
738 return false;
739}
740
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000741/// emitCPPObjectAtomicGetterCall - Call the runtime function to
742/// copy the ivar into the resturn slot.
743static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
744 llvm::Value *returnAddr,
745 ObjCIvarDecl *ivar,
746 llvm::Constant *AtomicHelperFn) {
747 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
748 // AtomicHelperFn);
749 CallArgList args;
750
751 // The 1st argument is the return Slot.
752 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
753
754 // The 2nd argument is the address of the ivar.
755 llvm::Value *ivarAddr =
756 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
757 CGF.LoadObjCSelf(), ivar, 0).getAddress();
758 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
759 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
760
761 // Third argument is the helper function.
762 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
763
764 llvm::Value *copyCppAtomicObjectFn =
765 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000766 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
767 FunctionType::ExtInfo(),
768 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000769 copyCppAtomicObjectFn, ReturnValueSlot(), args);
770}
771
John McCall1e1f4872011-09-13 03:34:09 +0000772void
773CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000774 const ObjCPropertyImplDecl *propImpl,
775 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000776 // If there's a non-trivial 'get' expression, we just have to emit that.
777 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000778 if (!AtomicHelperFn) {
779 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
780 /*nrvo*/ 0);
781 EmitReturnStmt(ret);
782 }
783 else {
784 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
785 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
786 ivar, AtomicHelperFn);
787 }
John McCall1e1f4872011-09-13 03:34:09 +0000788 return;
789 }
790
791 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
792 QualType propType = prop->getType();
793 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
794
795 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
796
797 // Pick an implementation strategy.
798 PropertyImplStrategy strategy(CGM, propImpl);
799 switch (strategy.getKind()) {
800 case PropertyImplStrategy::Native: {
801 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
802
803 // Currently, all atomic accesses have to be through integer
804 // types, so there's no point in trying to pick a prettier type.
805 llvm::Type *bitcastType =
806 llvm::Type::getIntNTy(getLLVMContext(),
807 getContext().toBits(strategy.getIvarSize()));
808 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
809
810 // Perform an atomic load. This does not impose ordering constraints.
811 llvm::Value *ivarAddr = LV.getAddress();
812 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
813 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
814 load->setAlignment(strategy.getIvarAlignment().getQuantity());
815 load->setAtomic(llvm::Unordered);
816
817 // Store that value into the return address. Doing this with a
818 // bitcast is likely to produce some pretty ugly IR, but it's not
819 // the *most* terrible thing in the world.
820 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
821
822 // Make sure we don't do an autorelease.
823 AutoreleaseResult = false;
824 return;
825 }
826
827 case PropertyImplStrategy::GetSetProperty: {
828 llvm::Value *getPropertyFn =
829 CGM.getObjCRuntime().GetPropertyGetFunction();
830 if (!getPropertyFn) {
831 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000832 return;
833 }
834
835 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
836 // FIXME: Can't this be simpler? This might even be worse than the
837 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000838 llvm::Value *cmd =
839 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
840 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
841 llvm::Value *ivarOffset =
842 EmitIvarOffset(classImpl->getClassInterface(), ivar);
843
844 CallArgList args;
845 args.add(RValue::get(self), getContext().getObjCIdType());
846 args.add(RValue::get(cmd), getContext().getObjCSelType());
847 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000848 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
849 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000850
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000851 // FIXME: We shouldn't need to get the function info here, the
852 // runtime already should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +0000853 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args,
854 FunctionType::ExtInfo(),
855 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000856 getPropertyFn, ReturnValueSlot(), args);
857
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000858 // We need to fix the type here. Ivars with copy & retain are
859 // always objects so we don't need to worry about complex or
860 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000861 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000862 getTypes().ConvertType(propType)));
863
864 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000865
866 // objc_getProperty does an autorelease, so we should suppress ours.
867 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000868
John McCall1e1f4872011-09-13 03:34:09 +0000869 return;
870 }
871
872 case PropertyImplStrategy::CopyStruct:
873 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
874 strategy.hasStrongMember());
875 return;
876
877 case PropertyImplStrategy::Expression:
878 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
879 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
880
881 QualType ivarType = ivar->getType();
882 if (ivarType->isAnyComplexType()) {
883 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
884 LV.isVolatileQualified());
885 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
886 } else if (hasAggregateLLVMType(ivarType)) {
887 // The return value slot is guaranteed to not be aliased, but
888 // that's not necessarily the same as "on the stack", so
889 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000890 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000891 } else {
John McCallba3dd902011-07-22 05:23:13 +0000892 llvm::Value *value;
893 if (propType->isReferenceType()) {
894 value = LV.getAddress();
895 } else {
896 // We want to load and autoreleaseReturnValue ARC __weak ivars.
897 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000898 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000899
900 // Otherwise we want to do a simple load, suppressing the
901 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000902 } else {
John McCallba3dd902011-07-22 05:23:13 +0000903 value = EmitLoadOfLValue(LV).getScalarVal();
904 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000905 }
John McCallf85e1932011-06-15 23:02:42 +0000906
John McCallba3dd902011-07-22 05:23:13 +0000907 value = Builder.CreateBitCast(value, ConvertType(propType));
908 }
909
910 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000911 }
John McCall1e1f4872011-09-13 03:34:09 +0000912 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000913 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000914
John McCall1e1f4872011-09-13 03:34:09 +0000915 }
916 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000917}
918
John McCall41bdde92011-09-12 23:06:44 +0000919/// emitStructSetterCall - Call the runtime function to store the value
920/// from the first formal parameter into the given ivar.
921static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
922 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000923 // objc_copyStruct (&structIvar, &Arg,
924 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000925 CallArgList args;
926
927 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000928 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
929 CGF.LoadObjCSelf(), ivar, 0)
930 .getAddress();
931 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
932 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000933
934 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000935 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000936 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000937 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000938 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
939 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
940 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000941
942 // The third argument is the sizeof the type.
943 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000944 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
945 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000946
John McCall41bdde92011-09-12 23:06:44 +0000947 // The fourth argument is the 'isAtomic' flag.
948 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000949
John McCall41bdde92011-09-12 23:06:44 +0000950 // The fifth argument is the 'hasStrong' flag.
951 // FIXME: should this really always be false?
952 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
953
954 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000955 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
956 FunctionType::ExtInfo(),
957 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000958 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000959}
960
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000961/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
962/// the value from the first formal parameter into the given ivar, using
963/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
964static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
965 ObjCMethodDecl *OMD,
966 ObjCIvarDecl *ivar,
967 llvm::Constant *AtomicHelperFn) {
968 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
969 // AtomicHelperFn);
970 CallArgList args;
971
972 // The first argument is the address of the ivar.
973 llvm::Value *ivarAddr =
974 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
975 CGF.LoadObjCSelf(), ivar, 0).getAddress();
976 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
977 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
978
979 // The second argument is the address of the parameter variable.
980 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000981 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000982 VK_LValue, SourceLocation());
983 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
984 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
985 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
986
987 // Third argument is the helper function.
988 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
989
990 llvm::Value *copyCppAtomicObjectFn =
991 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000992 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
993 FunctionType::ExtInfo(),
994 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000995 copyCppAtomicObjectFn, ReturnValueSlot(), args);
996
997
998}
999
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001000
John McCall1e1f4872011-09-13 03:34:09 +00001001static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1002 Expr *setter = PID->getSetterCXXAssignment();
1003 if (!setter) return true;
1004
1005 // Sema only makes only of these when the ivar has a C++ class type,
1006 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001007
1008 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001009 // This also implies that there's nothing non-trivial going on with
1010 // the arguments, because operator= can only be trivial if it's a
1011 // synthesized assignment operator and therefore both parameters are
1012 // references.
1013 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001014 if (const FunctionDecl *callee
1015 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1016 if (callee->isTrivial())
1017 return true;
1018 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001019 }
John McCall71c758d2011-09-10 09:17:20 +00001020
John McCall1e1f4872011-09-13 03:34:09 +00001021 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001022 return false;
1023}
1024
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001025static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001026 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001027 return false;
1028 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001029
1030 if (Target.getPlatformName() != "macosx")
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001031 return false;
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001032
1033 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001034}
1035
John McCall71c758d2011-09-10 09:17:20 +00001036void
1037CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001038 const ObjCPropertyImplDecl *propImpl,
1039 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001040 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001041 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001042 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001043
1044 // Just use the setter expression if Sema gave us one and it's
1045 // non-trivial.
1046 if (!hasTrivialSetExpr(propImpl)) {
1047 if (!AtomicHelperFn)
1048 // If non-atomic, assignment is called directly.
1049 EmitStmt(propImpl->getSetterCXXAssignment());
1050 else
1051 // If atomic, assignment is called via a locking api.
1052 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1053 AtomicHelperFn);
1054 return;
1055 }
John McCall71c758d2011-09-10 09:17:20 +00001056
John McCall1e1f4872011-09-13 03:34:09 +00001057 PropertyImplStrategy strategy(CGM, propImpl);
1058 switch (strategy.getKind()) {
1059 case PropertyImplStrategy::Native: {
1060 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001061
John McCall1e1f4872011-09-13 03:34:09 +00001062 LValue ivarLValue =
1063 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1064 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001065
John McCall1e1f4872011-09-13 03:34:09 +00001066 // Currently, all atomic accesses have to be through integer
1067 // types, so there's no point in trying to pick a prettier type.
1068 llvm::Type *bitcastType =
1069 llvm::Type::getIntNTy(getLLVMContext(),
1070 getContext().toBits(strategy.getIvarSize()));
1071 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1072
1073 // Cast both arguments to the chosen operation type.
1074 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1075 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1076
1077 // This bitcast load is likely to cause some nasty IR.
1078 llvm::Value *load = Builder.CreateLoad(argAddr);
1079
1080 // Perform an atomic store. There are no memory ordering requirements.
1081 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1082 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1083 store->setAtomic(llvm::Unordered);
1084 return;
1085 }
1086
1087 case PropertyImplStrategy::GetSetProperty:
1088 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001089
1090 llvm::Value *setOptimizedPropertyFn = 0;
1091 llvm::Value *setPropertyFn = 0;
1092 if (UseOptimizedSetter(CGM)) {
1093 // 10.8 code and GC is off
1094 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001095 CGM.getObjCRuntime()
1096 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1097 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001098 if (!setOptimizedPropertyFn) {
1099 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1100 return;
1101 }
John McCall71c758d2011-09-10 09:17:20 +00001102 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001103 else {
1104 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1105 if (!setPropertyFn) {
1106 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1107 return;
1108 }
1109 }
1110
John McCall71c758d2011-09-10 09:17:20 +00001111 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1112 // <is-atomic>, <is-copy>).
1113 llvm::Value *cmd =
1114 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1115 llvm::Value *self =
1116 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1117 llvm::Value *ivarOffset =
1118 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1119 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1120 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1121
1122 CallArgList args;
1123 args.add(RValue::get(self), getContext().getObjCIdType());
1124 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001125 if (setOptimizedPropertyFn) {
1126 args.add(RValue::get(arg), getContext().getObjCIdType());
1127 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1128 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1129 FunctionType::ExtInfo(),
1130 RequiredArgs::All),
1131 setOptimizedPropertyFn, ReturnValueSlot(), args);
1132 } else {
1133 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1134 args.add(RValue::get(arg), getContext().getObjCIdType());
1135 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1136 getContext().BoolTy);
1137 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1138 getContext().BoolTy);
1139 // FIXME: We shouldn't need to get the function info here, the runtime
1140 // already should have computed it to build the function.
1141 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1142 FunctionType::ExtInfo(),
1143 RequiredArgs::All),
1144 setPropertyFn, ReturnValueSlot(), args);
1145 }
1146
John McCall71c758d2011-09-10 09:17:20 +00001147 return;
1148 }
1149
John McCall1e1f4872011-09-13 03:34:09 +00001150 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001151 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001152 return;
John McCall1e1f4872011-09-13 03:34:09 +00001153
1154 case PropertyImplStrategy::Expression:
1155 break;
John McCall71c758d2011-09-10 09:17:20 +00001156 }
1157
1158 // Otherwise, fake up some ASTs and emit a normal assignment.
1159 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001160 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1161 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001162 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1163 selfDecl->getType(), CK_LValueToRValue, &self,
1164 VK_RValue);
1165 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1166 SourceLocation(), &selfLoad, true, true);
1167
1168 ParmVarDecl *argDecl = *setterMethod->param_begin();
1169 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001170 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001171 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1172 argType.getUnqualifiedType(), CK_LValueToRValue,
1173 &arg, VK_RValue);
1174
1175 // The property type can differ from the ivar type in some situations with
1176 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1177 // The following absurdity is just to ensure well-formed IR.
1178 CastKind argCK = CK_NoOp;
1179 if (ivarRef.getType()->isObjCObjectPointerType()) {
1180 if (argLoad.getType()->isObjCObjectPointerType())
1181 argCK = CK_BitCast;
1182 else if (argLoad.getType()->isBlockPointerType())
1183 argCK = CK_BlockPointerToObjCPointerCast;
1184 else
1185 argCK = CK_CPointerToObjCPointerCast;
1186 } else if (ivarRef.getType()->isBlockPointerType()) {
1187 if (argLoad.getType()->isBlockPointerType())
1188 argCK = CK_BitCast;
1189 else
1190 argCK = CK_AnyPointerToBlockPointerCast;
1191 } else if (ivarRef.getType()->isPointerType()) {
1192 argCK = CK_BitCast;
1193 }
1194 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1195 ivarRef.getType(), argCK, &argLoad,
1196 VK_RValue);
1197 Expr *finalArg = &argLoad;
1198 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1199 argLoad.getType()))
1200 finalArg = &argCast;
1201
1202
1203 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1204 ivarRef.getType(), VK_RValue, OK_Ordinary,
1205 SourceLocation());
1206 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001207}
1208
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001209/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +00001210/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1211/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001212void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1213 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001214 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001215 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001216 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1217 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1218 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001219 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001220
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001221 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001222
1223 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001224}
1225
John McCalle81ac692011-03-22 07:05:39 +00001226namespace {
John McCall9928c482011-07-12 16:41:08 +00001227 struct DestroyIvar : EHScopeStack::Cleanup {
1228 private:
1229 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001230 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001231 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001232 bool useEHCleanupForArray;
1233 public:
1234 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1235 CodeGenFunction::Destroyer *destroyer,
1236 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001237 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001238 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001239
John McCallad346f42011-07-12 20:27:29 +00001240 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001241 LValue lvalue
1242 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1243 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001244 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001245 }
1246 };
1247}
1248
John McCall9928c482011-07-12 16:41:08 +00001249/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1250static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1251 llvm::Value *addr,
1252 QualType type) {
1253 llvm::Value *null = getNullForVariable(addr);
1254 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1255}
John McCallf85e1932011-06-15 23:02:42 +00001256
John McCalle81ac692011-03-22 07:05:39 +00001257static void emitCXXDestructMethod(CodeGenFunction &CGF,
1258 ObjCImplementationDecl *impl) {
1259 CodeGenFunction::RunCleanupsScope scope(CGF);
1260
1261 llvm::Value *self = CGF.LoadObjCSelf();
1262
Jordy Rosedb8264e2011-07-22 02:08:32 +00001263 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1264 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001265 ivar; ivar = ivar->getNextIvar()) {
1266 QualType type = ivar->getType();
1267
John McCalle81ac692011-03-22 07:05:39 +00001268 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001269 QualType::DestructionKind dtorKind = type.isDestructedType();
1270 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001271
John McCall9928c482011-07-12 16:41:08 +00001272 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001273
John McCall9928c482011-07-12 16:41:08 +00001274 // Use a call to objc_storeStrong to destroy strong ivars, for the
1275 // general benefit of the tools.
1276 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001277 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001278
John McCall9928c482011-07-12 16:41:08 +00001279 // Otherwise use the default for the destruction kind.
1280 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001281 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001282 }
John McCall9928c482011-07-12 16:41:08 +00001283
1284 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1285
1286 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1287 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001288 }
1289
1290 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1291}
1292
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001293void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1294 ObjCMethodDecl *MD,
1295 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001296 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001297 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001298
1299 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001300 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001301 // Suppress the final autorelease in ARC.
1302 AutoreleaseResult = false;
1303
Chris Lattner5f9e2722011-07-23 10:55:15 +00001304 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001305 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1306 E = IMP->init_end(); B != E; ++B) {
1307 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001308 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001309 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001310 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1311 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001312 EmitAggExpr(IvarInit->getInit(),
1313 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001314 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001315 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001316 }
1317 // constructor returns 'self'.
1318 CodeGenTypes &Types = CGM.getTypes();
1319 QualType IdTy(CGM.getContext().getObjCIdType());
1320 llvm::Value *SelfAsId =
1321 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1322 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001323
1324 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001325 } else {
John McCalle81ac692011-03-22 07:05:39 +00001326 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001327 }
1328 FinishFunction();
1329}
1330
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001331bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1332 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1333 it++; it++;
1334 const ABIArgInfo &AI = it->info;
1335 // FIXME. Is this sufficient check?
1336 return (AI.getKind() == ABIArgInfo::Indirect);
1337}
1338
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001339bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001340 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001341 return false;
1342 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1343 return FDTTy->getDecl()->hasObjectMember();
1344 return false;
1345}
1346
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001347llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001348 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1349 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001350}
1351
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001352QualType CodeGenFunction::TypeOfSelfObject() {
1353 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1354 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001355 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1356 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001357 return PTy->getPointeeType();
1358}
1359
Chris Lattner74391b42009-03-22 21:03:39 +00001360void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001361 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001362 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001364 if (!EnumerationMutationFn) {
1365 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1366 return;
1367 }
1368
Devang Patelbcbd03a2011-01-19 01:36:36 +00001369 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001370 if (DI)
1371 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001372
Devang Patel9d99f2d2011-06-13 23:15:32 +00001373 // The local variable comes into scope immediately.
1374 AutoVarEmission variable = AutoVarEmission::invalid();
1375 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1376 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1377
John McCalld88687f2011-01-07 01:49:06 +00001378 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001379
Anders Carlssonf484c312008-08-31 02:33:12 +00001380 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001381 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001382 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001383 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Anders Carlssonf484c312008-08-31 02:33:12 +00001385 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001386 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001387
John McCalld88687f2011-01-07 01:49:06 +00001388 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001389 IdentifierInfo *II[] = {
1390 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1391 &CGM.getContext().Idents.get("objects"),
1392 &CGM.getContext().Idents.get("count")
1393 };
1394 Selector FastEnumSel =
1395 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001396
1397 QualType ItemsTy =
1398 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001399 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001400 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001401 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001402
John McCall990567c2011-07-27 01:07:15 +00001403 // Emit the collection pointer. In ARC, we do a retain.
1404 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001405 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001406 Collection = EmitARCRetainScalarExpr(S.getCollection());
1407
1408 // Enter a cleanup to do the release.
1409 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1410 } else {
1411 Collection = EmitScalarExpr(S.getCollection());
1412 }
Mike Stump1eb44332009-09-09 15:08:12 +00001413
John McCall4b302d32011-08-05 00:14:38 +00001414 // The 'continue' label needs to appear within the cleanup for the
1415 // collection object.
1416 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1417
John McCalld88687f2011-01-07 01:49:06 +00001418 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001419 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001420
1421 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001422 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001423
John McCalld88687f2011-01-07 01:49:06 +00001424 // The second argument is a temporary array with space for NumItems
1425 // pointers. We'll actually be loading elements from the array
1426 // pointer written into the control state; this buffer is so that
1427 // collections that *aren't* backed by arrays can still queue up
1428 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001429 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001430
John McCalld88687f2011-01-07 01:49:06 +00001431 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001432 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001433 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001434 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
John McCalld88687f2011-01-07 01:49:06 +00001436 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001437 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001438 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001439 getContext().UnsignedLongTy,
1440 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001441 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001442
John McCalld88687f2011-01-07 01:49:06 +00001443 // The initial number of objects that were returned in the buffer.
1444 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001445
John McCalld88687f2011-01-07 01:49:06 +00001446 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1447 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001448
John McCalld88687f2011-01-07 01:49:06 +00001449 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001450
John McCalld88687f2011-01-07 01:49:06 +00001451 // If the limit pointer was zero to begin with, the collection is
1452 // empty; skip all this.
1453 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1454 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001455
John McCalld88687f2011-01-07 01:49:06 +00001456 // Otherwise, initialize the loop.
1457 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCalld88687f2011-01-07 01:49:06 +00001459 // Save the initial mutations value. This is the value at an
1460 // address that was written into the state object by
1461 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001462 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001463 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001464 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001465 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001466
John McCalld88687f2011-01-07 01:49:06 +00001467 llvm::Value *initialMutations =
1468 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001469
John McCalld88687f2011-01-07 01:49:06 +00001470 // Start looping. This is the point we return to whenever we have a
1471 // fresh, non-empty batch of objects.
1472 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1473 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001474
John McCalld88687f2011-01-07 01:49:06 +00001475 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001476 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001477 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001478
John McCalld88687f2011-01-07 01:49:06 +00001479 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001480 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001481 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
John McCalld88687f2011-01-07 01:49:06 +00001483 // Check whether the mutations value has changed from where it was
1484 // at start. StateMutationsPtr should actually be invariant between
1485 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001486 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001487 llvm::Value *currentMutations
1488 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001489
John McCalld88687f2011-01-07 01:49:06 +00001490 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001491 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001492
John McCalld88687f2011-01-07 01:49:06 +00001493 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1494 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
John McCalld88687f2011-01-07 01:49:06 +00001496 // If so, call the enumeration-mutation function.
1497 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001498 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001499 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001500 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001501 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001502 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001503 // FIXME: We shouldn't need to get the function info here, the runtime already
1504 // should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +00001505 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1506 FunctionType::ExtInfo(),
1507 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001508 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
John McCalld88687f2011-01-07 01:49:06 +00001510 // Otherwise, or if the mutation function returns, just continue.
1511 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
John McCalld88687f2011-01-07 01:49:06 +00001513 // Initialize the element variable.
1514 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001515 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001516 LValue elementLValue;
1517 QualType elementType;
1518 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001519 // Initialize the variable, in case it's a __block variable or something.
1520 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001521
John McCall57b3b6a2011-02-22 07:16:58 +00001522 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001523 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001524 VK_LValue, SourceLocation());
1525 elementLValue = EmitLValue(&tempDRE);
1526 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001527 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001528
1529 if (D->isARCPseudoStrong())
1530 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001531 } else {
1532 elementLValue = LValue(); // suppress warning
1533 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001534 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001535 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001536 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001537
1538 // Fetch the buffer out of the enumeration state.
1539 // TODO: this pointer should actually be invariant between
1540 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001541 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001542 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001543 llvm::Value *EnumStateItems =
1544 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001545
John McCalld88687f2011-01-07 01:49:06 +00001546 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001547 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001548 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1549 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001550
John McCalld88687f2011-01-07 01:49:06 +00001551 // Cast that value to the right type.
1552 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1553 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001554
John McCalld88687f2011-01-07 01:49:06 +00001555 // Make sure we have an l-value. Yes, this gets evaluated every
1556 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001557 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001558 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001559 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001560 } else {
1561 EmitScalarInit(CurrentItem, elementLValue);
1562 }
Mike Stump1eb44332009-09-09 15:08:12 +00001563
John McCall57b3b6a2011-02-22 07:16:58 +00001564 // If we do have an element variable, this assignment is the end of
1565 // its initialization.
1566 if (elementIsVariable)
1567 EmitAutoVarCleanups(variable);
1568
John McCalld88687f2011-01-07 01:49:06 +00001569 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001570 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001571 {
1572 RunCleanupsScope Scope(*this);
1573 EmitStmt(S.getBody());
1574 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001575 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001576
John McCalld88687f2011-01-07 01:49:06 +00001577 // Destroy the element variable now.
1578 elementVariableScope.ForceCleanup();
1579
1580 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001581 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001582
John McCalld88687f2011-01-07 01:49:06 +00001583 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001584
John McCalld88687f2011-01-07 01:49:06 +00001585 // First we check in the local buffer.
1586 llvm::Value *indexPlusOne
1587 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001588
John McCalld88687f2011-01-07 01:49:06 +00001589 // If we haven't overrun the buffer yet, we can continue.
1590 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1591 LoopBodyBB, FetchMoreBB);
1592
1593 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1594 count->addIncoming(count, AfterBody.getBlock());
1595
1596 // Otherwise, we have to fetch more elements.
1597 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001598
1599 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001600 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001601 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001602 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001603 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001604
John McCalld88687f2011-01-07 01:49:06 +00001605 // If we got a zero count, we're done.
1606 llvm::Value *refetchCount = CountRV.getScalarVal();
1607
1608 // (note that the message send might split FetchMoreBB)
1609 index->addIncoming(zero, Builder.GetInsertBlock());
1610 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1611
1612 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1613 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Anders Carlssonf484c312008-08-31 02:33:12 +00001615 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001616 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001617
John McCall57b3b6a2011-02-22 07:16:58 +00001618 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001619 // If the element was not a declaration, set it to be null.
1620
John McCalld88687f2011-01-07 01:49:06 +00001621 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1622 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001623 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001624 }
1625
Eric Christopher73fb3502011-10-13 21:45:18 +00001626 if (DI)
1627 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001628
John McCall990567c2011-07-27 01:07:15 +00001629 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001630 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001631 PopCleanupBlock();
1632
John McCallff8e1152010-07-23 21:56:41 +00001633 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001634}
1635
Mike Stump1eb44332009-09-09 15:08:12 +00001636void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001637 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001638}
1639
Mike Stump1eb44332009-09-09 15:08:12 +00001640void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001641 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1642}
1643
Chris Lattner10cac6f2008-11-15 21:26:17 +00001644void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001645 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001646 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001647}
1648
John McCall33e56f32011-09-10 06:18:15 +00001649/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001650/// primitive retain.
1651llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1652 llvm::Value *value) {
1653 return EmitARCRetain(type, value);
1654}
1655
1656namespace {
1657 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001658 CallObjCRelease(llvm::Value *object) : object(object) {}
1659 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001660
John McCallad346f42011-07-12 20:27:29 +00001661 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001662 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001663 }
1664 };
1665}
1666
John McCall33e56f32011-09-10 06:18:15 +00001667/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001668/// release at the end of the full-expression.
1669llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1670 llvm::Value *object) {
1671 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001672 // conditional.
1673 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001674 return object;
1675}
1676
1677llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1678 llvm::Value *value) {
1679 return EmitARCRetainAutorelease(type, value);
1680}
1681
1682
1683static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001684 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001685 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001686 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1687
1688 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1689 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001690 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001691 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1692 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1693
1694 return fn;
1695}
1696
1697/// Perform an operation having the signature
1698/// i8* (i8*)
1699/// where a null input causes a no-op and returns null.
1700static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1701 llvm::Value *value,
1702 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001703 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001704 if (isa<llvm::ConstantPointerNull>(value)) return value;
1705
1706 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001707 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001708 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001709 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1710 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1711 }
1712
1713 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001714 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001715 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1716
1717 // Call the function.
1718 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1719 call->setDoesNotThrow();
1720
1721 // Cast the result back to the original type.
1722 return CGF.Builder.CreateBitCast(call, origType);
1723}
1724
1725/// Perform an operation having the following signature:
1726/// i8* (i8**)
1727static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1728 llvm::Value *addr,
1729 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001730 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001731 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001732 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001733 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001734 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1735 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1736 }
1737
1738 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001739 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001740 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1741
1742 // Call the function.
1743 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1744 call->setDoesNotThrow();
1745
1746 // Cast the result back to a dereference of the original type.
1747 llvm::Value *result = call;
1748 if (origType != CGF.Int8PtrPtrTy)
1749 result = CGF.Builder.CreateBitCast(result,
1750 cast<llvm::PointerType>(origType)->getElementType());
1751
1752 return result;
1753}
1754
1755/// Perform an operation having the following signature:
1756/// i8* (i8**, i8*)
1757static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1758 llvm::Value *addr,
1759 llvm::Value *value,
1760 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001761 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001762 bool ignored) {
1763 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1764 == value->getType());
1765
1766 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001767 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001768
Chris Lattner2acc6e32011-07-18 04:24:23 +00001769 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001770 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1771 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1772 }
1773
Chris Lattner2acc6e32011-07-18 04:24:23 +00001774 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001775
1776 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1777 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1778
1779 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1780 result->setDoesNotThrow();
1781
1782 if (ignored) return 0;
1783
1784 return CGF.Builder.CreateBitCast(result, origType);
1785}
1786
1787/// Perform an operation having the following signature:
1788/// void (i8**, i8**)
1789static void emitARCCopyOperation(CodeGenFunction &CGF,
1790 llvm::Value *dst,
1791 llvm::Value *src,
1792 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001793 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001794 assert(dst->getType() == src->getType());
1795
1796 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001797 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001798 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001799 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1800 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1801 }
1802
1803 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1804 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1805
1806 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1807 result->setDoesNotThrow();
1808}
1809
1810/// Produce the code to do a retain. Based on the type, calls one of:
1811/// call i8* @objc_retain(i8* %value)
1812/// call i8* @objc_retainBlock(i8* %value)
1813llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1814 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001815 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001816 else
1817 return EmitARCRetainNonBlock(value);
1818}
1819
1820/// Retain the given object, with normal retain semantics.
1821/// call i8* @objc_retain(i8* %value)
1822llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1823 return emitARCValueOperation(*this, value,
1824 CGM.getARCEntrypoints().objc_retain,
1825 "objc_retain");
1826}
1827
1828/// Retain the given block, with _Block_copy semantics.
1829/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001830///
1831/// \param mandatory - If false, emit the call with metadata
1832/// indicating that it's okay for the optimizer to eliminate this call
1833/// if it can prove that the block never escapes except down the stack.
1834llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1835 bool mandatory) {
1836 llvm::Value *result
1837 = emitARCValueOperation(*this, value,
1838 CGM.getARCEntrypoints().objc_retainBlock,
1839 "objc_retainBlock");
1840
1841 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1842 // tell the optimizer that it doesn't need to do this copy if the
1843 // block doesn't escape, where being passed as an argument doesn't
1844 // count as escaping.
1845 if (!mandatory && isa<llvm::Instruction>(result)) {
1846 llvm::CallInst *call
1847 = cast<llvm::CallInst>(result->stripPointerCasts());
1848 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1849
1850 SmallVector<llvm::Value*,1> args;
1851 call->setMetadata("clang.arc.copy_on_escape",
1852 llvm::MDNode::get(Builder.getContext(), args));
1853 }
1854
1855 return result;
John McCallf85e1932011-06-15 23:02:42 +00001856}
1857
1858/// Retain the given object which is the result of a function call.
1859/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1860///
1861/// Yes, this function name is one character away from a different
1862/// call with completely different semantics.
1863llvm::Value *
1864CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1865 // Fetch the void(void) inline asm which marks that we're going to
1866 // retain the autoreleased return value.
1867 llvm::InlineAsm *&marker
1868 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1869 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001870 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001871 = CGM.getTargetCodeGenInfo()
1872 .getARCRetainAutoreleasedReturnValueMarker();
1873
1874 // If we have an empty assembly string, there's nothing to do.
1875 if (assembly.empty()) {
1876
1877 // Otherwise, at -O0, build an inline asm that we're going to call
1878 // in a moment.
1879 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1880 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001881 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001882
1883 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1884
1885 // If we're at -O1 and above, we don't want to litter the code
1886 // with this marker yet, so leave a breadcrumb for the ARC
1887 // optimizer to pick up.
1888 } else {
1889 llvm::NamedMDNode *metadata =
1890 CGM.getModule().getOrInsertNamedMetadata(
1891 "clang.arc.retainAutoreleasedReturnValueMarker");
1892 assert(metadata->getNumOperands() <= 1);
1893 if (metadata->getNumOperands() == 0) {
1894 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001895 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001896 }
1897 }
1898 }
1899
1900 // Call the marker asm if we made one, which we do only at -O0.
1901 if (marker) Builder.CreateCall(marker);
1902
1903 return emitARCValueOperation(*this, value,
1904 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1905 "objc_retainAutoreleasedReturnValue");
1906}
1907
1908/// Release the given object.
1909/// call void @objc_release(i8* %value)
1910void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1911 if (isa<llvm::ConstantPointerNull>(value)) return;
1912
1913 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1914 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001915 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001916 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001917 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1918 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1919 }
1920
1921 // Cast the argument to 'id'.
1922 value = Builder.CreateBitCast(value, Int8PtrTy);
1923
1924 // Call objc_release.
1925 llvm::CallInst *call = Builder.CreateCall(fn, value);
1926 call->setDoesNotThrow();
1927
1928 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001929 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001930 call->setMetadata("clang.imprecise_release",
1931 llvm::MDNode::get(Builder.getContext(), args));
1932 }
1933}
1934
1935/// Store into a strong object. Always calls this:
1936/// call void @objc_storeStrong(i8** %addr, i8* %value)
1937llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1938 llvm::Value *value,
1939 bool ignored) {
1940 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1941 == value->getType());
1942
1943 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1944 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001945 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001946 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001947 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1948 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1949 }
1950
1951 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1952 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1953
1954 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1955
1956 if (ignored) return 0;
1957 return value;
1958}
1959
1960/// Store into a strong object. Sometimes calls this:
1961/// call void @objc_storeStrong(i8** %addr, i8* %value)
1962/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001963llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001964 llvm::Value *newValue,
1965 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001966 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001967 bool isBlock = type->isBlockPointerType();
1968
1969 // Use a store barrier at -O0 unless this is a block type or the
1970 // lvalue is inadequately aligned.
1971 if (shouldUseFusedARCCalls() &&
1972 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001973 (dst.getAlignment().isZero() ||
1974 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001975 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1976 }
1977
1978 // Otherwise, split it out.
1979
1980 // Retain the new value.
1981 newValue = EmitARCRetain(type, newValue);
1982
1983 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001984 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001985
1986 // Store. We do this before the release so that any deallocs won't
1987 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001988 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001989
1990 // Finally, release the old value.
1991 EmitARCRelease(oldValue, /*precise*/ false);
1992
1993 return newValue;
1994}
1995
1996/// Autorelease the given object.
1997/// call i8* @objc_autorelease(i8* %value)
1998llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1999 return emitARCValueOperation(*this, value,
2000 CGM.getARCEntrypoints().objc_autorelease,
2001 "objc_autorelease");
2002}
2003
2004/// Autorelease the given object.
2005/// call i8* @objc_autoreleaseReturnValue(i8* %value)
2006llvm::Value *
2007CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2008 return emitARCValueOperation(*this, value,
2009 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2010 "objc_autoreleaseReturnValue");
2011}
2012
2013/// Do a fused retain/autorelease of the given object.
2014/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
2015llvm::Value *
2016CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2017 return emitARCValueOperation(*this, value,
2018 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2019 "objc_retainAutoreleaseReturnValue");
2020}
2021
2022/// Do a fused retain/autorelease of the given object.
2023/// call i8* @objc_retainAutorelease(i8* %value)
2024/// or
2025/// %retain = call i8* @objc_retainBlock(i8* %value)
2026/// call i8* @objc_autorelease(i8* %retain)
2027llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2028 llvm::Value *value) {
2029 if (!type->isBlockPointerType())
2030 return EmitARCRetainAutoreleaseNonBlock(value);
2031
2032 if (isa<llvm::ConstantPointerNull>(value)) return value;
2033
Chris Lattner2acc6e32011-07-18 04:24:23 +00002034 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002035 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002036 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002037 value = EmitARCAutorelease(value);
2038 return Builder.CreateBitCast(value, origType);
2039}
2040
2041/// Do a fused retain/autorelease of the given object.
2042/// call i8* @objc_retainAutorelease(i8* %value)
2043llvm::Value *
2044CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2045 return emitARCValueOperation(*this, value,
2046 CGM.getARCEntrypoints().objc_retainAutorelease,
2047 "objc_retainAutorelease");
2048}
2049
2050/// i8* @objc_loadWeak(i8** %addr)
2051/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2052llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2053 return emitARCLoadOperation(*this, addr,
2054 CGM.getARCEntrypoints().objc_loadWeak,
2055 "objc_loadWeak");
2056}
2057
2058/// i8* @objc_loadWeakRetained(i8** %addr)
2059llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2060 return emitARCLoadOperation(*this, addr,
2061 CGM.getARCEntrypoints().objc_loadWeakRetained,
2062 "objc_loadWeakRetained");
2063}
2064
2065/// i8* @objc_storeWeak(i8** %addr, i8* %value)
2066/// Returns %value.
2067llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2068 llvm::Value *value,
2069 bool ignored) {
2070 return emitARCStoreOperation(*this, addr, value,
2071 CGM.getARCEntrypoints().objc_storeWeak,
2072 "objc_storeWeak", ignored);
2073}
2074
2075/// i8* @objc_initWeak(i8** %addr, i8* %value)
2076/// Returns %value. %addr is known to not have a current weak entry.
2077/// Essentially equivalent to:
2078/// *addr = nil; objc_storeWeak(addr, value);
2079void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2080 // If we're initializing to null, just write null to memory; no need
2081 // to get the runtime involved. But don't do this if optimization
2082 // is enabled, because accounting for this would make the optimizer
2083 // much more complicated.
2084 if (isa<llvm::ConstantPointerNull>(value) &&
2085 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2086 Builder.CreateStore(value, addr);
2087 return;
2088 }
2089
2090 emitARCStoreOperation(*this, addr, value,
2091 CGM.getARCEntrypoints().objc_initWeak,
2092 "objc_initWeak", /*ignored*/ true);
2093}
2094
2095/// void @objc_destroyWeak(i8** %addr)
2096/// Essentially objc_storeWeak(addr, nil).
2097void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2098 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2099 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002100 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002101 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002102 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2103 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2104 }
2105
2106 // Cast the argument to 'id*'.
2107 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2108
2109 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2110 call->setDoesNotThrow();
2111}
2112
2113/// void @objc_moveWeak(i8** %dest, i8** %src)
2114/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2115/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2116void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2117 emitARCCopyOperation(*this, dst, src,
2118 CGM.getARCEntrypoints().objc_moveWeak,
2119 "objc_moveWeak");
2120}
2121
2122/// void @objc_copyWeak(i8** %dest, i8** %src)
2123/// Disregards the current value in %dest. Essentially
2124/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2125void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2126 emitARCCopyOperation(*this, dst, src,
2127 CGM.getARCEntrypoints().objc_copyWeak,
2128 "objc_copyWeak");
2129}
2130
2131/// Produce the code to do a objc_autoreleasepool_push.
2132/// call i8* @objc_autoreleasePoolPush(void)
2133llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2134 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2135 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002136 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002137 llvm::FunctionType::get(Int8PtrTy, false);
2138 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2139 }
2140
2141 llvm::CallInst *call = Builder.CreateCall(fn);
2142 call->setDoesNotThrow();
2143
2144 return call;
2145}
2146
2147/// Produce the code to do a primitive release.
2148/// call void @objc_autoreleasePoolPop(i8* %ptr)
2149void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2150 assert(value->getType() == Int8PtrTy);
2151
2152 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2153 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002154 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002155 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002156 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2157
2158 // We don't want to use a weak import here; instead we should not
2159 // fall into this path.
2160 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2161 }
2162
2163 llvm::CallInst *call = Builder.CreateCall(fn, value);
2164 call->setDoesNotThrow();
2165}
2166
2167/// Produce the code to do an MRR version objc_autoreleasepool_push.
2168/// Which is: [[NSAutoreleasePool alloc] init];
2169/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2170/// init is declared as: - (id) init; in its NSObject super class.
2171///
2172llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2173 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2174 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2175 // [NSAutoreleasePool alloc]
2176 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2177 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2178 CallArgList Args;
2179 RValue AllocRV =
2180 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2181 getContext().getObjCIdType(),
2182 AllocSel, Receiver, Args);
2183
2184 // [Receiver init]
2185 Receiver = AllocRV.getScalarVal();
2186 II = &CGM.getContext().Idents.get("init");
2187 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2188 RValue InitRV =
2189 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2190 getContext().getObjCIdType(),
2191 InitSel, Receiver, Args);
2192 return InitRV.getScalarVal();
2193}
2194
2195/// Produce the code to do a primitive release.
2196/// [tmp drain];
2197void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2198 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2199 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2200 CallArgList Args;
2201 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2202 getContext().VoidTy, DrainSel, Arg, Args);
2203}
2204
John McCallbdc4d802011-07-09 01:37:26 +00002205void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2206 llvm::Value *addr,
2207 QualType type) {
2208 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2209 CGF.EmitARCRelease(ptr, /*precise*/ true);
2210}
2211
2212void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2213 llvm::Value *addr,
2214 QualType type) {
2215 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2216 CGF.EmitARCRelease(ptr, /*precise*/ false);
2217}
2218
2219void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2220 llvm::Value *addr,
2221 QualType type) {
2222 CGF.EmitARCDestroyWeak(addr);
2223}
2224
John McCallf85e1932011-06-15 23:02:42 +00002225namespace {
John McCallf85e1932011-06-15 23:02:42 +00002226 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2227 llvm::Value *Token;
2228
2229 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2230
John McCallad346f42011-07-12 20:27:29 +00002231 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002232 CGF.EmitObjCAutoreleasePoolPop(Token);
2233 }
2234 };
2235 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2236 llvm::Value *Token;
2237
2238 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2239
John McCallad346f42011-07-12 20:27:29 +00002240 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002241 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2242 }
2243 };
2244}
2245
2246void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002247 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002248 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2249 else
2250 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2251}
2252
John McCallf85e1932011-06-15 23:02:42 +00002253static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2254 LValue lvalue,
2255 QualType type) {
2256 switch (type.getObjCLifetime()) {
2257 case Qualifiers::OCL_None:
2258 case Qualifiers::OCL_ExplicitNone:
2259 case Qualifiers::OCL_Strong:
2260 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002261 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002262 false);
2263
2264 case Qualifiers::OCL_Weak:
2265 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2266 true);
2267 }
2268
2269 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002270}
2271
2272static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2273 const Expr *e) {
2274 e = e->IgnoreParens();
2275 QualType type = e->getType();
2276
John McCall21480112011-08-30 00:57:29 +00002277 // If we're loading retained from a __strong xvalue, we can avoid
2278 // an extra retain/release pair by zeroing out the source of this
2279 // "move" operation.
2280 if (e->isXValue() &&
2281 !type.isConstQualified() &&
2282 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2283 // Emit the lvalue.
2284 LValue lv = CGF.EmitLValue(e);
2285
2286 // Load the object pointer.
2287 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2288
2289 // Set the source pointer to NULL.
2290 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2291
2292 return TryEmitResult(result, true);
2293 }
2294
John McCallf85e1932011-06-15 23:02:42 +00002295 // As a very special optimization, in ARC++, if the l-value is the
2296 // result of a non-volatile assignment, do a simple retain of the
2297 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002298 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002299 !type.isVolatileQualified() &&
2300 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2301 isa<BinaryOperator>(e) &&
2302 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2303 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2304
2305 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2306}
2307
2308static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2309 llvm::Value *value);
2310
2311/// Given that the given expression is some sort of call (which does
2312/// not return retained), emit a retain following it.
2313static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2314 llvm::Value *value = CGF.EmitScalarExpr(e);
2315 return emitARCRetainAfterCall(CGF, value);
2316}
2317
2318static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2319 llvm::Value *value) {
2320 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2321 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2322
2323 // Place the retain immediately following the call.
2324 CGF.Builder.SetInsertPoint(call->getParent(),
2325 ++llvm::BasicBlock::iterator(call));
2326 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2327
2328 CGF.Builder.restoreIP(ip);
2329 return value;
2330 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2331 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2332
2333 // Place the retain at the beginning of the normal destination block.
2334 llvm::BasicBlock *BB = invoke->getNormalDest();
2335 CGF.Builder.SetInsertPoint(BB, BB->begin());
2336 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2337
2338 CGF.Builder.restoreIP(ip);
2339 return value;
2340
2341 // Bitcasts can arise because of related-result returns. Rewrite
2342 // the operand.
2343 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2344 llvm::Value *operand = bitcast->getOperand(0);
2345 operand = emitARCRetainAfterCall(CGF, operand);
2346 bitcast->setOperand(0, operand);
2347 return bitcast;
2348
2349 // Generic fall-back case.
2350 } else {
2351 // Retain using the non-block variant: we never need to do a copy
2352 // of a block that's been returned to us.
2353 return CGF.EmitARCRetainNonBlock(value);
2354 }
2355}
2356
John McCalldc05b112011-09-10 01:16:55 +00002357/// Determine whether it might be important to emit a separate
2358/// objc_retain_block on the result of the given expression, or
2359/// whether it's okay to just emit it in a +1 context.
2360static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2361 assert(e->getType()->isBlockPointerType());
2362 e = e->IgnoreParens();
2363
2364 // For future goodness, emit block expressions directly in +1
2365 // contexts if we can.
2366 if (isa<BlockExpr>(e))
2367 return false;
2368
2369 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2370 switch (cast->getCastKind()) {
2371 // Emitting these operations in +1 contexts is goodness.
2372 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002373 case CK_ARCReclaimReturnedObject:
2374 case CK_ARCConsumeObject:
2375 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002376 return false;
2377
2378 // These operations preserve a block type.
2379 case CK_NoOp:
2380 case CK_BitCast:
2381 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2382
2383 // These operations are known to be bad (or haven't been considered).
2384 case CK_AnyPointerToBlockPointerCast:
2385 default:
2386 return true;
2387 }
2388 }
2389
2390 return true;
2391}
2392
John McCall4b9c2d22011-11-06 09:01:30 +00002393/// Try to emit a PseudoObjectExpr at +1.
2394///
2395/// This massively duplicates emitPseudoObjectRValue.
2396static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2397 const PseudoObjectExpr *E) {
2398 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2399
2400 // Find the result expression.
2401 const Expr *resultExpr = E->getResultExpr();
2402 assert(resultExpr);
2403 TryEmitResult result;
2404
2405 for (PseudoObjectExpr::const_semantics_iterator
2406 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2407 const Expr *semantic = *i;
2408
2409 // If this semantic expression is an opaque value, bind it
2410 // to the result of its source expression.
2411 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2412 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2413 OVMA opaqueData;
2414
2415 // If this semantic is the result of the pseudo-object
2416 // expression, try to evaluate the source as +1.
2417 if (ov == resultExpr) {
2418 assert(!OVMA::shouldBindAsLValue(ov));
2419 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2420 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2421
2422 // Otherwise, just bind it.
2423 } else {
2424 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2425 }
2426 opaques.push_back(opaqueData);
2427
2428 // Otherwise, if the expression is the result, evaluate it
2429 // and remember the result.
2430 } else if (semantic == resultExpr) {
2431 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2432
2433 // Otherwise, evaluate the expression in an ignored context.
2434 } else {
2435 CGF.EmitIgnoredExpr(semantic);
2436 }
2437 }
2438
2439 // Unbind all the opaques now.
2440 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2441 opaques[i].unbind(CGF);
2442
2443 return result;
2444}
2445
John McCallf85e1932011-06-15 23:02:42 +00002446static TryEmitResult
2447tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002448 // Look through cleanups.
2449 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002450 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002451 CodeGenFunction::RunCleanupsScope scope(CGF);
2452 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2453 }
2454
John McCallf85e1932011-06-15 23:02:42 +00002455 // The desired result type, if it differs from the type of the
2456 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002457 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002458
2459 while (true) {
2460 e = e->IgnoreParens();
2461
2462 // There's a break at the end of this if-chain; anything
2463 // that wants to keep looping has to explicitly continue.
2464 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2465 switch (ce->getCastKind()) {
2466 // No-op casts don't change the type, so we just ignore them.
2467 case CK_NoOp:
2468 e = ce->getSubExpr();
2469 continue;
2470
2471 case CK_LValueToRValue: {
2472 TryEmitResult loadResult
2473 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2474 if (resultType) {
2475 llvm::Value *value = loadResult.getPointer();
2476 value = CGF.Builder.CreateBitCast(value, resultType);
2477 loadResult.setPointer(value);
2478 }
2479 return loadResult;
2480 }
2481
2482 // These casts can change the type, so remember that and
2483 // soldier on. We only need to remember the outermost such
2484 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002485 case CK_CPointerToObjCPointerCast:
2486 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002487 case CK_AnyPointerToBlockPointerCast:
2488 case CK_BitCast:
2489 if (!resultType)
2490 resultType = CGF.ConvertType(ce->getType());
2491 e = ce->getSubExpr();
2492 assert(e->getType()->hasPointerRepresentation());
2493 continue;
2494
2495 // For consumptions, just emit the subexpression and thus elide
2496 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002497 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002498 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2499 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2500 return TryEmitResult(result, true);
2501 }
2502
John McCalldc05b112011-09-10 01:16:55 +00002503 // Block extends are net +0. Naively, we could just recurse on
2504 // the subexpression, but actually we need to ensure that the
2505 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002506 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002507 llvm::Value *result; // will be a +0 value
2508
2509 // If we can't safely assume the sub-expression will produce a
2510 // block-copied value, emit the sub-expression at +0.
2511 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2512 result = CGF.EmitScalarExpr(ce->getSubExpr());
2513
2514 // Otherwise, try to emit the sub-expression at +1 recursively.
2515 } else {
2516 TryEmitResult subresult
2517 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2518 result = subresult.getPointer();
2519
2520 // If that produced a retained value, just use that,
2521 // possibly casting down.
2522 if (subresult.getInt()) {
2523 if (resultType)
2524 result = CGF.Builder.CreateBitCast(result, resultType);
2525 return TryEmitResult(result, true);
2526 }
2527
2528 // Otherwise it's +0.
2529 }
2530
2531 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002532 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002533 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2534 return TryEmitResult(result, true);
2535 }
2536
John McCall7e5e5f42011-07-07 06:58:02 +00002537 // For reclaims, emit the subexpression as a retained call and
2538 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002539 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002540 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2541 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2542 return TryEmitResult(result, true);
2543 }
2544
John McCallf85e1932011-06-15 23:02:42 +00002545 default:
2546 break;
2547 }
2548
2549 // Skip __extension__.
2550 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2551 if (op->getOpcode() == UO_Extension) {
2552 e = op->getSubExpr();
2553 continue;
2554 }
2555
2556 // For calls and message sends, use the retained-call logic.
2557 // Delegate inits are a special case in that they're the only
2558 // returns-retained expression that *isn't* surrounded by
2559 // a consume.
2560 } else if (isa<CallExpr>(e) ||
2561 (isa<ObjCMessageExpr>(e) &&
2562 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2563 llvm::Value *result = emitARCRetainCall(CGF, e);
2564 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2565 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002566
2567 // Look through pseudo-object expressions.
2568 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2569 TryEmitResult result
2570 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2571 if (resultType) {
2572 llvm::Value *value = result.getPointer();
2573 value = CGF.Builder.CreateBitCast(value, resultType);
2574 result.setPointer(value);
2575 }
2576 return result;
John McCallf85e1932011-06-15 23:02:42 +00002577 }
2578
2579 // Conservatively halt the search at any other expression kind.
2580 break;
2581 }
2582
2583 // We didn't find an obvious production, so emit what we've got and
2584 // tell the caller that we didn't manage to retain.
2585 llvm::Value *result = CGF.EmitScalarExpr(e);
2586 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2587 return TryEmitResult(result, false);
2588}
2589
2590static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2591 LValue lvalue,
2592 QualType type) {
2593 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2594 llvm::Value *value = result.getPointer();
2595 if (!result.getInt())
2596 value = CGF.EmitARCRetain(type, value);
2597 return value;
2598}
2599
2600/// EmitARCRetainScalarExpr - Semantically equivalent to
2601/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2602/// best-effort attempt to peephole expressions that naturally produce
2603/// retained objects.
2604llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2605 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2606 llvm::Value *value = result.getPointer();
2607 if (!result.getInt())
2608 value = EmitARCRetain(e->getType(), value);
2609 return value;
2610}
2611
2612llvm::Value *
2613CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2614 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2615 llvm::Value *value = result.getPointer();
2616 if (result.getInt())
2617 value = EmitARCAutorelease(value);
2618 else
2619 value = EmitARCRetainAutorelease(e->getType(), value);
2620 return value;
2621}
2622
John McCall348f16f2011-10-04 06:23:45 +00002623llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2624 llvm::Value *result;
2625 bool doRetain;
2626
2627 if (shouldEmitSeparateBlockRetain(e)) {
2628 result = EmitScalarExpr(e);
2629 doRetain = true;
2630 } else {
2631 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2632 result = subresult.getPointer();
2633 doRetain = !subresult.getInt();
2634 }
2635
2636 if (doRetain)
2637 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2638 return EmitObjCConsumeObject(e->getType(), result);
2639}
2640
John McCall2b014d62011-10-01 10:32:24 +00002641llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2642 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002643 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002644 // Do so before running any cleanups for the full-expression.
2645 // tryEmitARCRetainScalarExpr does make an effort to do things
2646 // inside cleanups, but there are crazy cases like
2647 // @throw A().foo;
2648 // where a full retain+autorelease is required and would
2649 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002650 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2651 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002652 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002653 }
John McCall2b014d62011-10-01 10:32:24 +00002654
John McCall1a343eb2011-11-10 08:15:53 +00002655 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002656 return EmitARCRetainAutoreleaseScalarExpr(expr);
2657 }
2658
2659 // Otherwise, use the normal scalar-expression emission. The
2660 // exception machinery doesn't do anything special with the
2661 // exception like retaining it, so there's no safety associated with
2662 // only running cleanups after the throw has started, and when it
2663 // matters it tends to be substantially inferior code.
2664 return EmitScalarExpr(expr);
2665}
2666
John McCallf85e1932011-06-15 23:02:42 +00002667std::pair<LValue,llvm::Value*>
2668CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2669 bool ignored) {
2670 // Evaluate the RHS first.
2671 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2672 llvm::Value *value = result.getPointer();
2673
John McCallfb720812011-07-28 07:23:35 +00002674 bool hasImmediateRetain = result.getInt();
2675
2676 // If we didn't emit a retained object, and the l-value is of block
2677 // type, then we need to emit the block-retain immediately in case
2678 // it invalidates the l-value.
2679 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002680 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002681 hasImmediateRetain = true;
2682 }
2683
John McCallf85e1932011-06-15 23:02:42 +00002684 LValue lvalue = EmitLValue(e->getLHS());
2685
2686 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002687 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002688 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002689 EmitLoadOfScalar(lvalue);
2690 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002691 EmitARCRelease(oldValue, /*precise*/ false);
2692 } else {
John McCall545d9962011-06-25 02:11:03 +00002693 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002694 }
2695
2696 return std::pair<LValue,llvm::Value*>(lvalue, value);
2697}
2698
2699std::pair<LValue,llvm::Value*>
2700CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2701 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2702 LValue lvalue = EmitLValue(e->getLHS());
2703
Eli Friedman6da2c712011-12-03 04:14:32 +00002704 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002705
2706 return std::pair<LValue,llvm::Value*>(lvalue, value);
2707}
2708
2709void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002710 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002711 const Stmt *subStmt = ARPS.getSubStmt();
2712 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2713
2714 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002715 if (DI)
2716 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002717
2718 // Keep track of the current cleanup stack depth.
2719 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002720 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002721 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2722 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2723 } else {
2724 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2725 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2726 }
2727
2728 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2729 E = S.body_end(); I != E; ++I)
2730 EmitStmt(*I);
2731
Eric Christopher73fb3502011-10-13 21:45:18 +00002732 if (DI)
2733 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002734}
John McCall0c24c802011-06-24 23:21:27 +00002735
2736/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2737/// make sure it survives garbage collection until this point.
2738void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2739 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002740 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002741 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002742 llvm::Value *extender
2743 = llvm::InlineAsm::get(extenderType,
2744 /* assembly */ "",
2745 /* constraints */ "r",
2746 /* side effects */ true);
2747
2748 object = Builder.CreateBitCast(object, VoidPtrTy);
2749 Builder.CreateCall(extender, object)->setDoesNotThrow();
2750}
2751
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002752/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002753/// non-trivial copy assignment function, produce following helper function.
2754/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2755///
2756llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002757CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2758 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002759 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002760 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002761 return 0;
2762 QualType Ty = PID->getPropertyIvarDecl()->getType();
2763 if (!Ty->isRecordType())
2764 return 0;
2765 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002766 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002767 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002768 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002769 if (hasTrivialSetExpr(PID))
2770 return 0;
2771 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2772 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2773 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002774
2775 ASTContext &C = getContext();
2776 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002777 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002778 FunctionDecl *FD = FunctionDecl::Create(C,
2779 C.getTranslationUnitDecl(),
2780 SourceLocation(),
2781 SourceLocation(), II, C.VoidTy, 0,
2782 SC_Static,
2783 SC_None,
2784 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002785 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002786
2787 QualType DestTy = C.getPointerType(Ty);
2788 QualType SrcTy = Ty;
2789 SrcTy.addConst();
2790 SrcTy = C.getPointerType(SrcTy);
2791
2792 FunctionArgList args;
2793 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2794 args.push_back(&dstDecl);
2795 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2796 args.push_back(&srcDecl);
2797
2798 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002799 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2800 FunctionType::ExtInfo(),
2801 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002802
John McCallde5d3c72012-02-17 03:33:10 +00002803 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002804
2805 llvm::Function *Fn =
2806 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002807 "__assign_helper_atomic_property_",
2808 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002809
2810 if (CGM.getModuleDebugInfo())
2811 DebugInfo = CGM.getModuleDebugInfo();
2812
2813
2814 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2815
John McCallf4b88a42012-03-10 09:33:50 +00002816 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2817 VK_RValue, SourceLocation());
2818 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2819 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002820
John McCallf4b88a42012-03-10 09:33:50 +00002821 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2822 VK_RValue, SourceLocation());
2823 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2824 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002825
John McCallf4b88a42012-03-10 09:33:50 +00002826 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002827 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002828 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2829 Args, 2, DestTy->getPointeeType(),
2830 VK_LValue, SourceLocation());
2831
2832 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002833
2834 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002835 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002836 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002837 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002838}
2839
2840llvm::Constant *
2841CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2842 const ObjCPropertyImplDecl *PID) {
2843 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002844 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002845 return 0;
2846 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2847 QualType Ty = PD->getType();
2848 if (!Ty->isRecordType())
2849 return 0;
2850 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2851 return 0;
2852 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002853
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002854 if (hasTrivialGetExpr(PID))
2855 return 0;
2856 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2857 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2858 return HelperFn;
2859
2860
2861 ASTContext &C = getContext();
2862 IdentifierInfo *II
2863 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2864 FunctionDecl *FD = FunctionDecl::Create(C,
2865 C.getTranslationUnitDecl(),
2866 SourceLocation(),
2867 SourceLocation(), II, C.VoidTy, 0,
2868 SC_Static,
2869 SC_None,
2870 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002871 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002872
2873 QualType DestTy = C.getPointerType(Ty);
2874 QualType SrcTy = Ty;
2875 SrcTy.addConst();
2876 SrcTy = C.getPointerType(SrcTy);
2877
2878 FunctionArgList args;
2879 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2880 args.push_back(&dstDecl);
2881 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2882 args.push_back(&srcDecl);
2883
2884 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002885 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2886 FunctionType::ExtInfo(),
2887 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002888
John McCallde5d3c72012-02-17 03:33:10 +00002889 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002890
2891 llvm::Function *Fn =
2892 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2893 "__copy_helper_atomic_property_", &CGM.getModule());
2894
2895 if (CGM.getModuleDebugInfo())
2896 DebugInfo = CGM.getModuleDebugInfo();
2897
2898
2899 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2900
John McCallf4b88a42012-03-10 09:33:50 +00002901 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002902 VK_RValue, SourceLocation());
2903
John McCallf4b88a42012-03-10 09:33:50 +00002904 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2905 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002906
2907 CXXConstructExpr *CXXConstExpr =
2908 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2909
2910 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002911 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002912 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2913 ++A;
2914
2915 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2916 A != AEnd; ++A)
2917 ConstructorArgs.push_back(*A);
2918
2919 CXXConstructExpr *TheCXXConstructExpr =
2920 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2921 CXXConstExpr->getConstructor(),
2922 CXXConstExpr->isElidable(),
2923 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002924 CXXConstExpr->hadMultipleCandidates(),
2925 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002926 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00002927 CXXConstExpr->getConstructionKind(),
2928 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002929
John McCallf4b88a42012-03-10 09:33:50 +00002930 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2931 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002932
John McCallf4b88a42012-03-10 09:33:50 +00002933 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00002934 CharUnits Alignment
2935 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002936 EmitAggExpr(TheCXXConstructExpr,
2937 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2938 AggValueSlot::IsDestructed,
2939 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00002940 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002941
2942 FinishFunction();
2943 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2944 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2945 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002946}
2947
Eli Friedmancae40c42012-02-28 01:08:45 +00002948llvm::Value *
2949CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2950 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002951 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2952 Selector CopySelector =
2953 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002954 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2955 Selector AutoreleaseSelector =
2956 getContext().Selectors.getNullarySelector(AutoreleaseID);
2957
2958 // Emit calls to retain/autorelease.
2959 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2960 llvm::Value *Val = Block;
2961 RValue Result;
2962 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002963 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002964 Val, CallArgList(), 0, 0);
2965 Val = Result.getScalarVal();
2966 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2967 Ty, AutoreleaseSelector,
2968 Val, CallArgList(), 0, 0);
2969 Val = Result.getScalarVal();
2970 return Val;
2971}
2972
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002973
Ted Kremenek2979ec72008-04-09 15:51:31 +00002974CGObjCRuntime::~CGObjCRuntime() {}