blob: a7e96ca044c20b7abae5a34a2fe4c61595ffc48b [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,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000033 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000034 const ObjCMethodDecl *Method,
35 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
39static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000040 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000041 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattner8fdf3282008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000047{
David Chisnall0d13f6f2010-01-23 02:40:42 +000048 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000052}
53
Patrick Beardeb382ec2012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
56/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000057///
Eric Christopher16098f32012-03-29 17:31:31 +000058llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Patrick Beardeb382ec2012-04-19 00:25:12 +000061 const Expr *SubExpr = E->getSubExpr();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Get the method.
Patrick Beardeb382ec2012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 assert(BoxingMethod && "BoxingMethod is null");
65 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
66 Selector Sel = BoxingMethod->getSelector();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000067
68 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-04-19 00:25:12 +000069 // Assumes that the method was introduced in the class that should be
70 // messaged (avoids pulling it out of the result type).
Ted Kremenekebcb57a2012-03-06 20:05:56 +000071 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000072 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
73 llvm::Value *Receiver = Runtime.GetClass(Builder, ClassDecl);
74
75 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000076 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beardeb382ec2012-04-19 00:25:12 +000077 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000078 CallArgList Args;
79 Args.add(RV, ArgQT);
Patrick Beardeb382ec2012-04-19 00:25:12 +000080
Ted Kremenekebcb57a2012-03-06 20:05:56 +000081 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beardeb382ec2012-04-19 00:25:12 +000082 BoxingMethod->getResultType(), Sel, Receiver, Args,
83 ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000084 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86}
87
88llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
112 // Perform the actual initialialization of the array(s).
113 for (uint64_t i = 0; i < NumElements; i++) {
114 if (ALE) {
115 // Emit the initializer.
116 const Expr *Rhs = ALE->getElement(i);
117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
118 ElementType,
119 Context.getTypeAlignInChars(Rhs->getType()),
120 Context);
121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
122 } else {
123 // Emit the key initializer.
124 const Expr *Key = DLE->getKeyValueElement(i).Key;
125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
126 ElementType,
127 Context.getTypeAlignInChars(Key->getType()),
128 Context);
129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
130
131 // Emit the value initializer.
132 const Expr *Value = DLE->getKeyValueElement(i).Value;
133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
134 ElementType,
135 Context.getTypeAlignInChars(Value->getType()),
136 Context);
137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
138 }
139 }
140
141 // Generate the argument list.
142 CallArgList Args;
143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
144 const ParmVarDecl *argDecl = *PI++;
145 QualType ArgQT = argDecl->getType().getUnqualifiedType();
146 Args.add(RValue::get(Objects), ArgQT);
147 if (DLE) {
148 argDecl = *PI++;
149 ArgQT = argDecl->getType().getUnqualifiedType();
150 Args.add(RValue::get(Keys), ArgQT);
151 }
152 argDecl = *PI;
153 ArgQT = argDecl->getType().getUnqualifiedType();
154 llvm::Value *Count =
155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
156 Args.add(RValue::get(Count), ArgQT);
157
158 // Generate a reference to the class pointer, which will be the receiver.
159 Selector Sel = MethodWithObjects->getSelector();
160 QualType ResultType = E->getType();
161 const ObjCObjectPointerType *InterfacePointerType
162 = ResultType->getAsObjCInterfacePointerType();
163 ObjCInterfaceDecl *Class
164 = InterfacePointerType->getObjectType()->getInterface();
165 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
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,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000205 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000206 const ObjCMethodDecl *Method,
207 RValue Result) {
208 if (!Method)
209 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000210
Douglas Gregor926df6c2011-06-11 01:09:30 +0000211 if (!Method->hasRelatedResultType() ||
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000212 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor926df6c2011-06-11 01:09:30 +0000213 !Result.isScalar())
214 return Result;
215
216 // We have applied a related result type. Cast the rvalue appropriately.
217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000218 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000219}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000220
John McCalldc7c5ad2011-07-22 08:53:00 +0000221/// Decide whether to extend the lifetime of the receiver of a
222/// returns-inner-pointer message.
223static bool
224shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
225 switch (message->getReceiverKind()) {
226
227 // For a normal instance message, we should extend unless the
228 // receiver is loaded from a variable with precise lifetime.
229 case ObjCMessageExpr::Instance: {
230 const Expr *receiver = message->getInstanceReceiver();
231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
233 receiver = ice->getSubExpr()->IgnoreParens();
234
235 // Only __strong variables.
236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
237 return true;
238
239 // All ivars and fields have precise lifetime.
240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
241 return false;
242
243 // Otherwise, check for variables.
244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
245 if (!declRef) return true;
246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
247 if (!var) return true;
248
249 // All variables have precise lifetime except local variables with
250 // automatic storage duration that aren't specially marked.
251 return (var->hasLocalStorage() &&
252 !var->hasAttr<ObjCPreciseLifetimeAttr>());
253 }
254
255 case ObjCMessageExpr::Class:
256 case ObjCMessageExpr::SuperClass:
257 // It's never necessary for class objects.
258 return false;
259
260 case ObjCMessageExpr::SuperInstance:
261 // We generally assume that 'self' lives throughout a method call.
262 return false;
263 }
264
265 llvm_unreachable("invalid receiver kind");
266}
267
John McCallef072fd2010-05-22 01:48:05 +0000268RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
269 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000270 // Only the lookup mechanism and first two arguments of the method
271 // implementation vary between runtimes. We can get the receiver and
272 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000273
John McCallf85e1932011-06-15 23:02:42 +0000274 bool isDelegateInit = E->isDelegateInitCall();
275
John McCalldc7c5ad2011-07-22 08:53:00 +0000276 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000277
John McCallf85e1932011-06-15 23:02:42 +0000278 // We don't retain the receiver in delegate init calls, and this is
279 // safe because the receiver value is always loaded from 'self',
280 // which we zero out. We don't want to Block_copy block receivers,
281 // though.
282 bool retainSelf =
283 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000284 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000285 method &&
286 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000287
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000288 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000289 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000290 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000291 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000292 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000293 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000294 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000295 switch (E->getReceiverKind()) {
296 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000297 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000298 if (retainSelf) {
299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
300 E->getInstanceReceiver());
301 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000302 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000303 } else
304 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000305 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000306
Douglas Gregor04badcf2010-04-21 00:45:42 +0000307 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000308 ReceiverType = E->getClassReceiver();
309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000310 assert(ObjTy && "Invalid Objective-C class message send");
311 OID = ObjTy->getInterface();
312 assert(OID && "Invalid Objective-C class message send");
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
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000404 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000405}
406
John McCallf85e1932011-06-15 23:02:42 +0000407namespace {
408struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000409 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000411
412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000413 const ObjCInterfaceDecl *iface = impl->getClassInterface();
414 if (!iface->getSuperClass()) return;
415
John McCall799d34e2011-07-13 18:26:47 +0000416 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
417
John McCallf85e1932011-06-15 23:02:42 +0000418 // Call [super dealloc] if we have a superclass.
419 llvm::Value *self = CGF.LoadObjCSelf();
420
421 CallArgList args;
422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
423 CGF.getContext().VoidTy,
424 method->getSelector(),
425 iface,
John McCall799d34e2011-07-13 18:26:47 +0000426 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000427 self,
428 /*is class msg*/ false,
429 args,
430 method);
431 }
432};
433}
434
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000435/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
436/// the LLVM function and sets the other context used by
437/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000438void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000439 const ObjCContainerDecl *CD,
440 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000441 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000442 // Check if we should generate debug info for this method.
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
James Dennett2ee5ba32012-06-15 22:10:14 +0000701/// \brief Generate an Objective-C property getter function.
702///
703/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000704/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000705void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
706 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000707 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000708 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000709 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
710 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
711 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000712 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000714 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000715
716 FinishFunction();
717}
718
John McCall6c11f0b2011-09-13 06:00:03 +0000719static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
720 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000721 if (!getter) return true;
722
723 // Sema only makes only of these when the ivar has a C++ class type,
724 // so the form is pretty constrained.
725
John McCall6c11f0b2011-09-13 06:00:03 +0000726 // If the property has a reference type, we might just be binding a
727 // reference, in which case the result will be a gl-value. We should
728 // treat this as a non-trivial operation.
729 if (getter->isGLValue())
730 return false;
731
John McCall1e1f4872011-09-13 03:34:09 +0000732 // If we selected a trivial copy-constructor, we're okay.
733 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
734 return (construct->getConstructor()->isTrivial());
735
736 // The constructor might require cleanups (in which case it's never
737 // trivial).
738 assert(isa<ExprWithCleanups>(getter));
739 return false;
740}
741
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000742/// emitCPPObjectAtomicGetterCall - Call the runtime function to
743/// copy the ivar into the resturn slot.
744static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
745 llvm::Value *returnAddr,
746 ObjCIvarDecl *ivar,
747 llvm::Constant *AtomicHelperFn) {
748 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
749 // AtomicHelperFn);
750 CallArgList args;
751
752 // The 1st argument is the return Slot.
753 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
754
755 // The 2nd argument is the address of the ivar.
756 llvm::Value *ivarAddr =
757 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
758 CGF.LoadObjCSelf(), ivar, 0).getAddress();
759 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
760 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
761
762 // Third argument is the helper function.
763 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
764
765 llvm::Value *copyCppAtomicObjectFn =
766 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000767 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
768 FunctionType::ExtInfo(),
769 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000770 copyCppAtomicObjectFn, ReturnValueSlot(), args);
771}
772
John McCall1e1f4872011-09-13 03:34:09 +0000773void
774CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000775 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000776 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000777 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000778 // If there's a non-trivial 'get' expression, we just have to emit that.
779 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000780 if (!AtomicHelperFn) {
781 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
782 /*nrvo*/ 0);
783 EmitReturnStmt(ret);
784 }
785 else {
786 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
787 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
788 ivar, AtomicHelperFn);
789 }
John McCall1e1f4872011-09-13 03:34:09 +0000790 return;
791 }
792
793 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
794 QualType propType = prop->getType();
795 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
796
797 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
798
799 // Pick an implementation strategy.
800 PropertyImplStrategy strategy(CGM, propImpl);
801 switch (strategy.getKind()) {
802 case PropertyImplStrategy::Native: {
803 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
804
805 // Currently, all atomic accesses have to be through integer
806 // types, so there's no point in trying to pick a prettier type.
807 llvm::Type *bitcastType =
808 llvm::Type::getIntNTy(getLLVMContext(),
809 getContext().toBits(strategy.getIvarSize()));
810 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
811
812 // Perform an atomic load. This does not impose ordering constraints.
813 llvm::Value *ivarAddr = LV.getAddress();
814 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
815 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
816 load->setAlignment(strategy.getIvarAlignment().getQuantity());
817 load->setAtomic(llvm::Unordered);
818
819 // Store that value into the return address. Doing this with a
820 // bitcast is likely to produce some pretty ugly IR, but it's not
821 // the *most* terrible thing in the world.
822 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
823
824 // Make sure we don't do an autorelease.
825 AutoreleaseResult = false;
826 return;
827 }
828
829 case PropertyImplStrategy::GetSetProperty: {
830 llvm::Value *getPropertyFn =
831 CGM.getObjCRuntime().GetPropertyGetFunction();
832 if (!getPropertyFn) {
833 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000834 return;
835 }
836
837 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
838 // FIXME: Can't this be simpler? This might even be worse than the
839 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000840 llvm::Value *cmd =
841 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
842 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
843 llvm::Value *ivarOffset =
844 EmitIvarOffset(classImpl->getClassInterface(), ivar);
845
846 CallArgList args;
847 args.add(RValue::get(self), getContext().getObjCIdType());
848 args.add(RValue::get(cmd), getContext().getObjCSelType());
849 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000850 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
851 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000852
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000853 // FIXME: We shouldn't need to get the function info here, the
854 // runtime already should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +0000855 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args,
856 FunctionType::ExtInfo(),
857 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000858 getPropertyFn, ReturnValueSlot(), args);
859
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000860 // We need to fix the type here. Ivars with copy & retain are
861 // always objects so we don't need to worry about complex or
862 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000863 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian52c18b02012-04-26 21:33:14 +0000864 getTypes().ConvertType(getterMethod->getResultType())));
John McCall1e1f4872011-09-13 03:34:09 +0000865
866 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000867
868 // objc_getProperty does an autorelease, so we should suppress ours.
869 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000870
John McCall1e1f4872011-09-13 03:34:09 +0000871 return;
872 }
873
874 case PropertyImplStrategy::CopyStruct:
875 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
876 strategy.hasStrongMember());
877 return;
878
879 case PropertyImplStrategy::Expression:
880 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
881 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
882
883 QualType ivarType = ivar->getType();
884 if (ivarType->isAnyComplexType()) {
885 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
886 LV.isVolatileQualified());
887 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
888 } else if (hasAggregateLLVMType(ivarType)) {
889 // The return value slot is guaranteed to not be aliased, but
890 // that's not necessarily the same as "on the stack", so
891 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000892 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000893 } else {
John McCallba3dd902011-07-22 05:23:13 +0000894 llvm::Value *value;
895 if (propType->isReferenceType()) {
896 value = LV.getAddress();
897 } else {
898 // We want to load and autoreleaseReturnValue ARC __weak ivars.
899 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000900 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000901
902 // Otherwise we want to do a simple load, suppressing the
903 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000904 } else {
John McCallba3dd902011-07-22 05:23:13 +0000905 value = EmitLoadOfLValue(LV).getScalarVal();
906 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000907 }
John McCallf85e1932011-06-15 23:02:42 +0000908
John McCallba3dd902011-07-22 05:23:13 +0000909 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000910 value = Builder.CreateBitCast(value,
911 ConvertType(GetterMethodDecl->getResultType()));
John McCallba3dd902011-07-22 05:23:13 +0000912 }
913
914 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000915 }
John McCall1e1f4872011-09-13 03:34:09 +0000916 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000917 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000918
John McCall1e1f4872011-09-13 03:34:09 +0000919 }
920 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000921}
922
John McCall41bdde92011-09-12 23:06:44 +0000923/// emitStructSetterCall - Call the runtime function to store the value
924/// from the first formal parameter into the given ivar.
925static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
926 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000927 // objc_copyStruct (&structIvar, &Arg,
928 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000929 CallArgList args;
930
931 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000932 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
933 CGF.LoadObjCSelf(), ivar, 0)
934 .getAddress();
935 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
936 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000937
938 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000939 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000940 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000941 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000942 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
943 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
944 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000945
946 // The third argument is the sizeof the type.
947 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000948 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
949 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000950
John McCall41bdde92011-09-12 23:06:44 +0000951 // The fourth argument is the 'isAtomic' flag.
952 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000953
John McCall41bdde92011-09-12 23:06:44 +0000954 // The fifth argument is the 'hasStrong' flag.
955 // FIXME: should this really always be false?
956 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
957
958 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000959 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
960 FunctionType::ExtInfo(),
961 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000962 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000963}
964
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000965/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
966/// the value from the first formal parameter into the given ivar, using
967/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
968static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
969 ObjCMethodDecl *OMD,
970 ObjCIvarDecl *ivar,
971 llvm::Constant *AtomicHelperFn) {
972 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
973 // AtomicHelperFn);
974 CallArgList args;
975
976 // The first argument is the address of the ivar.
977 llvm::Value *ivarAddr =
978 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
979 CGF.LoadObjCSelf(), ivar, 0).getAddress();
980 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
981 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
982
983 // The second argument is the address of the parameter variable.
984 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000985 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000986 VK_LValue, SourceLocation());
987 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
988 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
989 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
990
991 // Third argument is the helper function.
992 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
993
994 llvm::Value *copyCppAtomicObjectFn =
995 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCallde5d3c72012-02-17 03:33:10 +0000996 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
997 FunctionType::ExtInfo(),
998 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000999 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1000
1001
1002}
1003
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001004
John McCall1e1f4872011-09-13 03:34:09 +00001005static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1006 Expr *setter = PID->getSetterCXXAssignment();
1007 if (!setter) return true;
1008
1009 // Sema only makes only of these when the ivar has a C++ class type,
1010 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001011
1012 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001013 // This also implies that there's nothing non-trivial going on with
1014 // the arguments, because operator= can only be trivial if it's a
1015 // synthesized assignment operator and therefore both parameters are
1016 // references.
1017 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001018 if (const FunctionDecl *callee
1019 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1020 if (callee->isTrivial())
1021 return true;
1022 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001023 }
John McCall71c758d2011-09-10 09:17:20 +00001024
John McCall1e1f4872011-09-13 03:34:09 +00001025 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001026 return false;
1027}
1028
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001029static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001030 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001031 return false;
1032 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001033
1034 if (Target.getPlatformName() != "macosx")
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001035 return false;
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001036
1037 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001038}
1039
John McCall71c758d2011-09-10 09:17:20 +00001040void
1041CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001042 const ObjCPropertyImplDecl *propImpl,
1043 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001044 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001045 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001046 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001047
1048 // Just use the setter expression if Sema gave us one and it's
1049 // non-trivial.
1050 if (!hasTrivialSetExpr(propImpl)) {
1051 if (!AtomicHelperFn)
1052 // If non-atomic, assignment is called directly.
1053 EmitStmt(propImpl->getSetterCXXAssignment());
1054 else
1055 // If atomic, assignment is called via a locking api.
1056 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1057 AtomicHelperFn);
1058 return;
1059 }
John McCall71c758d2011-09-10 09:17:20 +00001060
John McCall1e1f4872011-09-13 03:34:09 +00001061 PropertyImplStrategy strategy(CGM, propImpl);
1062 switch (strategy.getKind()) {
1063 case PropertyImplStrategy::Native: {
1064 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001065
John McCall1e1f4872011-09-13 03:34:09 +00001066 LValue ivarLValue =
1067 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1068 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001069
John McCall1e1f4872011-09-13 03:34:09 +00001070 // Currently, all atomic accesses have to be through integer
1071 // types, so there's no point in trying to pick a prettier type.
1072 llvm::Type *bitcastType =
1073 llvm::Type::getIntNTy(getLLVMContext(),
1074 getContext().toBits(strategy.getIvarSize()));
1075 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1076
1077 // Cast both arguments to the chosen operation type.
1078 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1079 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1080
1081 // This bitcast load is likely to cause some nasty IR.
1082 llvm::Value *load = Builder.CreateLoad(argAddr);
1083
1084 // Perform an atomic store. There are no memory ordering requirements.
1085 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1086 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1087 store->setAtomic(llvm::Unordered);
1088 return;
1089 }
1090
1091 case PropertyImplStrategy::GetSetProperty:
1092 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001093
1094 llvm::Value *setOptimizedPropertyFn = 0;
1095 llvm::Value *setPropertyFn = 0;
1096 if (UseOptimizedSetter(CGM)) {
1097 // 10.8 code and GC is off
1098 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001099 CGM.getObjCRuntime()
1100 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1101 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001102 if (!setOptimizedPropertyFn) {
1103 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1104 return;
1105 }
John McCall71c758d2011-09-10 09:17:20 +00001106 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001107 else {
1108 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1109 if (!setPropertyFn) {
1110 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1111 return;
1112 }
1113 }
1114
John McCall71c758d2011-09-10 09:17:20 +00001115 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1116 // <is-atomic>, <is-copy>).
1117 llvm::Value *cmd =
1118 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1119 llvm::Value *self =
1120 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1121 llvm::Value *ivarOffset =
1122 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1123 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1124 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1125
1126 CallArgList args;
1127 args.add(RValue::get(self), getContext().getObjCIdType());
1128 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001129 if (setOptimizedPropertyFn) {
1130 args.add(RValue::get(arg), getContext().getObjCIdType());
1131 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1132 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1133 FunctionType::ExtInfo(),
1134 RequiredArgs::All),
1135 setOptimizedPropertyFn, ReturnValueSlot(), args);
1136 } else {
1137 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1138 args.add(RValue::get(arg), getContext().getObjCIdType());
1139 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1140 getContext().BoolTy);
1141 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1142 getContext().BoolTy);
1143 // FIXME: We shouldn't need to get the function info here, the runtime
1144 // already should have computed it to build the function.
1145 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1146 FunctionType::ExtInfo(),
1147 RequiredArgs::All),
1148 setPropertyFn, ReturnValueSlot(), args);
1149 }
1150
John McCall71c758d2011-09-10 09:17:20 +00001151 return;
1152 }
1153
John McCall1e1f4872011-09-13 03:34:09 +00001154 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001155 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001156 return;
John McCall1e1f4872011-09-13 03:34:09 +00001157
1158 case PropertyImplStrategy::Expression:
1159 break;
John McCall71c758d2011-09-10 09:17:20 +00001160 }
1161
1162 // Otherwise, fake up some ASTs and emit a normal assignment.
1163 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001164 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1165 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001166 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1167 selfDecl->getType(), CK_LValueToRValue, &self,
1168 VK_RValue);
1169 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1170 SourceLocation(), &selfLoad, true, true);
1171
1172 ParmVarDecl *argDecl = *setterMethod->param_begin();
1173 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001174 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001175 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1176 argType.getUnqualifiedType(), CK_LValueToRValue,
1177 &arg, VK_RValue);
1178
1179 // The property type can differ from the ivar type in some situations with
1180 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1181 // The following absurdity is just to ensure well-formed IR.
1182 CastKind argCK = CK_NoOp;
1183 if (ivarRef.getType()->isObjCObjectPointerType()) {
1184 if (argLoad.getType()->isObjCObjectPointerType())
1185 argCK = CK_BitCast;
1186 else if (argLoad.getType()->isBlockPointerType())
1187 argCK = CK_BlockPointerToObjCPointerCast;
1188 else
1189 argCK = CK_CPointerToObjCPointerCast;
1190 } else if (ivarRef.getType()->isBlockPointerType()) {
1191 if (argLoad.getType()->isBlockPointerType())
1192 argCK = CK_BitCast;
1193 else
1194 argCK = CK_AnyPointerToBlockPointerCast;
1195 } else if (ivarRef.getType()->isPointerType()) {
1196 argCK = CK_BitCast;
1197 }
1198 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1199 ivarRef.getType(), argCK, &argLoad,
1200 VK_RValue);
1201 Expr *finalArg = &argLoad;
1202 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1203 argLoad.getType()))
1204 finalArg = &argCast;
1205
1206
1207 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1208 ivarRef.getType(), VK_RValue, OK_Ordinary,
1209 SourceLocation());
1210 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001211}
1212
James Dennett2ee5ba32012-06-15 22:10:14 +00001213/// \brief Generate an Objective-C property setter function.
1214///
1215/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001216/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001217void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1218 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001219 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001220 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001221 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1222 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1223 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001224 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001225
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001226 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001227
1228 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001229}
1230
John McCalle81ac692011-03-22 07:05:39 +00001231namespace {
John McCall9928c482011-07-12 16:41:08 +00001232 struct DestroyIvar : EHScopeStack::Cleanup {
1233 private:
1234 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001235 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001236 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001237 bool useEHCleanupForArray;
1238 public:
1239 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1240 CodeGenFunction::Destroyer *destroyer,
1241 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001242 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001243 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001244
John McCallad346f42011-07-12 20:27:29 +00001245 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001246 LValue lvalue
1247 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1248 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001249 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001250 }
1251 };
1252}
1253
John McCall9928c482011-07-12 16:41:08 +00001254/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1255static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1256 llvm::Value *addr,
1257 QualType type) {
1258 llvm::Value *null = getNullForVariable(addr);
1259 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1260}
John McCallf85e1932011-06-15 23:02:42 +00001261
John McCalle81ac692011-03-22 07:05:39 +00001262static void emitCXXDestructMethod(CodeGenFunction &CGF,
1263 ObjCImplementationDecl *impl) {
1264 CodeGenFunction::RunCleanupsScope scope(CGF);
1265
1266 llvm::Value *self = CGF.LoadObjCSelf();
1267
Jordy Rosedb8264e2011-07-22 02:08:32 +00001268 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1269 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001270 ivar; ivar = ivar->getNextIvar()) {
1271 QualType type = ivar->getType();
1272
John McCalle81ac692011-03-22 07:05:39 +00001273 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001274 QualType::DestructionKind dtorKind = type.isDestructedType();
1275 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001276
John McCall9928c482011-07-12 16:41:08 +00001277 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001278
John McCall9928c482011-07-12 16:41:08 +00001279 // Use a call to objc_storeStrong to destroy strong ivars, for the
1280 // general benefit of the tools.
1281 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001282 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001283
John McCall9928c482011-07-12 16:41:08 +00001284 // Otherwise use the default for the destruction kind.
1285 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001286 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001287 }
John McCall9928c482011-07-12 16:41:08 +00001288
1289 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1290
1291 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1292 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001293 }
1294
1295 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1296}
1297
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001298void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1299 ObjCMethodDecl *MD,
1300 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001301 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001302 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001303
1304 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001305 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001306 // Suppress the final autorelease in ARC.
1307 AutoreleaseResult = false;
1308
Chris Lattner5f9e2722011-07-23 10:55:15 +00001309 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001310 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1311 E = IMP->init_end(); B != E; ++B) {
1312 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001313 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001314 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001315 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1316 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001317 EmitAggExpr(IvarInit->getInit(),
1318 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001319 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001320 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001321 }
1322 // constructor returns 'self'.
1323 CodeGenTypes &Types = CGM.getTypes();
1324 QualType IdTy(CGM.getContext().getObjCIdType());
1325 llvm::Value *SelfAsId =
1326 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1327 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001328
1329 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001330 } else {
John McCalle81ac692011-03-22 07:05:39 +00001331 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001332 }
1333 FinishFunction();
1334}
1335
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001336bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1337 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1338 it++; it++;
1339 const ABIArgInfo &AI = it->info;
1340 // FIXME. Is this sufficient check?
1341 return (AI.getKind() == ABIArgInfo::Indirect);
1342}
1343
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001344bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001345 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001346 return false;
1347 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1348 return FDTTy->getDecl()->hasObjectMember();
1349 return false;
1350}
1351
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001352llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001353 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1354 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001355}
1356
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001357QualType CodeGenFunction::TypeOfSelfObject() {
1358 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1359 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001360 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1361 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001362 return PTy->getPointeeType();
1363}
1364
Chris Lattner74391b42009-03-22 21:03:39 +00001365void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001366 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001367 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001369 if (!EnumerationMutationFn) {
1370 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1371 return;
1372 }
1373
Devang Patelbcbd03a2011-01-19 01:36:36 +00001374 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001375 if (DI)
1376 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001377
Devang Patel9d99f2d2011-06-13 23:15:32 +00001378 // The local variable comes into scope immediately.
1379 AutoVarEmission variable = AutoVarEmission::invalid();
1380 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1381 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1382
John McCalld88687f2011-01-07 01:49:06 +00001383 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Anders Carlssonf484c312008-08-31 02:33:12 +00001385 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001386 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001387 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001388 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Anders Carlssonf484c312008-08-31 02:33:12 +00001390 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001391 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001392
John McCalld88687f2011-01-07 01:49:06 +00001393 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001394 IdentifierInfo *II[] = {
1395 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1396 &CGM.getContext().Idents.get("objects"),
1397 &CGM.getContext().Idents.get("count")
1398 };
1399 Selector FastEnumSel =
1400 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001401
1402 QualType ItemsTy =
1403 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001404 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001405 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001406 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001407
John McCall990567c2011-07-27 01:07:15 +00001408 // Emit the collection pointer. In ARC, we do a retain.
1409 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001410 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001411 Collection = EmitARCRetainScalarExpr(S.getCollection());
1412
1413 // Enter a cleanup to do the release.
1414 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1415 } else {
1416 Collection = EmitScalarExpr(S.getCollection());
1417 }
Mike Stump1eb44332009-09-09 15:08:12 +00001418
John McCall4b302d32011-08-05 00:14:38 +00001419 // The 'continue' label needs to appear within the cleanup for the
1420 // collection object.
1421 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1422
John McCalld88687f2011-01-07 01:49:06 +00001423 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001424 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001425
1426 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001427 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001428
John McCalld88687f2011-01-07 01:49:06 +00001429 // The second argument is a temporary array with space for NumItems
1430 // pointers. We'll actually be loading elements from the array
1431 // pointer written into the control state; this buffer is so that
1432 // collections that *aren't* backed by arrays can still queue up
1433 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001434 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001435
John McCalld88687f2011-01-07 01:49:06 +00001436 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001437 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001438 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001439 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
John McCalld88687f2011-01-07 01:49:06 +00001441 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001442 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001443 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001444 getContext().UnsignedLongTy,
1445 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001446 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001447
John McCalld88687f2011-01-07 01:49:06 +00001448 // The initial number of objects that were returned in the buffer.
1449 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001450
John McCalld88687f2011-01-07 01:49:06 +00001451 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1452 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001453
John McCalld88687f2011-01-07 01:49:06 +00001454 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001455
John McCalld88687f2011-01-07 01:49:06 +00001456 // If the limit pointer was zero to begin with, the collection is
1457 // empty; skip all this.
1458 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1459 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001460
John McCalld88687f2011-01-07 01:49:06 +00001461 // Otherwise, initialize the loop.
1462 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001463
John McCalld88687f2011-01-07 01:49:06 +00001464 // Save the initial mutations value. This is the value at an
1465 // address that was written into the state object by
1466 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001467 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001468 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001469 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001470 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001471
John McCalld88687f2011-01-07 01:49:06 +00001472 llvm::Value *initialMutations =
1473 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001474
John McCalld88687f2011-01-07 01:49:06 +00001475 // Start looping. This is the point we return to whenever we have a
1476 // fresh, non-empty batch of objects.
1477 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1478 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001479
John McCalld88687f2011-01-07 01:49:06 +00001480 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001481 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001482 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001483
John McCalld88687f2011-01-07 01:49:06 +00001484 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001485 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001486 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001487
John McCalld88687f2011-01-07 01:49:06 +00001488 // Check whether the mutations value has changed from where it was
1489 // at start. StateMutationsPtr should actually be invariant between
1490 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001491 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001492 llvm::Value *currentMutations
1493 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001494
John McCalld88687f2011-01-07 01:49:06 +00001495 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001496 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001497
John McCalld88687f2011-01-07 01:49:06 +00001498 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1499 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001500
John McCalld88687f2011-01-07 01:49:06 +00001501 // If so, call the enumeration-mutation function.
1502 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001503 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001504 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001505 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001506 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001507 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001508 // FIXME: We shouldn't need to get the function info here, the runtime already
1509 // should have computed it to build the function.
John McCallde5d3c72012-02-17 03:33:10 +00001510 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1511 FunctionType::ExtInfo(),
1512 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001513 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
John McCalld88687f2011-01-07 01:49:06 +00001515 // Otherwise, or if the mutation function returns, just continue.
1516 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001517
John McCalld88687f2011-01-07 01:49:06 +00001518 // Initialize the element variable.
1519 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001520 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001521 LValue elementLValue;
1522 QualType elementType;
1523 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001524 // Initialize the variable, in case it's a __block variable or something.
1525 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001526
John McCall57b3b6a2011-02-22 07:16:58 +00001527 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001528 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001529 VK_LValue, SourceLocation());
1530 elementLValue = EmitLValue(&tempDRE);
1531 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001532 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001533
1534 if (D->isARCPseudoStrong())
1535 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001536 } else {
1537 elementLValue = LValue(); // suppress warning
1538 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001539 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001540 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001541 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001542
1543 // Fetch the buffer out of the enumeration state.
1544 // TODO: this pointer should actually be invariant between
1545 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001546 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001547 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001548 llvm::Value *EnumStateItems =
1549 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001550
John McCalld88687f2011-01-07 01:49:06 +00001551 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001552 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001553 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1554 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001555
John McCalld88687f2011-01-07 01:49:06 +00001556 // Cast that value to the right type.
1557 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1558 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001559
John McCalld88687f2011-01-07 01:49:06 +00001560 // Make sure we have an l-value. Yes, this gets evaluated every
1561 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001562 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001563 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001564 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001565 } else {
1566 EmitScalarInit(CurrentItem, elementLValue);
1567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
John McCall57b3b6a2011-02-22 07:16:58 +00001569 // If we do have an element variable, this assignment is the end of
1570 // its initialization.
1571 if (elementIsVariable)
1572 EmitAutoVarCleanups(variable);
1573
John McCalld88687f2011-01-07 01:49:06 +00001574 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001575 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001576 {
1577 RunCleanupsScope Scope(*this);
1578 EmitStmt(S.getBody());
1579 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001580 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001581
John McCalld88687f2011-01-07 01:49:06 +00001582 // Destroy the element variable now.
1583 elementVariableScope.ForceCleanup();
1584
1585 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001586 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001587
John McCalld88687f2011-01-07 01:49:06 +00001588 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001589
John McCalld88687f2011-01-07 01:49:06 +00001590 // First we check in the local buffer.
1591 llvm::Value *indexPlusOne
1592 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001593
John McCalld88687f2011-01-07 01:49:06 +00001594 // If we haven't overrun the buffer yet, we can continue.
1595 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1596 LoopBodyBB, FetchMoreBB);
1597
1598 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1599 count->addIncoming(count, AfterBody.getBlock());
1600
1601 // Otherwise, we have to fetch more elements.
1602 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
1604 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001605 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001606 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001607 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001608 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
John McCalld88687f2011-01-07 01:49:06 +00001610 // If we got a zero count, we're done.
1611 llvm::Value *refetchCount = CountRV.getScalarVal();
1612
1613 // (note that the message send might split FetchMoreBB)
1614 index->addIncoming(zero, Builder.GetInsertBlock());
1615 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1616
1617 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1618 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Anders Carlssonf484c312008-08-31 02:33:12 +00001620 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001621 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001622
John McCall57b3b6a2011-02-22 07:16:58 +00001623 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001624 // If the element was not a declaration, set it to be null.
1625
John McCalld88687f2011-01-07 01:49:06 +00001626 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1627 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001628 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001629 }
1630
Eric Christopher73fb3502011-10-13 21:45:18 +00001631 if (DI)
1632 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001633
John McCall990567c2011-07-27 01:07:15 +00001634 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001635 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001636 PopCleanupBlock();
1637
John McCallff8e1152010-07-23 21:56:41 +00001638 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001639}
1640
Mike Stump1eb44332009-09-09 15:08:12 +00001641void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001642 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001643}
1644
Mike Stump1eb44332009-09-09 15:08:12 +00001645void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001646 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1647}
1648
Chris Lattner10cac6f2008-11-15 21:26:17 +00001649void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001650 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001651 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001652}
1653
John McCall33e56f32011-09-10 06:18:15 +00001654/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001655/// primitive retain.
1656llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1657 llvm::Value *value) {
1658 return EmitARCRetain(type, value);
1659}
1660
1661namespace {
1662 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001663 CallObjCRelease(llvm::Value *object) : object(object) {}
1664 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001665
John McCallad346f42011-07-12 20:27:29 +00001666 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001667 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001668 }
1669 };
1670}
1671
John McCall33e56f32011-09-10 06:18:15 +00001672/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001673/// release at the end of the full-expression.
1674llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1675 llvm::Value *object) {
1676 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001677 // conditional.
1678 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001679 return object;
1680}
1681
1682llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1683 llvm::Value *value) {
1684 return EmitARCRetainAutorelease(type, value);
1685}
1686
1687
1688static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001689 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001690 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001691 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1692
John McCall260611a2012-06-20 06:18:46 +00001693 // If the target runtime doesn't naturally support ARC, emit weak
1694 // references to the runtime support library. We don't really
1695 // permit this to fail, but we need a particular relocation style.
1696 if (!CGM.getLangOpts().ObjCRuntime.hasARC())
John McCallf85e1932011-06-15 23:02:42 +00001697 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1698 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1699
1700 return fn;
1701}
1702
1703/// Perform an operation having the signature
1704/// i8* (i8*)
1705/// where a null input causes a no-op and returns null.
1706static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1707 llvm::Value *value,
1708 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001709 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001710 if (isa<llvm::ConstantPointerNull>(value)) return value;
1711
1712 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001713 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001714 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001715 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1716 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1717 }
1718
1719 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001720 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001721 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1722
1723 // Call the function.
1724 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1725 call->setDoesNotThrow();
1726
1727 // Cast the result back to the original type.
1728 return CGF.Builder.CreateBitCast(call, origType);
1729}
1730
1731/// Perform an operation having the following signature:
1732/// i8* (i8**)
1733static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1734 llvm::Value *addr,
1735 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001736 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001737 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001738 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001739 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001740 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1741 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1742 }
1743
1744 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001745 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001746 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1747
1748 // Call the function.
1749 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1750 call->setDoesNotThrow();
1751
1752 // Cast the result back to a dereference of the original type.
1753 llvm::Value *result = call;
1754 if (origType != CGF.Int8PtrPtrTy)
1755 result = CGF.Builder.CreateBitCast(result,
1756 cast<llvm::PointerType>(origType)->getElementType());
1757
1758 return result;
1759}
1760
1761/// Perform an operation having the following signature:
1762/// i8* (i8**, i8*)
1763static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1764 llvm::Value *addr,
1765 llvm::Value *value,
1766 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001767 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001768 bool ignored) {
1769 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1770 == value->getType());
1771
1772 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001773 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001774
Chris Lattner2acc6e32011-07-18 04:24:23 +00001775 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001776 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1777 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1778 }
1779
Chris Lattner2acc6e32011-07-18 04:24:23 +00001780 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001781
1782 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1783 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1784
1785 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1786 result->setDoesNotThrow();
1787
1788 if (ignored) return 0;
1789
1790 return CGF.Builder.CreateBitCast(result, origType);
1791}
1792
1793/// Perform an operation having the following signature:
1794/// void (i8**, i8**)
1795static void emitARCCopyOperation(CodeGenFunction &CGF,
1796 llvm::Value *dst,
1797 llvm::Value *src,
1798 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001799 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001800 assert(dst->getType() == src->getType());
1801
1802 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001803 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001804 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001805 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1806 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1807 }
1808
1809 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1810 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1811
1812 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1813 result->setDoesNotThrow();
1814}
1815
1816/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001817/// call i8* \@objc_retain(i8* %value)
1818/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001819llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1820 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001821 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001822 else
1823 return EmitARCRetainNonBlock(value);
1824}
1825
1826/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001827/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001828llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1829 return emitARCValueOperation(*this, value,
1830 CGM.getARCEntrypoints().objc_retain,
1831 "objc_retain");
1832}
1833
1834/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001835/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001836///
1837/// \param mandatory - If false, emit the call with metadata
1838/// indicating that it's okay for the optimizer to eliminate this call
1839/// if it can prove that the block never escapes except down the stack.
1840llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1841 bool mandatory) {
1842 llvm::Value *result
1843 = emitARCValueOperation(*this, value,
1844 CGM.getARCEntrypoints().objc_retainBlock,
1845 "objc_retainBlock");
1846
1847 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1848 // tell the optimizer that it doesn't need to do this copy if the
1849 // block doesn't escape, where being passed as an argument doesn't
1850 // count as escaping.
1851 if (!mandatory && isa<llvm::Instruction>(result)) {
1852 llvm::CallInst *call
1853 = cast<llvm::CallInst>(result->stripPointerCasts());
1854 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1855
1856 SmallVector<llvm::Value*,1> args;
1857 call->setMetadata("clang.arc.copy_on_escape",
1858 llvm::MDNode::get(Builder.getContext(), args));
1859 }
1860
1861 return result;
John McCallf85e1932011-06-15 23:02:42 +00001862}
1863
1864/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001865/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001866///
1867/// Yes, this function name is one character away from a different
1868/// call with completely different semantics.
1869llvm::Value *
1870CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1871 // Fetch the void(void) inline asm which marks that we're going to
1872 // retain the autoreleased return value.
1873 llvm::InlineAsm *&marker
1874 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1875 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001876 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001877 = CGM.getTargetCodeGenInfo()
1878 .getARCRetainAutoreleasedReturnValueMarker();
1879
1880 // If we have an empty assembly string, there's nothing to do.
1881 if (assembly.empty()) {
1882
1883 // Otherwise, at -O0, build an inline asm that we're going to call
1884 // in a moment.
1885 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1886 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001887 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001888
1889 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1890
1891 // If we're at -O1 and above, we don't want to litter the code
1892 // with this marker yet, so leave a breadcrumb for the ARC
1893 // optimizer to pick up.
1894 } else {
1895 llvm::NamedMDNode *metadata =
1896 CGM.getModule().getOrInsertNamedMetadata(
1897 "clang.arc.retainAutoreleasedReturnValueMarker");
1898 assert(metadata->getNumOperands() <= 1);
1899 if (metadata->getNumOperands() == 0) {
1900 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001901 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001902 }
1903 }
1904 }
1905
1906 // Call the marker asm if we made one, which we do only at -O0.
1907 if (marker) Builder.CreateCall(marker);
1908
1909 return emitARCValueOperation(*this, value,
1910 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1911 "objc_retainAutoreleasedReturnValue");
1912}
1913
1914/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001915/// call void \@objc_release(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001916void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1917 if (isa<llvm::ConstantPointerNull>(value)) return;
1918
1919 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1920 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001921 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001922 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001923 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1924 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1925 }
1926
1927 // Cast the argument to 'id'.
1928 value = Builder.CreateBitCast(value, Int8PtrTy);
1929
1930 // Call objc_release.
1931 llvm::CallInst *call = Builder.CreateCall(fn, value);
1932 call->setDoesNotThrow();
1933
1934 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001935 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001936 call->setMetadata("clang.imprecise_release",
1937 llvm::MDNode::get(Builder.getContext(), args));
1938 }
1939}
1940
1941/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001942/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001943llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1944 llvm::Value *value,
1945 bool ignored) {
1946 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1947 == value->getType());
1948
1949 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1950 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001951 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001952 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001953 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1954 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1955 }
1956
1957 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1958 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1959
1960 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1961
1962 if (ignored) return 0;
1963 return value;
1964}
1965
1966/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001967/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001968/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001969llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001970 llvm::Value *newValue,
1971 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001972 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001973 bool isBlock = type->isBlockPointerType();
1974
1975 // Use a store barrier at -O0 unless this is a block type or the
1976 // lvalue is inadequately aligned.
1977 if (shouldUseFusedARCCalls() &&
1978 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001979 (dst.getAlignment().isZero() ||
1980 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001981 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1982 }
1983
1984 // Otherwise, split it out.
1985
1986 // Retain the new value.
1987 newValue = EmitARCRetain(type, newValue);
1988
1989 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001990 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001991
1992 // Store. We do this before the release so that any deallocs won't
1993 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001994 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001995
1996 // Finally, release the old value.
1997 EmitARCRelease(oldValue, /*precise*/ false);
1998
1999 return newValue;
2000}
2001
2002/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002003/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002004llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2005 return emitARCValueOperation(*this, value,
2006 CGM.getARCEntrypoints().objc_autorelease,
2007 "objc_autorelease");
2008}
2009
2010/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002011/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002012llvm::Value *
2013CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2014 return emitARCValueOperation(*this, value,
2015 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2016 "objc_autoreleaseReturnValue");
2017}
2018
2019/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002020/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002021llvm::Value *
2022CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2023 return emitARCValueOperation(*this, value,
2024 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2025 "objc_retainAutoreleaseReturnValue");
2026}
2027
2028/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002029/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002030/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002031/// %retain = call i8* \@objc_retainBlock(i8* %value)
2032/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002033llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2034 llvm::Value *value) {
2035 if (!type->isBlockPointerType())
2036 return EmitARCRetainAutoreleaseNonBlock(value);
2037
2038 if (isa<llvm::ConstantPointerNull>(value)) return value;
2039
Chris Lattner2acc6e32011-07-18 04:24:23 +00002040 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002041 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002042 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002043 value = EmitARCAutorelease(value);
2044 return Builder.CreateBitCast(value, origType);
2045}
2046
2047/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002048/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002049llvm::Value *
2050CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2051 return emitARCValueOperation(*this, value,
2052 CGM.getARCEntrypoints().objc_retainAutorelease,
2053 "objc_retainAutorelease");
2054}
2055
James Dennett9d96e9c2012-06-22 05:41:30 +00002056/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002057/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2058llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2059 return emitARCLoadOperation(*this, addr,
2060 CGM.getARCEntrypoints().objc_loadWeak,
2061 "objc_loadWeak");
2062}
2063
James Dennett9d96e9c2012-06-22 05:41:30 +00002064/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002065llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2066 return emitARCLoadOperation(*this, addr,
2067 CGM.getARCEntrypoints().objc_loadWeakRetained,
2068 "objc_loadWeakRetained");
2069}
2070
James Dennett9d96e9c2012-06-22 05:41:30 +00002071/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002072/// Returns %value.
2073llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2074 llvm::Value *value,
2075 bool ignored) {
2076 return emitARCStoreOperation(*this, addr, value,
2077 CGM.getARCEntrypoints().objc_storeWeak,
2078 "objc_storeWeak", ignored);
2079}
2080
James Dennett9d96e9c2012-06-22 05:41:30 +00002081/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002082/// Returns %value. %addr is known to not have a current weak entry.
2083/// Essentially equivalent to:
2084/// *addr = nil; objc_storeWeak(addr, value);
2085void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2086 // If we're initializing to null, just write null to memory; no need
2087 // to get the runtime involved. But don't do this if optimization
2088 // is enabled, because accounting for this would make the optimizer
2089 // much more complicated.
2090 if (isa<llvm::ConstantPointerNull>(value) &&
2091 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2092 Builder.CreateStore(value, addr);
2093 return;
2094 }
2095
2096 emitARCStoreOperation(*this, addr, value,
2097 CGM.getARCEntrypoints().objc_initWeak,
2098 "objc_initWeak", /*ignored*/ true);
2099}
2100
James Dennett9d96e9c2012-06-22 05:41:30 +00002101/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002102/// Essentially objc_storeWeak(addr, nil).
2103void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2104 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2105 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002106 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002107 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002108 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2109 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2110 }
2111
2112 // Cast the argument to 'id*'.
2113 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2114
2115 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2116 call->setDoesNotThrow();
2117}
2118
James Dennett9d96e9c2012-06-22 05:41:30 +00002119/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002120/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2121/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2122void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2123 emitARCCopyOperation(*this, dst, src,
2124 CGM.getARCEntrypoints().objc_moveWeak,
2125 "objc_moveWeak");
2126}
2127
James Dennett9d96e9c2012-06-22 05:41:30 +00002128/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002129/// Disregards the current value in %dest. Essentially
2130/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2131void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2132 emitARCCopyOperation(*this, dst, src,
2133 CGM.getARCEntrypoints().objc_copyWeak,
2134 "objc_copyWeak");
2135}
2136
2137/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002138/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002139llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2140 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2141 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002142 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002143 llvm::FunctionType::get(Int8PtrTy, false);
2144 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2145 }
2146
2147 llvm::CallInst *call = Builder.CreateCall(fn);
2148 call->setDoesNotThrow();
2149
2150 return call;
2151}
2152
2153/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002154/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002155void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2156 assert(value->getType() == Int8PtrTy);
2157
2158 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2159 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002160 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002161 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002162 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2163
2164 // We don't want to use a weak import here; instead we should not
2165 // fall into this path.
2166 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2167 }
2168
2169 llvm::CallInst *call = Builder.CreateCall(fn, value);
2170 call->setDoesNotThrow();
2171}
2172
2173/// Produce the code to do an MRR version objc_autoreleasepool_push.
2174/// Which is: [[NSAutoreleasePool alloc] init];
2175/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2176/// init is declared as: - (id) init; in its NSObject super class.
2177///
2178llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2179 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2180 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2181 // [NSAutoreleasePool alloc]
2182 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2183 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2184 CallArgList Args;
2185 RValue AllocRV =
2186 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2187 getContext().getObjCIdType(),
2188 AllocSel, Receiver, Args);
2189
2190 // [Receiver init]
2191 Receiver = AllocRV.getScalarVal();
2192 II = &CGM.getContext().Idents.get("init");
2193 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2194 RValue InitRV =
2195 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2196 getContext().getObjCIdType(),
2197 InitSel, Receiver, Args);
2198 return InitRV.getScalarVal();
2199}
2200
2201/// Produce the code to do a primitive release.
2202/// [tmp drain];
2203void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2204 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2205 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2206 CallArgList Args;
2207 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2208 getContext().VoidTy, DrainSel, Arg, Args);
2209}
2210
John McCallbdc4d802011-07-09 01:37:26 +00002211void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2212 llvm::Value *addr,
2213 QualType type) {
2214 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2215 CGF.EmitARCRelease(ptr, /*precise*/ true);
2216}
2217
2218void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2219 llvm::Value *addr,
2220 QualType type) {
2221 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2222 CGF.EmitARCRelease(ptr, /*precise*/ false);
2223}
2224
2225void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2226 llvm::Value *addr,
2227 QualType type) {
2228 CGF.EmitARCDestroyWeak(addr);
2229}
2230
John McCallf85e1932011-06-15 23:02:42 +00002231namespace {
John McCallf85e1932011-06-15 23:02:42 +00002232 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2233 llvm::Value *Token;
2234
2235 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2236
John McCallad346f42011-07-12 20:27:29 +00002237 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002238 CGF.EmitObjCAutoreleasePoolPop(Token);
2239 }
2240 };
2241 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2242 llvm::Value *Token;
2243
2244 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2245
John McCallad346f42011-07-12 20:27:29 +00002246 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002247 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2248 }
2249 };
2250}
2251
2252void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002253 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002254 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2255 else
2256 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2257}
2258
John McCallf85e1932011-06-15 23:02:42 +00002259static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2260 LValue lvalue,
2261 QualType type) {
2262 switch (type.getObjCLifetime()) {
2263 case Qualifiers::OCL_None:
2264 case Qualifiers::OCL_ExplicitNone:
2265 case Qualifiers::OCL_Strong:
2266 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002267 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002268 false);
2269
2270 case Qualifiers::OCL_Weak:
2271 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2272 true);
2273 }
2274
2275 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002276}
2277
2278static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2279 const Expr *e) {
2280 e = e->IgnoreParens();
2281 QualType type = e->getType();
2282
John McCall21480112011-08-30 00:57:29 +00002283 // If we're loading retained from a __strong xvalue, we can avoid
2284 // an extra retain/release pair by zeroing out the source of this
2285 // "move" operation.
2286 if (e->isXValue() &&
2287 !type.isConstQualified() &&
2288 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2289 // Emit the lvalue.
2290 LValue lv = CGF.EmitLValue(e);
2291
2292 // Load the object pointer.
2293 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2294
2295 // Set the source pointer to NULL.
2296 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2297
2298 return TryEmitResult(result, true);
2299 }
2300
John McCallf85e1932011-06-15 23:02:42 +00002301 // As a very special optimization, in ARC++, if the l-value is the
2302 // result of a non-volatile assignment, do a simple retain of the
2303 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002304 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002305 !type.isVolatileQualified() &&
2306 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2307 isa<BinaryOperator>(e) &&
2308 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2309 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2310
2311 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2312}
2313
2314static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2315 llvm::Value *value);
2316
2317/// Given that the given expression is some sort of call (which does
2318/// not return retained), emit a retain following it.
2319static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2320 llvm::Value *value = CGF.EmitScalarExpr(e);
2321 return emitARCRetainAfterCall(CGF, value);
2322}
2323
2324static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2325 llvm::Value *value) {
2326 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2327 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2328
2329 // Place the retain immediately following the call.
2330 CGF.Builder.SetInsertPoint(call->getParent(),
2331 ++llvm::BasicBlock::iterator(call));
2332 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2333
2334 CGF.Builder.restoreIP(ip);
2335 return value;
2336 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2337 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2338
2339 // Place the retain at the beginning of the normal destination block.
2340 llvm::BasicBlock *BB = invoke->getNormalDest();
2341 CGF.Builder.SetInsertPoint(BB, BB->begin());
2342 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2343
2344 CGF.Builder.restoreIP(ip);
2345 return value;
2346
2347 // Bitcasts can arise because of related-result returns. Rewrite
2348 // the operand.
2349 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2350 llvm::Value *operand = bitcast->getOperand(0);
2351 operand = emitARCRetainAfterCall(CGF, operand);
2352 bitcast->setOperand(0, operand);
2353 return bitcast;
2354
2355 // Generic fall-back case.
2356 } else {
2357 // Retain using the non-block variant: we never need to do a copy
2358 // of a block that's been returned to us.
2359 return CGF.EmitARCRetainNonBlock(value);
2360 }
2361}
2362
John McCalldc05b112011-09-10 01:16:55 +00002363/// Determine whether it might be important to emit a separate
2364/// objc_retain_block on the result of the given expression, or
2365/// whether it's okay to just emit it in a +1 context.
2366static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2367 assert(e->getType()->isBlockPointerType());
2368 e = e->IgnoreParens();
2369
2370 // For future goodness, emit block expressions directly in +1
2371 // contexts if we can.
2372 if (isa<BlockExpr>(e))
2373 return false;
2374
2375 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2376 switch (cast->getCastKind()) {
2377 // Emitting these operations in +1 contexts is goodness.
2378 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002379 case CK_ARCReclaimReturnedObject:
2380 case CK_ARCConsumeObject:
2381 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002382 return false;
2383
2384 // These operations preserve a block type.
2385 case CK_NoOp:
2386 case CK_BitCast:
2387 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2388
2389 // These operations are known to be bad (or haven't been considered).
2390 case CK_AnyPointerToBlockPointerCast:
2391 default:
2392 return true;
2393 }
2394 }
2395
2396 return true;
2397}
2398
John McCall4b9c2d22011-11-06 09:01:30 +00002399/// Try to emit a PseudoObjectExpr at +1.
2400///
2401/// This massively duplicates emitPseudoObjectRValue.
2402static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2403 const PseudoObjectExpr *E) {
2404 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2405
2406 // Find the result expression.
2407 const Expr *resultExpr = E->getResultExpr();
2408 assert(resultExpr);
2409 TryEmitResult result;
2410
2411 for (PseudoObjectExpr::const_semantics_iterator
2412 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2413 const Expr *semantic = *i;
2414
2415 // If this semantic expression is an opaque value, bind it
2416 // to the result of its source expression.
2417 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2418 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2419 OVMA opaqueData;
2420
2421 // If this semantic is the result of the pseudo-object
2422 // expression, try to evaluate the source as +1.
2423 if (ov == resultExpr) {
2424 assert(!OVMA::shouldBindAsLValue(ov));
2425 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2426 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2427
2428 // Otherwise, just bind it.
2429 } else {
2430 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2431 }
2432 opaques.push_back(opaqueData);
2433
2434 // Otherwise, if the expression is the result, evaluate it
2435 // and remember the result.
2436 } else if (semantic == resultExpr) {
2437 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2438
2439 // Otherwise, evaluate the expression in an ignored context.
2440 } else {
2441 CGF.EmitIgnoredExpr(semantic);
2442 }
2443 }
2444
2445 // Unbind all the opaques now.
2446 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2447 opaques[i].unbind(CGF);
2448
2449 return result;
2450}
2451
John McCallf85e1932011-06-15 23:02:42 +00002452static TryEmitResult
2453tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002454 // Look through cleanups.
2455 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002456 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002457 CodeGenFunction::RunCleanupsScope scope(CGF);
2458 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2459 }
2460
John McCallf85e1932011-06-15 23:02:42 +00002461 // The desired result type, if it differs from the type of the
2462 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002463 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002464
2465 while (true) {
2466 e = e->IgnoreParens();
2467
2468 // There's a break at the end of this if-chain; anything
2469 // that wants to keep looping has to explicitly continue.
2470 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2471 switch (ce->getCastKind()) {
2472 // No-op casts don't change the type, so we just ignore them.
2473 case CK_NoOp:
2474 e = ce->getSubExpr();
2475 continue;
2476
2477 case CK_LValueToRValue: {
2478 TryEmitResult loadResult
2479 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2480 if (resultType) {
2481 llvm::Value *value = loadResult.getPointer();
2482 value = CGF.Builder.CreateBitCast(value, resultType);
2483 loadResult.setPointer(value);
2484 }
2485 return loadResult;
2486 }
2487
2488 // These casts can change the type, so remember that and
2489 // soldier on. We only need to remember the outermost such
2490 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002491 case CK_CPointerToObjCPointerCast:
2492 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002493 case CK_AnyPointerToBlockPointerCast:
2494 case CK_BitCast:
2495 if (!resultType)
2496 resultType = CGF.ConvertType(ce->getType());
2497 e = ce->getSubExpr();
2498 assert(e->getType()->hasPointerRepresentation());
2499 continue;
2500
2501 // For consumptions, just emit the subexpression and thus elide
2502 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002503 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002504 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2505 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2506 return TryEmitResult(result, true);
2507 }
2508
John McCalldc05b112011-09-10 01:16:55 +00002509 // Block extends are net +0. Naively, we could just recurse on
2510 // the subexpression, but actually we need to ensure that the
2511 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002512 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002513 llvm::Value *result; // will be a +0 value
2514
2515 // If we can't safely assume the sub-expression will produce a
2516 // block-copied value, emit the sub-expression at +0.
2517 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2518 result = CGF.EmitScalarExpr(ce->getSubExpr());
2519
2520 // Otherwise, try to emit the sub-expression at +1 recursively.
2521 } else {
2522 TryEmitResult subresult
2523 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2524 result = subresult.getPointer();
2525
2526 // If that produced a retained value, just use that,
2527 // possibly casting down.
2528 if (subresult.getInt()) {
2529 if (resultType)
2530 result = CGF.Builder.CreateBitCast(result, resultType);
2531 return TryEmitResult(result, true);
2532 }
2533
2534 // Otherwise it's +0.
2535 }
2536
2537 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002538 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002539 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2540 return TryEmitResult(result, true);
2541 }
2542
John McCall7e5e5f42011-07-07 06:58:02 +00002543 // For reclaims, emit the subexpression as a retained call and
2544 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002545 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002546 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2547 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2548 return TryEmitResult(result, true);
2549 }
2550
John McCallf85e1932011-06-15 23:02:42 +00002551 default:
2552 break;
2553 }
2554
2555 // Skip __extension__.
2556 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2557 if (op->getOpcode() == UO_Extension) {
2558 e = op->getSubExpr();
2559 continue;
2560 }
2561
2562 // For calls and message sends, use the retained-call logic.
2563 // Delegate inits are a special case in that they're the only
2564 // returns-retained expression that *isn't* surrounded by
2565 // a consume.
2566 } else if (isa<CallExpr>(e) ||
2567 (isa<ObjCMessageExpr>(e) &&
2568 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2569 llvm::Value *result = emitARCRetainCall(CGF, e);
2570 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2571 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002572
2573 // Look through pseudo-object expressions.
2574 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2575 TryEmitResult result
2576 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2577 if (resultType) {
2578 llvm::Value *value = result.getPointer();
2579 value = CGF.Builder.CreateBitCast(value, resultType);
2580 result.setPointer(value);
2581 }
2582 return result;
John McCallf85e1932011-06-15 23:02:42 +00002583 }
2584
2585 // Conservatively halt the search at any other expression kind.
2586 break;
2587 }
2588
2589 // We didn't find an obvious production, so emit what we've got and
2590 // tell the caller that we didn't manage to retain.
2591 llvm::Value *result = CGF.EmitScalarExpr(e);
2592 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2593 return TryEmitResult(result, false);
2594}
2595
2596static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2597 LValue lvalue,
2598 QualType type) {
2599 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2600 llvm::Value *value = result.getPointer();
2601 if (!result.getInt())
2602 value = CGF.EmitARCRetain(type, value);
2603 return value;
2604}
2605
2606/// EmitARCRetainScalarExpr - Semantically equivalent to
2607/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2608/// best-effort attempt to peephole expressions that naturally produce
2609/// retained objects.
2610llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2611 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2612 llvm::Value *value = result.getPointer();
2613 if (!result.getInt())
2614 value = EmitARCRetain(e->getType(), value);
2615 return value;
2616}
2617
2618llvm::Value *
2619CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2620 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2621 llvm::Value *value = result.getPointer();
2622 if (result.getInt())
2623 value = EmitARCAutorelease(value);
2624 else
2625 value = EmitARCRetainAutorelease(e->getType(), value);
2626 return value;
2627}
2628
John McCall348f16f2011-10-04 06:23:45 +00002629llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2630 llvm::Value *result;
2631 bool doRetain;
2632
2633 if (shouldEmitSeparateBlockRetain(e)) {
2634 result = EmitScalarExpr(e);
2635 doRetain = true;
2636 } else {
2637 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2638 result = subresult.getPointer();
2639 doRetain = !subresult.getInt();
2640 }
2641
2642 if (doRetain)
2643 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2644 return EmitObjCConsumeObject(e->getType(), result);
2645}
2646
John McCall2b014d62011-10-01 10:32:24 +00002647llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2648 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002649 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002650 // Do so before running any cleanups for the full-expression.
2651 // tryEmitARCRetainScalarExpr does make an effort to do things
2652 // inside cleanups, but there are crazy cases like
2653 // @throw A().foo;
2654 // where a full retain+autorelease is required and would
2655 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002656 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2657 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002658 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002659 }
John McCall2b014d62011-10-01 10:32:24 +00002660
John McCall1a343eb2011-11-10 08:15:53 +00002661 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002662 return EmitARCRetainAutoreleaseScalarExpr(expr);
2663 }
2664
2665 // Otherwise, use the normal scalar-expression emission. The
2666 // exception machinery doesn't do anything special with the
2667 // exception like retaining it, so there's no safety associated with
2668 // only running cleanups after the throw has started, and when it
2669 // matters it tends to be substantially inferior code.
2670 return EmitScalarExpr(expr);
2671}
2672
John McCallf85e1932011-06-15 23:02:42 +00002673std::pair<LValue,llvm::Value*>
2674CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2675 bool ignored) {
2676 // Evaluate the RHS first.
2677 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2678 llvm::Value *value = result.getPointer();
2679
John McCallfb720812011-07-28 07:23:35 +00002680 bool hasImmediateRetain = result.getInt();
2681
2682 // If we didn't emit a retained object, and the l-value is of block
2683 // type, then we need to emit the block-retain immediately in case
2684 // it invalidates the l-value.
2685 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002686 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002687 hasImmediateRetain = true;
2688 }
2689
John McCallf85e1932011-06-15 23:02:42 +00002690 LValue lvalue = EmitLValue(e->getLHS());
2691
2692 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002693 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002694 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002695 EmitLoadOfScalar(lvalue);
2696 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002697 EmitARCRelease(oldValue, /*precise*/ false);
2698 } else {
John McCall545d9962011-06-25 02:11:03 +00002699 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002700 }
2701
2702 return std::pair<LValue,llvm::Value*>(lvalue, value);
2703}
2704
2705std::pair<LValue,llvm::Value*>
2706CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2707 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2708 LValue lvalue = EmitLValue(e->getLHS());
2709
Eli Friedman6da2c712011-12-03 04:14:32 +00002710 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002711
2712 return std::pair<LValue,llvm::Value*>(lvalue, value);
2713}
2714
2715void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002716 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002717 const Stmt *subStmt = ARPS.getSubStmt();
2718 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2719
2720 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002721 if (DI)
2722 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002723
2724 // Keep track of the current cleanup stack depth.
2725 RunCleanupsScope Scope(*this);
John McCall260611a2012-06-20 06:18:46 +00002726 if (CGM.getLangOpts().ObjCRuntime.hasARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002727 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2728 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2729 } else {
2730 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2731 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2732 }
2733
2734 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2735 E = S.body_end(); I != E; ++I)
2736 EmitStmt(*I);
2737
Eric Christopher73fb3502011-10-13 21:45:18 +00002738 if (DI)
2739 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002740}
John McCall0c24c802011-06-24 23:21:27 +00002741
2742/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2743/// make sure it survives garbage collection until this point.
2744void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2745 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002746 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002747 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002748 llvm::Value *extender
2749 = llvm::InlineAsm::get(extenderType,
2750 /* assembly */ "",
2751 /* constraints */ "r",
2752 /* side effects */ true);
2753
2754 object = Builder.CreateBitCast(object, VoidPtrTy);
2755 Builder.CreateCall(extender, object)->setDoesNotThrow();
2756}
2757
John McCall260611a2012-06-20 06:18:46 +00002758static bool hasAtomicCopyHelperAPI(const ObjCRuntime &runtime) {
2759 // For now, only NeXT has these APIs.
2760 return runtime.isNeXTFamily();
2761}
2762
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002763/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002764/// non-trivial copy assignment function, produce following helper function.
2765/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2766///
2767llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002768CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2769 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002770 // FIXME. This api is for NeXt runtime only for now.
John McCall260611a2012-06-20 06:18:46 +00002771 if (!getLangOpts().CPlusPlus ||
2772 !hasAtomicCopyHelperAPI(getLangOpts().ObjCRuntime))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002773 return 0;
2774 QualType Ty = PID->getPropertyIvarDecl()->getType();
2775 if (!Ty->isRecordType())
2776 return 0;
2777 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002778 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002779 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002780 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002781 if (hasTrivialSetExpr(PID))
2782 return 0;
2783 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2784 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2785 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002786
2787 ASTContext &C = getContext();
2788 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002789 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002790 FunctionDecl *FD = FunctionDecl::Create(C,
2791 C.getTranslationUnitDecl(),
2792 SourceLocation(),
2793 SourceLocation(), II, C.VoidTy, 0,
2794 SC_Static,
2795 SC_None,
2796 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002797 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002798
2799 QualType DestTy = C.getPointerType(Ty);
2800 QualType SrcTy = Ty;
2801 SrcTy.addConst();
2802 SrcTy = C.getPointerType(SrcTy);
2803
2804 FunctionArgList args;
2805 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2806 args.push_back(&dstDecl);
2807 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2808 args.push_back(&srcDecl);
2809
2810 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002811 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2812 FunctionType::ExtInfo(),
2813 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002814
John McCallde5d3c72012-02-17 03:33:10 +00002815 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002816
2817 llvm::Function *Fn =
2818 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002819 "__assign_helper_atomic_property_",
2820 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002821
2822 if (CGM.getModuleDebugInfo())
2823 DebugInfo = CGM.getModuleDebugInfo();
2824
2825
2826 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2827
John McCallf4b88a42012-03-10 09:33:50 +00002828 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2829 VK_RValue, SourceLocation());
2830 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2831 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002832
John McCallf4b88a42012-03-10 09:33:50 +00002833 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2834 VK_RValue, SourceLocation());
2835 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2836 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002837
John McCallf4b88a42012-03-10 09:33:50 +00002838 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002839 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002840 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2841 Args, 2, DestTy->getPointeeType(),
2842 VK_LValue, SourceLocation());
2843
2844 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002845
2846 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002847 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002848 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002849 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002850}
2851
2852llvm::Constant *
2853CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2854 const ObjCPropertyImplDecl *PID) {
2855 // FIXME. This api is for NeXt runtime only for now.
John McCall260611a2012-06-20 06:18:46 +00002856 if (!getLangOpts().CPlusPlus ||
2857 !hasAtomicCopyHelperAPI(getLangOpts().ObjCRuntime))
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002858 return 0;
2859 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2860 QualType Ty = PD->getType();
2861 if (!Ty->isRecordType())
2862 return 0;
2863 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2864 return 0;
2865 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002866
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002867 if (hasTrivialGetExpr(PID))
2868 return 0;
2869 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2870 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2871 return HelperFn;
2872
2873
2874 ASTContext &C = getContext();
2875 IdentifierInfo *II
2876 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2877 FunctionDecl *FD = FunctionDecl::Create(C,
2878 C.getTranslationUnitDecl(),
2879 SourceLocation(),
2880 SourceLocation(), II, C.VoidTy, 0,
2881 SC_Static,
2882 SC_None,
2883 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002884 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002885
2886 QualType DestTy = C.getPointerType(Ty);
2887 QualType SrcTy = Ty;
2888 SrcTy.addConst();
2889 SrcTy = C.getPointerType(SrcTy);
2890
2891 FunctionArgList args;
2892 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2893 args.push_back(&dstDecl);
2894 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2895 args.push_back(&srcDecl);
2896
2897 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002898 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2899 FunctionType::ExtInfo(),
2900 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002901
John McCallde5d3c72012-02-17 03:33:10 +00002902 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002903
2904 llvm::Function *Fn =
2905 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2906 "__copy_helper_atomic_property_", &CGM.getModule());
2907
2908 if (CGM.getModuleDebugInfo())
2909 DebugInfo = CGM.getModuleDebugInfo();
2910
2911
2912 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2913
John McCallf4b88a42012-03-10 09:33:50 +00002914 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002915 VK_RValue, SourceLocation());
2916
John McCallf4b88a42012-03-10 09:33:50 +00002917 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2918 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002919
2920 CXXConstructExpr *CXXConstExpr =
2921 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2922
2923 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002924 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002925 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2926 ++A;
2927
2928 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2929 A != AEnd; ++A)
2930 ConstructorArgs.push_back(*A);
2931
2932 CXXConstructExpr *TheCXXConstructExpr =
2933 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2934 CXXConstExpr->getConstructor(),
2935 CXXConstExpr->isElidable(),
2936 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002937 CXXConstExpr->hadMultipleCandidates(),
2938 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002939 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00002940 CXXConstExpr->getConstructionKind(),
2941 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002942
John McCallf4b88a42012-03-10 09:33:50 +00002943 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2944 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002945
John McCallf4b88a42012-03-10 09:33:50 +00002946 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00002947 CharUnits Alignment
2948 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002949 EmitAggExpr(TheCXXConstructExpr,
2950 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2951 AggValueSlot::IsDestructed,
2952 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00002953 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002954
2955 FinishFunction();
2956 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2957 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2958 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002959}
2960
Eli Friedmancae40c42012-02-28 01:08:45 +00002961llvm::Value *
2962CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2963 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002964 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2965 Selector CopySelector =
2966 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002967 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2968 Selector AutoreleaseSelector =
2969 getContext().Selectors.getNullarySelector(AutoreleaseID);
2970
2971 // Emit calls to retain/autorelease.
2972 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2973 llvm::Value *Val = Block;
2974 RValue Result;
2975 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002976 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002977 Val, CallArgList(), 0, 0);
2978 Val = Result.getScalarVal();
2979 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2980 Ty, AutoreleaseSelector,
2981 Val, CallArgList(), 0, 0);
2982 Val = Result.getScalarVal();
2983 return Val;
2984}
2985
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002986
Ted Kremenek2979ec72008-04-09 15:51:31 +00002987CGObjCRuntime::~CGObjCRuntime() {}