blob: 192a47b3cc4fb07f20b734e38e29e9de08f158a5 [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)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000711 StartObjCMethod(OMD, IMP->getClassInterface(), PID->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.
John McCall57cd1b82012-03-28 23:30:44 +0000890 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType,
891 /*volatile*/ false, 0, /*destIsCompleteObject*/ true);
John McCall1e1f4872011-09-13 03:34:09 +0000892 } else {
John McCallba3dd902011-07-22 05:23:13 +0000893 llvm::Value *value;
894 if (propType->isReferenceType()) {
895 value = LV.getAddress();
896 } else {
897 // We want to load and autoreleaseReturnValue ARC __weak ivars.
898 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000899 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000900
901 // Otherwise we want to do a simple load, suppressing the
902 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000903 } else {
John McCallba3dd902011-07-22 05:23:13 +0000904 value = EmitLoadOfLValue(LV).getScalarVal();
905 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000906 }
John McCallf85e1932011-06-15 23:02:42 +0000907
John McCallba3dd902011-07-22 05:23:13 +0000908 value = Builder.CreateBitCast(value, ConvertType(propType));
909 }
910
911 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000912 }
John McCall1e1f4872011-09-13 03:34:09 +0000913 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000914 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000915
John McCall1e1f4872011-09-13 03:34:09 +0000916 }
917 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000918}
919
John McCall41bdde92011-09-12 23:06:44 +0000920/// emitStructSetterCall - Call the runtime function to store the value
921/// from the first formal parameter into the given ivar.
922static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
923 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000924 // objc_copyStruct (&structIvar, &Arg,
925 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000926 CallArgList args;
927
928 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000929 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
930 CGF.LoadObjCSelf(), ivar, 0)
931 .getAddress();
932 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
933 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000934
935 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000936 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000937 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000938 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000939 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
940 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
941 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000942
943 // The third argument is the sizeof the type.
944 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000945 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
946 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000947
John McCall41bdde92011-09-12 23:06:44 +0000948 // The fourth argument is the 'isAtomic' flag.
949 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000950
John McCall41bdde92011-09-12 23:06:44 +0000951 // The fifth argument is the 'hasStrong' flag.
952 // FIXME: should this really always be false?
953 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
954
955 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000956 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
957 FunctionType::ExtInfo(),
958 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000959 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000960}
961
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000962/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
963/// the value from the first formal parameter into the given ivar, using
964/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
965static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
966 ObjCMethodDecl *OMD,
967 ObjCIvarDecl *ivar,
968 llvm::Constant *AtomicHelperFn) {
969 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
970 // AtomicHelperFn);
971 CallArgList args;
972
973 // The first argument is the address of the ivar.
974 llvm::Value *ivarAddr =
975 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
976 CGF.LoadObjCSelf(), ivar, 0).getAddress();
977 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
978 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
979
980 // The second argument is the address of the parameter variable.
981 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000982 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000983 VK_LValue, SourceLocation());
984 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
985 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
986 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
987
988 // Third argument is the helper function.
989 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
990
991 llvm::Value *copyCppAtomicObjectFn =
992 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000993 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
994 FunctionType::ExtInfo(),
995 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000996 copyCppAtomicObjectFn, ReturnValueSlot(), args);
997
998
999}
1000
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001001
John McCall1e1f4872011-09-13 03:34:09 +00001002static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1003 Expr *setter = PID->getSetterCXXAssignment();
1004 if (!setter) return true;
1005
1006 // Sema only makes only of these when the ivar has a C++ class type,
1007 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001008
1009 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001010 // This also implies that there's nothing non-trivial going on with
1011 // the arguments, because operator= can only be trivial if it's a
1012 // synthesized assignment operator and therefore both parameters are
1013 // references.
1014 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001015 if (const FunctionDecl *callee
1016 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1017 if (callee->isTrivial())
1018 return true;
1019 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001020 }
John McCall71c758d2011-09-10 09:17:20 +00001021
John McCall1e1f4872011-09-13 03:34:09 +00001022 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001023 return false;
1024}
1025
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001026static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001027 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001028 return false;
1029 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001030
1031 if (Target.getPlatformName() != "macosx")
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001032 return false;
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001033
1034 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001035}
1036
John McCall71c758d2011-09-10 09:17:20 +00001037void
1038CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001039 const ObjCPropertyImplDecl *propImpl,
1040 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001041 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001042 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001043 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001044
1045 // Just use the setter expression if Sema gave us one and it's
1046 // non-trivial.
1047 if (!hasTrivialSetExpr(propImpl)) {
1048 if (!AtomicHelperFn)
1049 // If non-atomic, assignment is called directly.
1050 EmitStmt(propImpl->getSetterCXXAssignment());
1051 else
1052 // If atomic, assignment is called via a locking api.
1053 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1054 AtomicHelperFn);
1055 return;
1056 }
John McCall71c758d2011-09-10 09:17:20 +00001057
John McCall1e1f4872011-09-13 03:34:09 +00001058 PropertyImplStrategy strategy(CGM, propImpl);
1059 switch (strategy.getKind()) {
1060 case PropertyImplStrategy::Native: {
1061 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001062
John McCall1e1f4872011-09-13 03:34:09 +00001063 LValue ivarLValue =
1064 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1065 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001066
John McCall1e1f4872011-09-13 03:34:09 +00001067 // Currently, all atomic accesses have to be through integer
1068 // types, so there's no point in trying to pick a prettier type.
1069 llvm::Type *bitcastType =
1070 llvm::Type::getIntNTy(getLLVMContext(),
1071 getContext().toBits(strategy.getIvarSize()));
1072 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1073
1074 // Cast both arguments to the chosen operation type.
1075 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1076 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1077
1078 // This bitcast load is likely to cause some nasty IR.
1079 llvm::Value *load = Builder.CreateLoad(argAddr);
1080
1081 // Perform an atomic store. There are no memory ordering requirements.
1082 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1083 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1084 store->setAtomic(llvm::Unordered);
1085 return;
1086 }
1087
1088 case PropertyImplStrategy::GetSetProperty:
1089 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001090
1091 llvm::Value *setOptimizedPropertyFn = 0;
1092 llvm::Value *setPropertyFn = 0;
1093 if (UseOptimizedSetter(CGM)) {
1094 // 10.8 code and GC is off
1095 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001096 CGM.getObjCRuntime()
1097 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1098 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001099 if (!setOptimizedPropertyFn) {
1100 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1101 return;
1102 }
John McCall71c758d2011-09-10 09:17:20 +00001103 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001104 else {
1105 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1106 if (!setPropertyFn) {
1107 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1108 return;
1109 }
1110 }
1111
John McCall71c758d2011-09-10 09:17:20 +00001112 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1113 // <is-atomic>, <is-copy>).
1114 llvm::Value *cmd =
1115 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1116 llvm::Value *self =
1117 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1118 llvm::Value *ivarOffset =
1119 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1120 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1121 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1122
1123 CallArgList args;
1124 args.add(RValue::get(self), getContext().getObjCIdType());
1125 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001126 if (setOptimizedPropertyFn) {
1127 args.add(RValue::get(arg), getContext().getObjCIdType());
1128 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1129 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1130 FunctionType::ExtInfo(),
1131 RequiredArgs::All),
1132 setOptimizedPropertyFn, ReturnValueSlot(), args);
1133 } else {
1134 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1135 args.add(RValue::get(arg), getContext().getObjCIdType());
1136 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1137 getContext().BoolTy);
1138 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1139 getContext().BoolTy);
1140 // FIXME: We shouldn't need to get the function info here, the runtime
1141 // already should have computed it to build the function.
1142 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1143 FunctionType::ExtInfo(),
1144 RequiredArgs::All),
1145 setPropertyFn, ReturnValueSlot(), args);
1146 }
1147
John McCall71c758d2011-09-10 09:17:20 +00001148 return;
1149 }
1150
John McCall1e1f4872011-09-13 03:34:09 +00001151 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001152 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001153 return;
John McCall1e1f4872011-09-13 03:34:09 +00001154
1155 case PropertyImplStrategy::Expression:
1156 break;
John McCall71c758d2011-09-10 09:17:20 +00001157 }
1158
1159 // Otherwise, fake up some ASTs and emit a normal assignment.
1160 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001161 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1162 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001163 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1164 selfDecl->getType(), CK_LValueToRValue, &self,
1165 VK_RValue);
1166 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1167 SourceLocation(), &selfLoad, true, true);
1168
1169 ParmVarDecl *argDecl = *setterMethod->param_begin();
1170 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001171 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001172 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1173 argType.getUnqualifiedType(), CK_LValueToRValue,
1174 &arg, VK_RValue);
1175
1176 // The property type can differ from the ivar type in some situations with
1177 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1178 // The following absurdity is just to ensure well-formed IR.
1179 CastKind argCK = CK_NoOp;
1180 if (ivarRef.getType()->isObjCObjectPointerType()) {
1181 if (argLoad.getType()->isObjCObjectPointerType())
1182 argCK = CK_BitCast;
1183 else if (argLoad.getType()->isBlockPointerType())
1184 argCK = CK_BlockPointerToObjCPointerCast;
1185 else
1186 argCK = CK_CPointerToObjCPointerCast;
1187 } else if (ivarRef.getType()->isBlockPointerType()) {
1188 if (argLoad.getType()->isBlockPointerType())
1189 argCK = CK_BitCast;
1190 else
1191 argCK = CK_AnyPointerToBlockPointerCast;
1192 } else if (ivarRef.getType()->isPointerType()) {
1193 argCK = CK_BitCast;
1194 }
1195 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1196 ivarRef.getType(), argCK, &argLoad,
1197 VK_RValue);
1198 Expr *finalArg = &argLoad;
1199 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1200 argLoad.getType()))
1201 finalArg = &argCast;
1202
1203
1204 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1205 ivarRef.getType(), VK_RValue, OK_Ordinary,
1206 SourceLocation());
1207 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001208}
1209
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001210/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +00001211/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1212/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001213void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1214 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001215 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001216 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001217 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1218 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1219 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +00001220 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001221
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001222 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001223
1224 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001225}
1226
John McCalle81ac692011-03-22 07:05:39 +00001227namespace {
John McCall9928c482011-07-12 16:41:08 +00001228 struct DestroyIvar : EHScopeStack::Cleanup {
1229 private:
1230 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001231 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001232 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001233 bool useEHCleanupForArray;
1234 public:
1235 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1236 CodeGenFunction::Destroyer *destroyer,
1237 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001238 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001239 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001240
John McCallad346f42011-07-12 20:27:29 +00001241 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001242 LValue lvalue
1243 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1244 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001245 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001246 }
1247 };
1248}
1249
John McCall9928c482011-07-12 16:41:08 +00001250/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1251static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1252 llvm::Value *addr,
1253 QualType type) {
1254 llvm::Value *null = getNullForVariable(addr);
1255 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1256}
John McCallf85e1932011-06-15 23:02:42 +00001257
John McCalle81ac692011-03-22 07:05:39 +00001258static void emitCXXDestructMethod(CodeGenFunction &CGF,
1259 ObjCImplementationDecl *impl) {
1260 CodeGenFunction::RunCleanupsScope scope(CGF);
1261
1262 llvm::Value *self = CGF.LoadObjCSelf();
1263
Jordy Rosedb8264e2011-07-22 02:08:32 +00001264 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1265 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001266 ivar; ivar = ivar->getNextIvar()) {
1267 QualType type = ivar->getType();
1268
John McCalle81ac692011-03-22 07:05:39 +00001269 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001270 QualType::DestructionKind dtorKind = type.isDestructedType();
1271 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001272
John McCall9928c482011-07-12 16:41:08 +00001273 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001274
John McCall9928c482011-07-12 16:41:08 +00001275 // Use a call to objc_storeStrong to destroy strong ivars, for the
1276 // general benefit of the tools.
1277 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001278 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001279
John McCall9928c482011-07-12 16:41:08 +00001280 // Otherwise use the default for the destruction kind.
1281 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001282 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001283 }
John McCall9928c482011-07-12 16:41:08 +00001284
1285 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1286
1287 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1288 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001289 }
1290
1291 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1292}
1293
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001294void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1295 ObjCMethodDecl *MD,
1296 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001297 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001298 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001299
1300 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001301 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001302 // Suppress the final autorelease in ARC.
1303 AutoreleaseResult = false;
1304
Chris Lattner5f9e2722011-07-23 10:55:15 +00001305 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001306 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1307 E = IMP->init_end(); B != E; ++B) {
1308 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001309 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001310 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001311 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1312 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001313 EmitAggExpr(IvarInit->getInit(),
1314 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001315 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +00001316 AggValueSlot::IsNotAliased,
1317 AggValueSlot::IsCompleteObject));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001318 }
1319 // constructor returns 'self'.
1320 CodeGenTypes &Types = CGM.getTypes();
1321 QualType IdTy(CGM.getContext().getObjCIdType());
1322 llvm::Value *SelfAsId =
1323 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1324 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001325
1326 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001327 } else {
John McCalle81ac692011-03-22 07:05:39 +00001328 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001329 }
1330 FinishFunction();
1331}
1332
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001333bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1334 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1335 it++; it++;
1336 const ABIArgInfo &AI = it->info;
1337 // FIXME. Is this sufficient check?
1338 return (AI.getKind() == ABIArgInfo::Indirect);
1339}
1340
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001341bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001342 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001343 return false;
1344 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1345 return FDTTy->getDecl()->hasObjectMember();
1346 return false;
1347}
1348
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001349llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001350 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1351 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001352}
1353
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001354QualType CodeGenFunction::TypeOfSelfObject() {
1355 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1356 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001357 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1358 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001359 return PTy->getPointeeType();
1360}
1361
Chris Lattner74391b42009-03-22 21:03:39 +00001362void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001363 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001364 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001366 if (!EnumerationMutationFn) {
1367 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1368 return;
1369 }
1370
Devang Patelbcbd03a2011-01-19 01:36:36 +00001371 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001372 if (DI)
1373 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001374
Devang Patel9d99f2d2011-06-13 23:15:32 +00001375 // The local variable comes into scope immediately.
1376 AutoVarEmission variable = AutoVarEmission::invalid();
1377 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1378 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1379
John McCalld88687f2011-01-07 01:49:06 +00001380 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Anders Carlssonf484c312008-08-31 02:33:12 +00001382 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001383 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001384 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001385 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001386
Anders Carlssonf484c312008-08-31 02:33:12 +00001387 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001388 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001389
John McCalld88687f2011-01-07 01:49:06 +00001390 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001391 IdentifierInfo *II[] = {
1392 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1393 &CGM.getContext().Idents.get("objects"),
1394 &CGM.getContext().Idents.get("count")
1395 };
1396 Selector FastEnumSel =
1397 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001398
1399 QualType ItemsTy =
1400 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001401 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001402 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001403 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001404
John McCall990567c2011-07-27 01:07:15 +00001405 // Emit the collection pointer. In ARC, we do a retain.
1406 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001407 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001408 Collection = EmitARCRetainScalarExpr(S.getCollection());
1409
1410 // Enter a cleanup to do the release.
1411 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1412 } else {
1413 Collection = EmitScalarExpr(S.getCollection());
1414 }
Mike Stump1eb44332009-09-09 15:08:12 +00001415
John McCall4b302d32011-08-05 00:14:38 +00001416 // The 'continue' label needs to appear within the cleanup for the
1417 // collection object.
1418 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1419
John McCalld88687f2011-01-07 01:49:06 +00001420 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001421 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001422
1423 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001424 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001425
John McCalld88687f2011-01-07 01:49:06 +00001426 // The second argument is a temporary array with space for NumItems
1427 // pointers. We'll actually be loading elements from the array
1428 // pointer written into the control state; this buffer is so that
1429 // collections that *aren't* backed by arrays can still queue up
1430 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001431 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001432
John McCalld88687f2011-01-07 01:49:06 +00001433 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001434 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001435 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001436 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001437
John McCalld88687f2011-01-07 01:49:06 +00001438 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001439 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001440 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001441 getContext().UnsignedLongTy,
1442 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001443 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001444
John McCalld88687f2011-01-07 01:49:06 +00001445 // The initial number of objects that were returned in the buffer.
1446 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCalld88687f2011-01-07 01:49:06 +00001448 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1449 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001450
John McCalld88687f2011-01-07 01:49:06 +00001451 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001452
John McCalld88687f2011-01-07 01:49:06 +00001453 // If the limit pointer was zero to begin with, the collection is
1454 // empty; skip all this.
1455 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1456 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001457
John McCalld88687f2011-01-07 01:49:06 +00001458 // Otherwise, initialize the loop.
1459 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001460
John McCalld88687f2011-01-07 01:49:06 +00001461 // Save the initial mutations value. This is the value at an
1462 // address that was written into the state object by
1463 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001464 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001465 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001466 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001467 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001468
John McCalld88687f2011-01-07 01:49:06 +00001469 llvm::Value *initialMutations =
1470 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001471
John McCalld88687f2011-01-07 01:49:06 +00001472 // Start looping. This is the point we return to whenever we have a
1473 // fresh, non-empty batch of objects.
1474 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1475 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001476
John McCalld88687f2011-01-07 01:49:06 +00001477 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001478 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001479 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001480
John McCalld88687f2011-01-07 01:49:06 +00001481 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001482 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001483 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001484
John McCalld88687f2011-01-07 01:49:06 +00001485 // Check whether the mutations value has changed from where it was
1486 // at start. StateMutationsPtr should actually be invariant between
1487 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001488 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001489 llvm::Value *currentMutations
1490 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001491
John McCalld88687f2011-01-07 01:49:06 +00001492 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001493 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001494
John McCalld88687f2011-01-07 01:49:06 +00001495 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1496 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
John McCalld88687f2011-01-07 01:49:06 +00001498 // If so, call the enumeration-mutation function.
1499 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001500 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001501 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001502 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001503 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001504 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001505 // FIXME: We shouldn't need to get the function info here, the runtime already
1506 // should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +00001507 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1508 FunctionType::ExtInfo(),
1509 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001510 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001511
John McCalld88687f2011-01-07 01:49:06 +00001512 // Otherwise, or if the mutation function returns, just continue.
1513 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
John McCalld88687f2011-01-07 01:49:06 +00001515 // Initialize the element variable.
1516 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001517 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001518 LValue elementLValue;
1519 QualType elementType;
1520 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001521 // Initialize the variable, in case it's a __block variable or something.
1522 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001523
John McCall57b3b6a2011-02-22 07:16:58 +00001524 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001525 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001526 VK_LValue, SourceLocation());
1527 elementLValue = EmitLValue(&tempDRE);
1528 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001529 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001530
1531 if (D->isARCPseudoStrong())
1532 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001533 } else {
1534 elementLValue = LValue(); // suppress warning
1535 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001536 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001537 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001538 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001539
1540 // Fetch the buffer out of the enumeration state.
1541 // TODO: this pointer should actually be invariant between
1542 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001543 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001544 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001545 llvm::Value *EnumStateItems =
1546 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001547
John McCalld88687f2011-01-07 01:49:06 +00001548 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001549 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001550 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1551 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001552
John McCalld88687f2011-01-07 01:49:06 +00001553 // Cast that value to the right type.
1554 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1555 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001556
John McCalld88687f2011-01-07 01:49:06 +00001557 // Make sure we have an l-value. Yes, this gets evaluated every
1558 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001559 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001560 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001561 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001562 } else {
1563 EmitScalarInit(CurrentItem, elementLValue);
1564 }
Mike Stump1eb44332009-09-09 15:08:12 +00001565
John McCall57b3b6a2011-02-22 07:16:58 +00001566 // If we do have an element variable, this assignment is the end of
1567 // its initialization.
1568 if (elementIsVariable)
1569 EmitAutoVarCleanups(variable);
1570
John McCalld88687f2011-01-07 01:49:06 +00001571 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001572 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001573 {
1574 RunCleanupsScope Scope(*this);
1575 EmitStmt(S.getBody());
1576 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001577 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001578
John McCalld88687f2011-01-07 01:49:06 +00001579 // Destroy the element variable now.
1580 elementVariableScope.ForceCleanup();
1581
1582 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001583 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001584
John McCalld88687f2011-01-07 01:49:06 +00001585 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001586
John McCalld88687f2011-01-07 01:49:06 +00001587 // First we check in the local buffer.
1588 llvm::Value *indexPlusOne
1589 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001590
John McCalld88687f2011-01-07 01:49:06 +00001591 // If we haven't overrun the buffer yet, we can continue.
1592 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1593 LoopBodyBB, FetchMoreBB);
1594
1595 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1596 count->addIncoming(count, AfterBody.getBlock());
1597
1598 // Otherwise, we have to fetch more elements.
1599 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001600
1601 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001602 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001603 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001604 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001605 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
John McCalld88687f2011-01-07 01:49:06 +00001607 // If we got a zero count, we're done.
1608 llvm::Value *refetchCount = CountRV.getScalarVal();
1609
1610 // (note that the message send might split FetchMoreBB)
1611 index->addIncoming(zero, Builder.GetInsertBlock());
1612 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1613
1614 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1615 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Anders Carlssonf484c312008-08-31 02:33:12 +00001617 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001618 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001619
John McCall57b3b6a2011-02-22 07:16:58 +00001620 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001621 // If the element was not a declaration, set it to be null.
1622
John McCalld88687f2011-01-07 01:49:06 +00001623 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1624 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001625 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001626 }
1627
Eric Christopher73fb3502011-10-13 21:45:18 +00001628 if (DI)
1629 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001630
John McCall990567c2011-07-27 01:07:15 +00001631 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001632 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001633 PopCleanupBlock();
1634
John McCallff8e1152010-07-23 21:56:41 +00001635 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001636}
1637
Mike Stump1eb44332009-09-09 15:08:12 +00001638void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001639 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001640}
1641
Mike Stump1eb44332009-09-09 15:08:12 +00001642void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001643 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1644}
1645
Chris Lattner10cac6f2008-11-15 21:26:17 +00001646void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001647 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001648 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001649}
1650
John McCall33e56f32011-09-10 06:18:15 +00001651/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001652/// primitive retain.
1653llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1654 llvm::Value *value) {
1655 return EmitARCRetain(type, value);
1656}
1657
1658namespace {
1659 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001660 CallObjCRelease(llvm::Value *object) : object(object) {}
1661 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001662
John McCallad346f42011-07-12 20:27:29 +00001663 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001664 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001665 }
1666 };
1667}
1668
John McCall33e56f32011-09-10 06:18:15 +00001669/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001670/// release at the end of the full-expression.
1671llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1672 llvm::Value *object) {
1673 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001674 // conditional.
1675 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001676 return object;
1677}
1678
1679llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1680 llvm::Value *value) {
1681 return EmitARCRetainAutorelease(type, value);
1682}
1683
1684
1685static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001686 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001687 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001688 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1689
1690 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1691 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001692 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001693 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1694 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1695
1696 return fn;
1697}
1698
1699/// Perform an operation having the signature
1700/// i8* (i8*)
1701/// where a null input causes a no-op and returns null.
1702static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1703 llvm::Value *value,
1704 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001705 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001706 if (isa<llvm::ConstantPointerNull>(value)) return value;
1707
1708 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001709 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001710 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001711 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1712 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1713 }
1714
1715 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001716 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001717 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1718
1719 // Call the function.
1720 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1721 call->setDoesNotThrow();
1722
1723 // Cast the result back to the original type.
1724 return CGF.Builder.CreateBitCast(call, origType);
1725}
1726
1727/// Perform an operation having the following signature:
1728/// i8* (i8**)
1729static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1730 llvm::Value *addr,
1731 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001732 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001733 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001734 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001735 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001736 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1737 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1738 }
1739
1740 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001741 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001742 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1743
1744 // Call the function.
1745 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1746 call->setDoesNotThrow();
1747
1748 // Cast the result back to a dereference of the original type.
1749 llvm::Value *result = call;
1750 if (origType != CGF.Int8PtrPtrTy)
1751 result = CGF.Builder.CreateBitCast(result,
1752 cast<llvm::PointerType>(origType)->getElementType());
1753
1754 return result;
1755}
1756
1757/// Perform an operation having the following signature:
1758/// i8* (i8**, i8*)
1759static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1760 llvm::Value *addr,
1761 llvm::Value *value,
1762 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001763 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001764 bool ignored) {
1765 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1766 == value->getType());
1767
1768 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001769 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001770
Chris Lattner2acc6e32011-07-18 04:24:23 +00001771 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001772 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1773 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1774 }
1775
Chris Lattner2acc6e32011-07-18 04:24:23 +00001776 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001777
1778 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1779 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1780
1781 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1782 result->setDoesNotThrow();
1783
1784 if (ignored) return 0;
1785
1786 return CGF.Builder.CreateBitCast(result, origType);
1787}
1788
1789/// Perform an operation having the following signature:
1790/// void (i8**, i8**)
1791static void emitARCCopyOperation(CodeGenFunction &CGF,
1792 llvm::Value *dst,
1793 llvm::Value *src,
1794 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001795 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001796 assert(dst->getType() == src->getType());
1797
1798 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001799 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001800 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001801 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1802 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1803 }
1804
1805 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1806 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1807
1808 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1809 result->setDoesNotThrow();
1810}
1811
1812/// Produce the code to do a retain. Based on the type, calls one of:
1813/// call i8* @objc_retain(i8* %value)
1814/// call i8* @objc_retainBlock(i8* %value)
1815llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1816 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001817 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001818 else
1819 return EmitARCRetainNonBlock(value);
1820}
1821
1822/// Retain the given object, with normal retain semantics.
1823/// call i8* @objc_retain(i8* %value)
1824llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1825 return emitARCValueOperation(*this, value,
1826 CGM.getARCEntrypoints().objc_retain,
1827 "objc_retain");
1828}
1829
1830/// Retain the given block, with _Block_copy semantics.
1831/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001832///
1833/// \param mandatory - If false, emit the call with metadata
1834/// indicating that it's okay for the optimizer to eliminate this call
1835/// if it can prove that the block never escapes except down the stack.
1836llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1837 bool mandatory) {
1838 llvm::Value *result
1839 = emitARCValueOperation(*this, value,
1840 CGM.getARCEntrypoints().objc_retainBlock,
1841 "objc_retainBlock");
1842
1843 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1844 // tell the optimizer that it doesn't need to do this copy if the
1845 // block doesn't escape, where being passed as an argument doesn't
1846 // count as escaping.
1847 if (!mandatory && isa<llvm::Instruction>(result)) {
1848 llvm::CallInst *call
1849 = cast<llvm::CallInst>(result->stripPointerCasts());
1850 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1851
1852 SmallVector<llvm::Value*,1> args;
1853 call->setMetadata("clang.arc.copy_on_escape",
1854 llvm::MDNode::get(Builder.getContext(), args));
1855 }
1856
1857 return result;
John McCallf85e1932011-06-15 23:02:42 +00001858}
1859
1860/// Retain the given object which is the result of a function call.
1861/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1862///
1863/// Yes, this function name is one character away from a different
1864/// call with completely different semantics.
1865llvm::Value *
1866CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1867 // Fetch the void(void) inline asm which marks that we're going to
1868 // retain the autoreleased return value.
1869 llvm::InlineAsm *&marker
1870 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1871 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001872 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001873 = CGM.getTargetCodeGenInfo()
1874 .getARCRetainAutoreleasedReturnValueMarker();
1875
1876 // If we have an empty assembly string, there's nothing to do.
1877 if (assembly.empty()) {
1878
1879 // Otherwise, at -O0, build an inline asm that we're going to call
1880 // in a moment.
1881 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1882 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001883 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001884
1885 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1886
1887 // If we're at -O1 and above, we don't want to litter the code
1888 // with this marker yet, so leave a breadcrumb for the ARC
1889 // optimizer to pick up.
1890 } else {
1891 llvm::NamedMDNode *metadata =
1892 CGM.getModule().getOrInsertNamedMetadata(
1893 "clang.arc.retainAutoreleasedReturnValueMarker");
1894 assert(metadata->getNumOperands() <= 1);
1895 if (metadata->getNumOperands() == 0) {
1896 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001897 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001898 }
1899 }
1900 }
1901
1902 // Call the marker asm if we made one, which we do only at -O0.
1903 if (marker) Builder.CreateCall(marker);
1904
1905 return emitARCValueOperation(*this, value,
1906 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1907 "objc_retainAutoreleasedReturnValue");
1908}
1909
1910/// Release the given object.
1911/// call void @objc_release(i8* %value)
1912void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1913 if (isa<llvm::ConstantPointerNull>(value)) return;
1914
1915 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1916 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001917 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001918 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001919 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1920 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1921 }
1922
1923 // Cast the argument to 'id'.
1924 value = Builder.CreateBitCast(value, Int8PtrTy);
1925
1926 // Call objc_release.
1927 llvm::CallInst *call = Builder.CreateCall(fn, value);
1928 call->setDoesNotThrow();
1929
1930 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001931 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001932 call->setMetadata("clang.imprecise_release",
1933 llvm::MDNode::get(Builder.getContext(), args));
1934 }
1935}
1936
1937/// Store into a strong object. Always calls this:
1938/// call void @objc_storeStrong(i8** %addr, i8* %value)
1939llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1940 llvm::Value *value,
1941 bool ignored) {
1942 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1943 == value->getType());
1944
1945 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1946 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001947 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001948 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001949 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1950 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1951 }
1952
1953 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1954 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1955
1956 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1957
1958 if (ignored) return 0;
1959 return value;
1960}
1961
1962/// Store into a strong object. Sometimes calls this:
1963/// call void @objc_storeStrong(i8** %addr, i8* %value)
1964/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001965llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001966 llvm::Value *newValue,
1967 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001968 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001969 bool isBlock = type->isBlockPointerType();
1970
1971 // Use a store barrier at -O0 unless this is a block type or the
1972 // lvalue is inadequately aligned.
1973 if (shouldUseFusedARCCalls() &&
1974 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001975 (dst.getAlignment().isZero() ||
1976 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001977 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1978 }
1979
1980 // Otherwise, split it out.
1981
1982 // Retain the new value.
1983 newValue = EmitARCRetain(type, newValue);
1984
1985 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001986 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001987
1988 // Store. We do this before the release so that any deallocs won't
1989 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001990 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001991
1992 // Finally, release the old value.
1993 EmitARCRelease(oldValue, /*precise*/ false);
1994
1995 return newValue;
1996}
1997
1998/// Autorelease the given object.
1999/// call i8* @objc_autorelease(i8* %value)
2000llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2001 return emitARCValueOperation(*this, value,
2002 CGM.getARCEntrypoints().objc_autorelease,
2003 "objc_autorelease");
2004}
2005
2006/// Autorelease the given object.
2007/// call i8* @objc_autoreleaseReturnValue(i8* %value)
2008llvm::Value *
2009CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2010 return emitARCValueOperation(*this, value,
2011 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2012 "objc_autoreleaseReturnValue");
2013}
2014
2015/// Do a fused retain/autorelease of the given object.
2016/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
2017llvm::Value *
2018CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2019 return emitARCValueOperation(*this, value,
2020 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2021 "objc_retainAutoreleaseReturnValue");
2022}
2023
2024/// Do a fused retain/autorelease of the given object.
2025/// call i8* @objc_retainAutorelease(i8* %value)
2026/// or
2027/// %retain = call i8* @objc_retainBlock(i8* %value)
2028/// call i8* @objc_autorelease(i8* %retain)
2029llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2030 llvm::Value *value) {
2031 if (!type->isBlockPointerType())
2032 return EmitARCRetainAutoreleaseNonBlock(value);
2033
2034 if (isa<llvm::ConstantPointerNull>(value)) return value;
2035
Chris Lattner2acc6e32011-07-18 04:24:23 +00002036 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002037 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002038 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002039 value = EmitARCAutorelease(value);
2040 return Builder.CreateBitCast(value, origType);
2041}
2042
2043/// Do a fused retain/autorelease of the given object.
2044/// call i8* @objc_retainAutorelease(i8* %value)
2045llvm::Value *
2046CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2047 return emitARCValueOperation(*this, value,
2048 CGM.getARCEntrypoints().objc_retainAutorelease,
2049 "objc_retainAutorelease");
2050}
2051
2052/// i8* @objc_loadWeak(i8** %addr)
2053/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2054llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2055 return emitARCLoadOperation(*this, addr,
2056 CGM.getARCEntrypoints().objc_loadWeak,
2057 "objc_loadWeak");
2058}
2059
2060/// i8* @objc_loadWeakRetained(i8** %addr)
2061llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2062 return emitARCLoadOperation(*this, addr,
2063 CGM.getARCEntrypoints().objc_loadWeakRetained,
2064 "objc_loadWeakRetained");
2065}
2066
2067/// i8* @objc_storeWeak(i8** %addr, i8* %value)
2068/// Returns %value.
2069llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2070 llvm::Value *value,
2071 bool ignored) {
2072 return emitARCStoreOperation(*this, addr, value,
2073 CGM.getARCEntrypoints().objc_storeWeak,
2074 "objc_storeWeak", ignored);
2075}
2076
2077/// i8* @objc_initWeak(i8** %addr, i8* %value)
2078/// Returns %value. %addr is known to not have a current weak entry.
2079/// Essentially equivalent to:
2080/// *addr = nil; objc_storeWeak(addr, value);
2081void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2082 // If we're initializing to null, just write null to memory; no need
2083 // to get the runtime involved. But don't do this if optimization
2084 // is enabled, because accounting for this would make the optimizer
2085 // much more complicated.
2086 if (isa<llvm::ConstantPointerNull>(value) &&
2087 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2088 Builder.CreateStore(value, addr);
2089 return;
2090 }
2091
2092 emitARCStoreOperation(*this, addr, value,
2093 CGM.getARCEntrypoints().objc_initWeak,
2094 "objc_initWeak", /*ignored*/ true);
2095}
2096
2097/// void @objc_destroyWeak(i8** %addr)
2098/// Essentially objc_storeWeak(addr, nil).
2099void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2100 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2101 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002102 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002103 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002104 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2105 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2106 }
2107
2108 // Cast the argument to 'id*'.
2109 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2110
2111 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2112 call->setDoesNotThrow();
2113}
2114
2115/// void @objc_moveWeak(i8** %dest, i8** %src)
2116/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2117/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2118void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2119 emitARCCopyOperation(*this, dst, src,
2120 CGM.getARCEntrypoints().objc_moveWeak,
2121 "objc_moveWeak");
2122}
2123
2124/// void @objc_copyWeak(i8** %dest, i8** %src)
2125/// Disregards the current value in %dest. Essentially
2126/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2127void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2128 emitARCCopyOperation(*this, dst, src,
2129 CGM.getARCEntrypoints().objc_copyWeak,
2130 "objc_copyWeak");
2131}
2132
2133/// Produce the code to do a objc_autoreleasepool_push.
2134/// call i8* @objc_autoreleasePoolPush(void)
2135llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2136 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2137 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002138 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002139 llvm::FunctionType::get(Int8PtrTy, false);
2140 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2141 }
2142
2143 llvm::CallInst *call = Builder.CreateCall(fn);
2144 call->setDoesNotThrow();
2145
2146 return call;
2147}
2148
2149/// Produce the code to do a primitive release.
2150/// call void @objc_autoreleasePoolPop(i8* %ptr)
2151void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2152 assert(value->getType() == Int8PtrTy);
2153
2154 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2155 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002156 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002157 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002158 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2159
2160 // We don't want to use a weak import here; instead we should not
2161 // fall into this path.
2162 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2163 }
2164
2165 llvm::CallInst *call = Builder.CreateCall(fn, value);
2166 call->setDoesNotThrow();
2167}
2168
2169/// Produce the code to do an MRR version objc_autoreleasepool_push.
2170/// Which is: [[NSAutoreleasePool alloc] init];
2171/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2172/// init is declared as: - (id) init; in its NSObject super class.
2173///
2174llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2175 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2176 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2177 // [NSAutoreleasePool alloc]
2178 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2179 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2180 CallArgList Args;
2181 RValue AllocRV =
2182 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2183 getContext().getObjCIdType(),
2184 AllocSel, Receiver, Args);
2185
2186 // [Receiver init]
2187 Receiver = AllocRV.getScalarVal();
2188 II = &CGM.getContext().Idents.get("init");
2189 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2190 RValue InitRV =
2191 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2192 getContext().getObjCIdType(),
2193 InitSel, Receiver, Args);
2194 return InitRV.getScalarVal();
2195}
2196
2197/// Produce the code to do a primitive release.
2198/// [tmp drain];
2199void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2200 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2201 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2202 CallArgList Args;
2203 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2204 getContext().VoidTy, DrainSel, Arg, Args);
2205}
2206
John McCallbdc4d802011-07-09 01:37:26 +00002207void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2208 llvm::Value *addr,
2209 QualType type) {
2210 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2211 CGF.EmitARCRelease(ptr, /*precise*/ true);
2212}
2213
2214void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2215 llvm::Value *addr,
2216 QualType type) {
2217 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2218 CGF.EmitARCRelease(ptr, /*precise*/ false);
2219}
2220
2221void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2222 llvm::Value *addr,
2223 QualType type) {
2224 CGF.EmitARCDestroyWeak(addr);
2225}
2226
John McCallf85e1932011-06-15 23:02:42 +00002227namespace {
John McCallf85e1932011-06-15 23:02:42 +00002228 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2229 llvm::Value *Token;
2230
2231 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2232
John McCallad346f42011-07-12 20:27:29 +00002233 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002234 CGF.EmitObjCAutoreleasePoolPop(Token);
2235 }
2236 };
2237 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2238 llvm::Value *Token;
2239
2240 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2241
John McCallad346f42011-07-12 20:27:29 +00002242 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002243 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2244 }
2245 };
2246}
2247
2248void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002249 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002250 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2251 else
2252 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2253}
2254
John McCallf85e1932011-06-15 23:02:42 +00002255static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2256 LValue lvalue,
2257 QualType type) {
2258 switch (type.getObjCLifetime()) {
2259 case Qualifiers::OCL_None:
2260 case Qualifiers::OCL_ExplicitNone:
2261 case Qualifiers::OCL_Strong:
2262 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002263 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002264 false);
2265
2266 case Qualifiers::OCL_Weak:
2267 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2268 true);
2269 }
2270
2271 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002272}
2273
2274static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2275 const Expr *e) {
2276 e = e->IgnoreParens();
2277 QualType type = e->getType();
2278
John McCall21480112011-08-30 00:57:29 +00002279 // If we're loading retained from a __strong xvalue, we can avoid
2280 // an extra retain/release pair by zeroing out the source of this
2281 // "move" operation.
2282 if (e->isXValue() &&
2283 !type.isConstQualified() &&
2284 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2285 // Emit the lvalue.
2286 LValue lv = CGF.EmitLValue(e);
2287
2288 // Load the object pointer.
2289 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2290
2291 // Set the source pointer to NULL.
2292 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2293
2294 return TryEmitResult(result, true);
2295 }
2296
John McCallf85e1932011-06-15 23:02:42 +00002297 // As a very special optimization, in ARC++, if the l-value is the
2298 // result of a non-volatile assignment, do a simple retain of the
2299 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002300 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002301 !type.isVolatileQualified() &&
2302 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2303 isa<BinaryOperator>(e) &&
2304 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2305 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2306
2307 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2308}
2309
2310static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2311 llvm::Value *value);
2312
2313/// Given that the given expression is some sort of call (which does
2314/// not return retained), emit a retain following it.
2315static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2316 llvm::Value *value = CGF.EmitScalarExpr(e);
2317 return emitARCRetainAfterCall(CGF, value);
2318}
2319
2320static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2321 llvm::Value *value) {
2322 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2323 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2324
2325 // Place the retain immediately following the call.
2326 CGF.Builder.SetInsertPoint(call->getParent(),
2327 ++llvm::BasicBlock::iterator(call));
2328 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2329
2330 CGF.Builder.restoreIP(ip);
2331 return value;
2332 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2333 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2334
2335 // Place the retain at the beginning of the normal destination block.
2336 llvm::BasicBlock *BB = invoke->getNormalDest();
2337 CGF.Builder.SetInsertPoint(BB, BB->begin());
2338 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2339
2340 CGF.Builder.restoreIP(ip);
2341 return value;
2342
2343 // Bitcasts can arise because of related-result returns. Rewrite
2344 // the operand.
2345 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2346 llvm::Value *operand = bitcast->getOperand(0);
2347 operand = emitARCRetainAfterCall(CGF, operand);
2348 bitcast->setOperand(0, operand);
2349 return bitcast;
2350
2351 // Generic fall-back case.
2352 } else {
2353 // Retain using the non-block variant: we never need to do a copy
2354 // of a block that's been returned to us.
2355 return CGF.EmitARCRetainNonBlock(value);
2356 }
2357}
2358
John McCalldc05b112011-09-10 01:16:55 +00002359/// Determine whether it might be important to emit a separate
2360/// objc_retain_block on the result of the given expression, or
2361/// whether it's okay to just emit it in a +1 context.
2362static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2363 assert(e->getType()->isBlockPointerType());
2364 e = e->IgnoreParens();
2365
2366 // For future goodness, emit block expressions directly in +1
2367 // contexts if we can.
2368 if (isa<BlockExpr>(e))
2369 return false;
2370
2371 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2372 switch (cast->getCastKind()) {
2373 // Emitting these operations in +1 contexts is goodness.
2374 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002375 case CK_ARCReclaimReturnedObject:
2376 case CK_ARCConsumeObject:
2377 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002378 return false;
2379
2380 // These operations preserve a block type.
2381 case CK_NoOp:
2382 case CK_BitCast:
2383 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2384
2385 // These operations are known to be bad (or haven't been considered).
2386 case CK_AnyPointerToBlockPointerCast:
2387 default:
2388 return true;
2389 }
2390 }
2391
2392 return true;
2393}
2394
John McCall4b9c2d22011-11-06 09:01:30 +00002395/// Try to emit a PseudoObjectExpr at +1.
2396///
2397/// This massively duplicates emitPseudoObjectRValue.
2398static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2399 const PseudoObjectExpr *E) {
2400 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2401
2402 // Find the result expression.
2403 const Expr *resultExpr = E->getResultExpr();
2404 assert(resultExpr);
2405 TryEmitResult result;
2406
2407 for (PseudoObjectExpr::const_semantics_iterator
2408 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2409 const Expr *semantic = *i;
2410
2411 // If this semantic expression is an opaque value, bind it
2412 // to the result of its source expression.
2413 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2414 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2415 OVMA opaqueData;
2416
2417 // If this semantic is the result of the pseudo-object
2418 // expression, try to evaluate the source as +1.
2419 if (ov == resultExpr) {
2420 assert(!OVMA::shouldBindAsLValue(ov));
2421 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2422 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2423
2424 // Otherwise, just bind it.
2425 } else {
2426 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2427 }
2428 opaques.push_back(opaqueData);
2429
2430 // Otherwise, if the expression is the result, evaluate it
2431 // and remember the result.
2432 } else if (semantic == resultExpr) {
2433 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2434
2435 // Otherwise, evaluate the expression in an ignored context.
2436 } else {
2437 CGF.EmitIgnoredExpr(semantic);
2438 }
2439 }
2440
2441 // Unbind all the opaques now.
2442 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2443 opaques[i].unbind(CGF);
2444
2445 return result;
2446}
2447
John McCallf85e1932011-06-15 23:02:42 +00002448static TryEmitResult
2449tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002450 // Look through cleanups.
2451 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002452 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002453 CodeGenFunction::RunCleanupsScope scope(CGF);
2454 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2455 }
2456
John McCallf85e1932011-06-15 23:02:42 +00002457 // The desired result type, if it differs from the type of the
2458 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002459 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002460
2461 while (true) {
2462 e = e->IgnoreParens();
2463
2464 // There's a break at the end of this if-chain; anything
2465 // that wants to keep looping has to explicitly continue.
2466 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2467 switch (ce->getCastKind()) {
2468 // No-op casts don't change the type, so we just ignore them.
2469 case CK_NoOp:
2470 e = ce->getSubExpr();
2471 continue;
2472
2473 case CK_LValueToRValue: {
2474 TryEmitResult loadResult
2475 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2476 if (resultType) {
2477 llvm::Value *value = loadResult.getPointer();
2478 value = CGF.Builder.CreateBitCast(value, resultType);
2479 loadResult.setPointer(value);
2480 }
2481 return loadResult;
2482 }
2483
2484 // These casts can change the type, so remember that and
2485 // soldier on. We only need to remember the outermost such
2486 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002487 case CK_CPointerToObjCPointerCast:
2488 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002489 case CK_AnyPointerToBlockPointerCast:
2490 case CK_BitCast:
2491 if (!resultType)
2492 resultType = CGF.ConvertType(ce->getType());
2493 e = ce->getSubExpr();
2494 assert(e->getType()->hasPointerRepresentation());
2495 continue;
2496
2497 // For consumptions, just emit the subexpression and thus elide
2498 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002499 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002500 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2501 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2502 return TryEmitResult(result, true);
2503 }
2504
John McCalldc05b112011-09-10 01:16:55 +00002505 // Block extends are net +0. Naively, we could just recurse on
2506 // the subexpression, but actually we need to ensure that the
2507 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002508 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002509 llvm::Value *result; // will be a +0 value
2510
2511 // If we can't safely assume the sub-expression will produce a
2512 // block-copied value, emit the sub-expression at +0.
2513 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2514 result = CGF.EmitScalarExpr(ce->getSubExpr());
2515
2516 // Otherwise, try to emit the sub-expression at +1 recursively.
2517 } else {
2518 TryEmitResult subresult
2519 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2520 result = subresult.getPointer();
2521
2522 // If that produced a retained value, just use that,
2523 // possibly casting down.
2524 if (subresult.getInt()) {
2525 if (resultType)
2526 result = CGF.Builder.CreateBitCast(result, resultType);
2527 return TryEmitResult(result, true);
2528 }
2529
2530 // Otherwise it's +0.
2531 }
2532
2533 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002534 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002535 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2536 return TryEmitResult(result, true);
2537 }
2538
John McCall7e5e5f42011-07-07 06:58:02 +00002539 // For reclaims, emit the subexpression as a retained call and
2540 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002541 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002542 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2543 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2544 return TryEmitResult(result, true);
2545 }
2546
John McCallf85e1932011-06-15 23:02:42 +00002547 default:
2548 break;
2549 }
2550
2551 // Skip __extension__.
2552 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2553 if (op->getOpcode() == UO_Extension) {
2554 e = op->getSubExpr();
2555 continue;
2556 }
2557
2558 // For calls and message sends, use the retained-call logic.
2559 // Delegate inits are a special case in that they're the only
2560 // returns-retained expression that *isn't* surrounded by
2561 // a consume.
2562 } else if (isa<CallExpr>(e) ||
2563 (isa<ObjCMessageExpr>(e) &&
2564 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2565 llvm::Value *result = emitARCRetainCall(CGF, e);
2566 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2567 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002568
2569 // Look through pseudo-object expressions.
2570 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2571 TryEmitResult result
2572 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2573 if (resultType) {
2574 llvm::Value *value = result.getPointer();
2575 value = CGF.Builder.CreateBitCast(value, resultType);
2576 result.setPointer(value);
2577 }
2578 return result;
John McCallf85e1932011-06-15 23:02:42 +00002579 }
2580
2581 // Conservatively halt the search at any other expression kind.
2582 break;
2583 }
2584
2585 // We didn't find an obvious production, so emit what we've got and
2586 // tell the caller that we didn't manage to retain.
2587 llvm::Value *result = CGF.EmitScalarExpr(e);
2588 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2589 return TryEmitResult(result, false);
2590}
2591
2592static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2593 LValue lvalue,
2594 QualType type) {
2595 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2596 llvm::Value *value = result.getPointer();
2597 if (!result.getInt())
2598 value = CGF.EmitARCRetain(type, value);
2599 return value;
2600}
2601
2602/// EmitARCRetainScalarExpr - Semantically equivalent to
2603/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2604/// best-effort attempt to peephole expressions that naturally produce
2605/// retained objects.
2606llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2607 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2608 llvm::Value *value = result.getPointer();
2609 if (!result.getInt())
2610 value = EmitARCRetain(e->getType(), value);
2611 return value;
2612}
2613
2614llvm::Value *
2615CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2616 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2617 llvm::Value *value = result.getPointer();
2618 if (result.getInt())
2619 value = EmitARCAutorelease(value);
2620 else
2621 value = EmitARCRetainAutorelease(e->getType(), value);
2622 return value;
2623}
2624
John McCall348f16f2011-10-04 06:23:45 +00002625llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2626 llvm::Value *result;
2627 bool doRetain;
2628
2629 if (shouldEmitSeparateBlockRetain(e)) {
2630 result = EmitScalarExpr(e);
2631 doRetain = true;
2632 } else {
2633 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2634 result = subresult.getPointer();
2635 doRetain = !subresult.getInt();
2636 }
2637
2638 if (doRetain)
2639 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2640 return EmitObjCConsumeObject(e->getType(), result);
2641}
2642
John McCall2b014d62011-10-01 10:32:24 +00002643llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2644 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002645 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002646 // Do so before running any cleanups for the full-expression.
2647 // tryEmitARCRetainScalarExpr does make an effort to do things
2648 // inside cleanups, but there are crazy cases like
2649 // @throw A().foo;
2650 // where a full retain+autorelease is required and would
2651 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002652 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2653 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002654 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002655 }
John McCall2b014d62011-10-01 10:32:24 +00002656
John McCall1a343eb2011-11-10 08:15:53 +00002657 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002658 return EmitARCRetainAutoreleaseScalarExpr(expr);
2659 }
2660
2661 // Otherwise, use the normal scalar-expression emission. The
2662 // exception machinery doesn't do anything special with the
2663 // exception like retaining it, so there's no safety associated with
2664 // only running cleanups after the throw has started, and when it
2665 // matters it tends to be substantially inferior code.
2666 return EmitScalarExpr(expr);
2667}
2668
John McCallf85e1932011-06-15 23:02:42 +00002669std::pair<LValue,llvm::Value*>
2670CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2671 bool ignored) {
2672 // Evaluate the RHS first.
2673 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2674 llvm::Value *value = result.getPointer();
2675
John McCallfb720812011-07-28 07:23:35 +00002676 bool hasImmediateRetain = result.getInt();
2677
2678 // If we didn't emit a retained object, and the l-value is of block
2679 // type, then we need to emit the block-retain immediately in case
2680 // it invalidates the l-value.
2681 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002682 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002683 hasImmediateRetain = true;
2684 }
2685
John McCallf85e1932011-06-15 23:02:42 +00002686 LValue lvalue = EmitLValue(e->getLHS());
2687
2688 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002689 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002690 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002691 EmitLoadOfScalar(lvalue);
2692 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002693 EmitARCRelease(oldValue, /*precise*/ false);
2694 } else {
John McCall545d9962011-06-25 02:11:03 +00002695 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002696 }
2697
2698 return std::pair<LValue,llvm::Value*>(lvalue, value);
2699}
2700
2701std::pair<LValue,llvm::Value*>
2702CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2703 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2704 LValue lvalue = EmitLValue(e->getLHS());
2705
Eli Friedman6da2c712011-12-03 04:14:32 +00002706 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002707
2708 return std::pair<LValue,llvm::Value*>(lvalue, value);
2709}
2710
2711void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002712 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002713 const Stmt *subStmt = ARPS.getSubStmt();
2714 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2715
2716 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002717 if (DI)
2718 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002719
2720 // Keep track of the current cleanup stack depth.
2721 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002722 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002723 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2724 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2725 } else {
2726 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2727 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2728 }
2729
2730 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2731 E = S.body_end(); I != E; ++I)
2732 EmitStmt(*I);
2733
Eric Christopher73fb3502011-10-13 21:45:18 +00002734 if (DI)
2735 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002736}
John McCall0c24c802011-06-24 23:21:27 +00002737
2738/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2739/// make sure it survives garbage collection until this point.
2740void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2741 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002742 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002743 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002744 llvm::Value *extender
2745 = llvm::InlineAsm::get(extenderType,
2746 /* assembly */ "",
2747 /* constraints */ "r",
2748 /* side effects */ true);
2749
2750 object = Builder.CreateBitCast(object, VoidPtrTy);
2751 Builder.CreateCall(extender, object)->setDoesNotThrow();
2752}
2753
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002754/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002755/// non-trivial copy assignment function, produce following helper function.
2756/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2757///
2758llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002759CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2760 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002761 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002762 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002763 return 0;
2764 QualType Ty = PID->getPropertyIvarDecl()->getType();
2765 if (!Ty->isRecordType())
2766 return 0;
2767 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002768 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002769 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002770 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002771 if (hasTrivialSetExpr(PID))
2772 return 0;
2773 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2774 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2775 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002776
2777 ASTContext &C = getContext();
2778 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002779 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002780 FunctionDecl *FD = FunctionDecl::Create(C,
2781 C.getTranslationUnitDecl(),
2782 SourceLocation(),
2783 SourceLocation(), II, C.VoidTy, 0,
2784 SC_Static,
2785 SC_None,
2786 false,
2787 true);
2788
2789 QualType DestTy = C.getPointerType(Ty);
2790 QualType SrcTy = Ty;
2791 SrcTy.addConst();
2792 SrcTy = C.getPointerType(SrcTy);
2793
2794 FunctionArgList args;
2795 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2796 args.push_back(&dstDecl);
2797 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2798 args.push_back(&srcDecl);
2799
2800 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002801 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2802 FunctionType::ExtInfo(),
2803 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002804
John McCallde5d3c72012-02-17 03:33:10 +00002805 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002806
2807 llvm::Function *Fn =
2808 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002809 "__assign_helper_atomic_property_",
2810 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002811
2812 if (CGM.getModuleDebugInfo())
2813 DebugInfo = CGM.getModuleDebugInfo();
2814
2815
2816 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2817
John McCallf4b88a42012-03-10 09:33:50 +00002818 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2819 VK_RValue, SourceLocation());
2820 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2821 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002822
John McCallf4b88a42012-03-10 09:33:50 +00002823 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2824 VK_RValue, SourceLocation());
2825 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2826 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002827
John McCallf4b88a42012-03-10 09:33:50 +00002828 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002829 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002830 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2831 Args, 2, DestTy->getPointeeType(),
2832 VK_LValue, SourceLocation());
2833
2834 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002835
2836 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002837 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002838 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002839 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002840}
2841
2842llvm::Constant *
2843CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2844 const ObjCPropertyImplDecl *PID) {
2845 // FIXME. This api is for NeXt runtime only for now.
David Blaikie4e4d0842012-03-11 07:00:24 +00002846 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002847 return 0;
2848 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2849 QualType Ty = PD->getType();
2850 if (!Ty->isRecordType())
2851 return 0;
2852 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2853 return 0;
2854 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002855
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002856 if (hasTrivialGetExpr(PID))
2857 return 0;
2858 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2859 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2860 return HelperFn;
2861
2862
2863 ASTContext &C = getContext();
2864 IdentifierInfo *II
2865 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2866 FunctionDecl *FD = FunctionDecl::Create(C,
2867 C.getTranslationUnitDecl(),
2868 SourceLocation(),
2869 SourceLocation(), II, C.VoidTy, 0,
2870 SC_Static,
2871 SC_None,
2872 false,
2873 true);
2874
2875 QualType DestTy = C.getPointerType(Ty);
2876 QualType SrcTy = Ty;
2877 SrcTy.addConst();
2878 SrcTy = C.getPointerType(SrcTy);
2879
2880 FunctionArgList args;
2881 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2882 args.push_back(&dstDecl);
2883 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2884 args.push_back(&srcDecl);
2885
2886 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002887 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2888 FunctionType::ExtInfo(),
2889 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002890
John McCallde5d3c72012-02-17 03:33:10 +00002891 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002892
2893 llvm::Function *Fn =
2894 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2895 "__copy_helper_atomic_property_", &CGM.getModule());
2896
2897 if (CGM.getModuleDebugInfo())
2898 DebugInfo = CGM.getModuleDebugInfo();
2899
2900
2901 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2902
John McCallf4b88a42012-03-10 09:33:50 +00002903 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002904 VK_RValue, SourceLocation());
2905
John McCallf4b88a42012-03-10 09:33:50 +00002906 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2907 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002908
2909 CXXConstructExpr *CXXConstExpr =
2910 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2911
2912 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002913 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002914 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2915 ++A;
2916
2917 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2918 A != AEnd; ++A)
2919 ConstructorArgs.push_back(*A);
2920
2921 CXXConstructExpr *TheCXXConstructExpr =
2922 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2923 CXXConstExpr->getConstructor(),
2924 CXXConstExpr->isElidable(),
2925 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002926 CXXConstExpr->hadMultipleCandidates(),
2927 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002928 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00002929 CXXConstExpr->getConstructionKind(),
2930 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002931
John McCallf4b88a42012-03-10 09:33:50 +00002932 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2933 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002934
John McCallf4b88a42012-03-10 09:33:50 +00002935 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00002936 CharUnits Alignment
2937 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002938 EmitAggExpr(TheCXXConstructExpr,
2939 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2940 AggValueSlot::IsDestructed,
2941 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +00002942 AggValueSlot::IsNotAliased,
2943 AggValueSlot::IsCompleteObject));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002944
2945 FinishFunction();
2946 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2947 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2948 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002949}
2950
Eli Friedmancae40c42012-02-28 01:08:45 +00002951llvm::Value *
2952CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2953 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002954 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2955 Selector CopySelector =
2956 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002957 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2958 Selector AutoreleaseSelector =
2959 getContext().Selectors.getNullarySelector(AutoreleaseID);
2960
2961 // Emit calls to retain/autorelease.
2962 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2963 llvm::Value *Val = Block;
2964 RValue Result;
2965 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002966 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002967 Val, CallArgList(), 0, 0);
2968 Val = Result.getScalarVal();
2969 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2970 Ty, AutoreleaseSelector,
2971 Val, CallArgList(), 0, 0);
2972 Val = Result.getScalarVal();
2973 return Val;
2974}
2975
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002976
Ted Kremenek2979ec72008-04-09 15:51:31 +00002977CGObjCRuntime::~CGObjCRuntime() {}