blob: cea97317889cf0b6566f3a1333e2108824055fff [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"
Micah Villmow25a6a842012-10-08 16:25:52 +000024#include "llvm/DataLayout.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 McCall0f3d0972012-07-07 06:41:13 +0000510 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(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
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000583/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000584PropertyImplStrategy::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 McCalld64c2eb2012-08-20 23:36:59 +0000616 // Using standard expression emission for the setter is only
617 // acceptable if the ivar is __strong, which won't be true if
618 // the property is annotated with __attribute__((NSObject)).
619 // TODO: falling all the way back to objc_setProperty here is
620 // just laziness, though; we could still use objc_storeStrong
621 // if we hacked it right.
622 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
623 Kind = Expression;
624 else
625 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000626 return;
627
628 // Otherwise, we need to at least use setProperty. However, if
629 // the property isn't atomic, we can use normal expression
630 // emission for the getter.
631 } else if (!IsAtomic) {
632 Kind = SetPropertyAndExpressionGet;
633 return;
634
635 // Otherwise, we have to use both setProperty and getProperty.
636 } else {
637 Kind = GetSetProperty;
638 return;
639 }
640 }
641
642 // If we're not atomic, just use expression accesses.
643 if (!IsAtomic) {
644 Kind = Expression;
645 return;
646 }
647
John McCall5889c602011-09-13 05:36:29 +0000648 // Properties on bitfield ivars need to be emitted using expression
649 // accesses even if they're nominally atomic.
650 if (ivar->isBitField()) {
651 Kind = Expression;
652 return;
653 }
654
John McCall1e1f4872011-09-13 03:34:09 +0000655 // GC-qualified or ARC-qualified ivars need to be emitted as
656 // expressions. This actually works out to being atomic anyway,
657 // except for ARC __strong, but that should trigger the above code.
658 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000659 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000660 CGM.getContext().getObjCGCAttrKind(ivarType))) {
661 Kind = Expression;
662 return;
663 }
664
665 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000666 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000667 if (const RecordType *recordType = ivarType->getAs<RecordType>())
668 HasStrong = recordType->getDecl()->hasObjectMember();
669
670 // We can never access structs with object members with a native
671 // access, because we need to use write barriers. This is what
672 // objc_copyStruct is for.
673 if (HasStrong) {
674 Kind = CopyStruct;
675 return;
676 }
677
678 // Otherwise, this is target-dependent and based on the size and
679 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000680
681 // If the size of the ivar is not a power of two, give up. We don't
682 // want to get into the business of doing compare-and-swaps.
683 if (!IvarSize.isPowerOfTwo()) {
684 Kind = CopyStruct;
685 return;
686 }
687
John McCall1e1f4872011-09-13 03:34:09 +0000688 llvm::Triple::ArchType arch =
689 CGM.getContext().getTargetInfo().getTriple().getArch();
690
691 // Most architectures require memory to fit within a single cache
692 // line, so the alignment has to be at least the size of the access.
693 // Otherwise we have to grab a lock.
694 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
695 Kind = CopyStruct;
696 return;
697 }
698
699 // If the ivar's size exceeds the architecture's maximum atomic
700 // access size, we have to use CopyStruct.
701 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
702 Kind = CopyStruct;
703 return;
704 }
705
706 // Otherwise, we can use native loads and stores.
707 Kind = Native;
708}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000709
James Dennett2ee5ba32012-06-15 22:10:14 +0000710/// \brief Generate an Objective-C property getter function.
711///
712/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000713/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000714void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
715 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000716 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000717 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000718 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
719 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
720 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000721 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000723 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000724
725 FinishFunction();
726}
727
John McCall6c11f0b2011-09-13 06:00:03 +0000728static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
729 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000730 if (!getter) return true;
731
732 // Sema only makes only of these when the ivar has a C++ class type,
733 // so the form is pretty constrained.
734
John McCall6c11f0b2011-09-13 06:00:03 +0000735 // If the property has a reference type, we might just be binding a
736 // reference, in which case the result will be a gl-value. We should
737 // treat this as a non-trivial operation.
738 if (getter->isGLValue())
739 return false;
740
John McCall1e1f4872011-09-13 03:34:09 +0000741 // If we selected a trivial copy-constructor, we're okay.
742 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
743 return (construct->getConstructor()->isTrivial());
744
745 // The constructor might require cleanups (in which case it's never
746 // trivial).
747 assert(isa<ExprWithCleanups>(getter));
748 return false;
749}
750
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000751/// emitCPPObjectAtomicGetterCall - Call the runtime function to
752/// copy the ivar into the resturn slot.
753static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
754 llvm::Value *returnAddr,
755 ObjCIvarDecl *ivar,
756 llvm::Constant *AtomicHelperFn) {
757 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
758 // AtomicHelperFn);
759 CallArgList args;
760
761 // The 1st argument is the return Slot.
762 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
763
764 // The 2nd argument is the address of the ivar.
765 llvm::Value *ivarAddr =
766 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
767 CGF.LoadObjCSelf(), ivar, 0).getAddress();
768 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
769 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
770
771 // Third argument is the helper function.
772 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
773
774 llvm::Value *copyCppAtomicObjectFn =
775 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000776 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
777 args,
778 FunctionType::ExtInfo(),
779 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000780 copyCppAtomicObjectFn, ReturnValueSlot(), args);
781}
782
John McCall1e1f4872011-09-13 03:34:09 +0000783void
784CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000785 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000786 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000787 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000788 // If there's a non-trivial 'get' expression, we just have to emit that.
789 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000790 if (!AtomicHelperFn) {
791 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
792 /*nrvo*/ 0);
793 EmitReturnStmt(ret);
794 }
795 else {
796 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
797 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
798 ivar, AtomicHelperFn);
799 }
John McCall1e1f4872011-09-13 03:34:09 +0000800 return;
801 }
802
803 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
804 QualType propType = prop->getType();
805 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
806
807 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
808
809 // Pick an implementation strategy.
810 PropertyImplStrategy strategy(CGM, propImpl);
811 switch (strategy.getKind()) {
812 case PropertyImplStrategy::Native: {
813 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
814
815 // Currently, all atomic accesses have to be through integer
816 // types, so there's no point in trying to pick a prettier type.
817 llvm::Type *bitcastType =
818 llvm::Type::getIntNTy(getLLVMContext(),
819 getContext().toBits(strategy.getIvarSize()));
820 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
821
822 // Perform an atomic load. This does not impose ordering constraints.
823 llvm::Value *ivarAddr = LV.getAddress();
824 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
825 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
826 load->setAlignment(strategy.getIvarAlignment().getQuantity());
827 load->setAtomic(llvm::Unordered);
828
829 // Store that value into the return address. Doing this with a
830 // bitcast is likely to produce some pretty ugly IR, but it's not
831 // the *most* terrible thing in the world.
832 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
833
834 // Make sure we don't do an autorelease.
835 AutoreleaseResult = false;
836 return;
837 }
838
839 case PropertyImplStrategy::GetSetProperty: {
840 llvm::Value *getPropertyFn =
841 CGM.getObjCRuntime().GetPropertyGetFunction();
842 if (!getPropertyFn) {
843 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000844 return;
845 }
846
847 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
848 // FIXME: Can't this be simpler? This might even be worse than the
849 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000850 llvm::Value *cmd =
851 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
852 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
853 llvm::Value *ivarOffset =
854 EmitIvarOffset(classImpl->getClassInterface(), ivar);
855
856 CallArgList args;
857 args.add(RValue::get(self), getContext().getObjCIdType());
858 args.add(RValue::get(cmd), getContext().getObjCSelType());
859 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000860 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
861 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000862
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000863 // FIXME: We shouldn't need to get the function info here, the
864 // runtime already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +0000865 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
866 FunctionType::ExtInfo(),
867 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000868 getPropertyFn, ReturnValueSlot(), args);
869
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000870 // We need to fix the type here. Ivars with copy & retain are
871 // always objects so we don't need to worry about complex or
872 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000873 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian52c18b02012-04-26 21:33:14 +0000874 getTypes().ConvertType(getterMethod->getResultType())));
John McCall1e1f4872011-09-13 03:34:09 +0000875
876 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000877
878 // objc_getProperty does an autorelease, so we should suppress ours.
879 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000880
John McCall1e1f4872011-09-13 03:34:09 +0000881 return;
882 }
883
884 case PropertyImplStrategy::CopyStruct:
885 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
886 strategy.hasStrongMember());
887 return;
888
889 case PropertyImplStrategy::Expression:
890 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
891 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
892
893 QualType ivarType = ivar->getType();
894 if (ivarType->isAnyComplexType()) {
895 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
896 LV.isVolatileQualified());
897 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
898 } else if (hasAggregateLLVMType(ivarType)) {
899 // The return value slot is guaranteed to not be aliased, but
900 // that's not necessarily the same as "on the stack", so
901 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000902 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000903 } else {
John McCallba3dd902011-07-22 05:23:13 +0000904 llvm::Value *value;
905 if (propType->isReferenceType()) {
906 value = LV.getAddress();
907 } else {
908 // We want to load and autoreleaseReturnValue ARC __weak ivars.
909 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000910 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000911
912 // Otherwise we want to do a simple load, suppressing the
913 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000914 } else {
John McCallba3dd902011-07-22 05:23:13 +0000915 value = EmitLoadOfLValue(LV).getScalarVal();
916 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000917 }
John McCallf85e1932011-06-15 23:02:42 +0000918
John McCallba3dd902011-07-22 05:23:13 +0000919 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000920 value = Builder.CreateBitCast(value,
921 ConvertType(GetterMethodDecl->getResultType()));
John McCallba3dd902011-07-22 05:23:13 +0000922 }
923
924 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000925 }
John McCall1e1f4872011-09-13 03:34:09 +0000926 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000927 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000928
John McCall1e1f4872011-09-13 03:34:09 +0000929 }
930 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000931}
932
John McCall41bdde92011-09-12 23:06:44 +0000933/// emitStructSetterCall - Call the runtime function to store the value
934/// from the first formal parameter into the given ivar.
935static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
936 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000937 // objc_copyStruct (&structIvar, &Arg,
938 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000939 CallArgList args;
940
941 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000942 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
943 CGF.LoadObjCSelf(), ivar, 0)
944 .getAddress();
945 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
946 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000947
948 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000949 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000950 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000951 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000952 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
953 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
954 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000955
956 // The third argument is the sizeof the type.
957 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000958 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
959 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000960
John McCall41bdde92011-09-12 23:06:44 +0000961 // The fourth argument is the 'isAtomic' flag.
962 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000963
John McCall41bdde92011-09-12 23:06:44 +0000964 // The fifth argument is the 'hasStrong' flag.
965 // FIXME: should this really always be false?
966 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
967
968 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000969 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
970 args,
971 FunctionType::ExtInfo(),
972 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000973 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000974}
975
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000976/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
977/// the value from the first formal parameter into the given ivar, using
978/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
979static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
980 ObjCMethodDecl *OMD,
981 ObjCIvarDecl *ivar,
982 llvm::Constant *AtomicHelperFn) {
983 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
984 // AtomicHelperFn);
985 CallArgList args;
986
987 // The first argument is the address of the ivar.
988 llvm::Value *ivarAddr =
989 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
990 CGF.LoadObjCSelf(), ivar, 0).getAddress();
991 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
992 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
993
994 // The second argument is the address of the parameter variable.
995 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000996 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000997 VK_LValue, SourceLocation());
998 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
999 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1000 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1001
1002 // Third argument is the helper function.
1003 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1004
1005 llvm::Value *copyCppAtomicObjectFn =
1006 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001007 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1008 args,
1009 FunctionType::ExtInfo(),
1010 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001011 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1012
1013
1014}
1015
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001016
John McCall1e1f4872011-09-13 03:34:09 +00001017static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1018 Expr *setter = PID->getSetterCXXAssignment();
1019 if (!setter) return true;
1020
1021 // Sema only makes only of these when the ivar has a C++ class type,
1022 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001023
1024 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001025 // This also implies that there's nothing non-trivial going on with
1026 // the arguments, because operator= can only be trivial if it's a
1027 // synthesized assignment operator and therefore both parameters are
1028 // references.
1029 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001030 if (const FunctionDecl *callee
1031 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1032 if (callee->isTrivial())
1033 return true;
1034 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001035 }
John McCall71c758d2011-09-10 09:17:20 +00001036
John McCall1e1f4872011-09-13 03:34:09 +00001037 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001038 return false;
1039}
1040
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001041static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001042 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001043 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001044 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001045}
1046
John McCall71c758d2011-09-10 09:17:20 +00001047void
1048CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001049 const ObjCPropertyImplDecl *propImpl,
1050 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001051 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001052 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001053 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001054
1055 // Just use the setter expression if Sema gave us one and it's
1056 // non-trivial.
1057 if (!hasTrivialSetExpr(propImpl)) {
1058 if (!AtomicHelperFn)
1059 // If non-atomic, assignment is called directly.
1060 EmitStmt(propImpl->getSetterCXXAssignment());
1061 else
1062 // If atomic, assignment is called via a locking api.
1063 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1064 AtomicHelperFn);
1065 return;
1066 }
John McCall71c758d2011-09-10 09:17:20 +00001067
John McCall1e1f4872011-09-13 03:34:09 +00001068 PropertyImplStrategy strategy(CGM, propImpl);
1069 switch (strategy.getKind()) {
1070 case PropertyImplStrategy::Native: {
1071 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001072
John McCall1e1f4872011-09-13 03:34:09 +00001073 LValue ivarLValue =
1074 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1075 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001076
John McCall1e1f4872011-09-13 03:34:09 +00001077 // Currently, all atomic accesses have to be through integer
1078 // types, so there's no point in trying to pick a prettier type.
1079 llvm::Type *bitcastType =
1080 llvm::Type::getIntNTy(getLLVMContext(),
1081 getContext().toBits(strategy.getIvarSize()));
1082 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1083
1084 // Cast both arguments to the chosen operation type.
1085 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1086 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1087
1088 // This bitcast load is likely to cause some nasty IR.
1089 llvm::Value *load = Builder.CreateLoad(argAddr);
1090
1091 // Perform an atomic store. There are no memory ordering requirements.
1092 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1093 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1094 store->setAtomic(llvm::Unordered);
1095 return;
1096 }
1097
1098 case PropertyImplStrategy::GetSetProperty:
1099 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001100
1101 llvm::Value *setOptimizedPropertyFn = 0;
1102 llvm::Value *setPropertyFn = 0;
1103 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001104 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001105 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001106 CGM.getObjCRuntime()
1107 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1108 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001109 if (!setOptimizedPropertyFn) {
1110 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1111 return;
1112 }
John McCall71c758d2011-09-10 09:17:20 +00001113 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001114 else {
1115 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1116 if (!setPropertyFn) {
1117 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1118 return;
1119 }
1120 }
1121
John McCall71c758d2011-09-10 09:17:20 +00001122 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1123 // <is-atomic>, <is-copy>).
1124 llvm::Value *cmd =
1125 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1126 llvm::Value *self =
1127 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1128 llvm::Value *ivarOffset =
1129 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1130 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1131 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1132
1133 CallArgList args;
1134 args.add(RValue::get(self), getContext().getObjCIdType());
1135 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001136 if (setOptimizedPropertyFn) {
1137 args.add(RValue::get(arg), getContext().getObjCIdType());
1138 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001139 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1140 FunctionType::ExtInfo(),
1141 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001142 setOptimizedPropertyFn, ReturnValueSlot(), args);
1143 } else {
1144 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1145 args.add(RValue::get(arg), getContext().getObjCIdType());
1146 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1147 getContext().BoolTy);
1148 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1149 getContext().BoolTy);
1150 // FIXME: We shouldn't need to get the function info here, the runtime
1151 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001152 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1153 FunctionType::ExtInfo(),
1154 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001155 setPropertyFn, ReturnValueSlot(), args);
1156 }
1157
John McCall71c758d2011-09-10 09:17:20 +00001158 return;
1159 }
1160
John McCall1e1f4872011-09-13 03:34:09 +00001161 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001162 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001163 return;
John McCall1e1f4872011-09-13 03:34:09 +00001164
1165 case PropertyImplStrategy::Expression:
1166 break;
John McCall71c758d2011-09-10 09:17:20 +00001167 }
1168
1169 // Otherwise, fake up some ASTs and emit a normal assignment.
1170 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001171 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1172 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001173 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1174 selfDecl->getType(), CK_LValueToRValue, &self,
1175 VK_RValue);
1176 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1177 SourceLocation(), &selfLoad, true, true);
1178
1179 ParmVarDecl *argDecl = *setterMethod->param_begin();
1180 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001181 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001182 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1183 argType.getUnqualifiedType(), CK_LValueToRValue,
1184 &arg, VK_RValue);
1185
1186 // The property type can differ from the ivar type in some situations with
1187 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1188 // The following absurdity is just to ensure well-formed IR.
1189 CastKind argCK = CK_NoOp;
1190 if (ivarRef.getType()->isObjCObjectPointerType()) {
1191 if (argLoad.getType()->isObjCObjectPointerType())
1192 argCK = CK_BitCast;
1193 else if (argLoad.getType()->isBlockPointerType())
1194 argCK = CK_BlockPointerToObjCPointerCast;
1195 else
1196 argCK = CK_CPointerToObjCPointerCast;
1197 } else if (ivarRef.getType()->isBlockPointerType()) {
1198 if (argLoad.getType()->isBlockPointerType())
1199 argCK = CK_BitCast;
1200 else
1201 argCK = CK_AnyPointerToBlockPointerCast;
1202 } else if (ivarRef.getType()->isPointerType()) {
1203 argCK = CK_BitCast;
1204 }
1205 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1206 ivarRef.getType(), argCK, &argLoad,
1207 VK_RValue);
1208 Expr *finalArg = &argLoad;
1209 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1210 argLoad.getType()))
1211 finalArg = &argCast;
1212
1213
1214 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1215 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +00001216 SourceLocation(), false);
John McCall71c758d2011-09-10 09:17:20 +00001217 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001218}
1219
James Dennett2ee5ba32012-06-15 22:10:14 +00001220/// \brief Generate an Objective-C property setter function.
1221///
1222/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001223/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001224void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1225 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001226 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001227 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001228 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1229 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1230 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001231 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001232
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001233 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001234
1235 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001236}
1237
John McCalle81ac692011-03-22 07:05:39 +00001238namespace {
John McCall9928c482011-07-12 16:41:08 +00001239 struct DestroyIvar : EHScopeStack::Cleanup {
1240 private:
1241 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001242 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001243 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001244 bool useEHCleanupForArray;
1245 public:
1246 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1247 CodeGenFunction::Destroyer *destroyer,
1248 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001249 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001250 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001251
John McCallad346f42011-07-12 20:27:29 +00001252 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001253 LValue lvalue
1254 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1255 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001256 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001257 }
1258 };
1259}
1260
John McCall9928c482011-07-12 16:41:08 +00001261/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1262static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1263 llvm::Value *addr,
1264 QualType type) {
1265 llvm::Value *null = getNullForVariable(addr);
1266 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1267}
John McCallf85e1932011-06-15 23:02:42 +00001268
John McCalle81ac692011-03-22 07:05:39 +00001269static void emitCXXDestructMethod(CodeGenFunction &CGF,
1270 ObjCImplementationDecl *impl) {
1271 CodeGenFunction::RunCleanupsScope scope(CGF);
1272
1273 llvm::Value *self = CGF.LoadObjCSelf();
1274
Jordy Rosedb8264e2011-07-22 02:08:32 +00001275 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1276 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001277 ivar; ivar = ivar->getNextIvar()) {
1278 QualType type = ivar->getType();
1279
John McCalle81ac692011-03-22 07:05:39 +00001280 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001281 QualType::DestructionKind dtorKind = type.isDestructedType();
1282 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001283
John McCall9928c482011-07-12 16:41:08 +00001284 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001285
John McCall9928c482011-07-12 16:41:08 +00001286 // Use a call to objc_storeStrong to destroy strong ivars, for the
1287 // general benefit of the tools.
1288 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001289 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001290
John McCall9928c482011-07-12 16:41:08 +00001291 // Otherwise use the default for the destruction kind.
1292 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001293 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001294 }
John McCall9928c482011-07-12 16:41:08 +00001295
1296 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1297
1298 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1299 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001300 }
1301
1302 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1303}
1304
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001305void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1306 ObjCMethodDecl *MD,
1307 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001308 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001309 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001310
1311 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001312 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001313 // Suppress the final autorelease in ARC.
1314 AutoreleaseResult = false;
1315
Chris Lattner5f9e2722011-07-23 10:55:15 +00001316 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001317 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1318 E = IMP->init_end(); B != E; ++B) {
1319 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001320 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001321 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001322 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1323 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001324 EmitAggExpr(IvarInit->getInit(),
1325 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001326 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001327 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001328 }
1329 // constructor returns 'self'.
1330 CodeGenTypes &Types = CGM.getTypes();
1331 QualType IdTy(CGM.getContext().getObjCIdType());
1332 llvm::Value *SelfAsId =
1333 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1334 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001335
1336 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001337 } else {
John McCalle81ac692011-03-22 07:05:39 +00001338 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001339 }
1340 FinishFunction();
1341}
1342
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001343bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1344 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1345 it++; it++;
1346 const ABIArgInfo &AI = it->info;
1347 // FIXME. Is this sufficient check?
1348 return (AI.getKind() == ABIArgInfo::Indirect);
1349}
1350
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001351bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001353 return false;
1354 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1355 return FDTTy->getDecl()->hasObjectMember();
1356 return false;
1357}
1358
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001359llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001360 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1361 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001362}
1363
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001364QualType CodeGenFunction::TypeOfSelfObject() {
1365 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1366 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001367 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1368 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001369 return PTy->getPointeeType();
1370}
1371
Chris Lattner74391b42009-03-22 21:03:39 +00001372void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001373 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001374 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001376 if (!EnumerationMutationFn) {
1377 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1378 return;
1379 }
1380
Devang Patelbcbd03a2011-01-19 01:36:36 +00001381 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001382 if (DI)
1383 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001384
Devang Patel9d99f2d2011-06-13 23:15:32 +00001385 // The local variable comes into scope immediately.
1386 AutoVarEmission variable = AutoVarEmission::invalid();
1387 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1388 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1389
John McCalld88687f2011-01-07 01:49:06 +00001390 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Anders Carlssonf484c312008-08-31 02:33:12 +00001392 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001393 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001394 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001395 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Anders Carlssonf484c312008-08-31 02:33:12 +00001397 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001398 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001399
John McCalld88687f2011-01-07 01:49:06 +00001400 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001401 IdentifierInfo *II[] = {
1402 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1403 &CGM.getContext().Idents.get("objects"),
1404 &CGM.getContext().Idents.get("count")
1405 };
1406 Selector FastEnumSel =
1407 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001408
1409 QualType ItemsTy =
1410 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001411 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001412 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001413 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001414
John McCall990567c2011-07-27 01:07:15 +00001415 // Emit the collection pointer. In ARC, we do a retain.
1416 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001417 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001418 Collection = EmitARCRetainScalarExpr(S.getCollection());
1419
1420 // Enter a cleanup to do the release.
1421 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1422 } else {
1423 Collection = EmitScalarExpr(S.getCollection());
1424 }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
John McCall4b302d32011-08-05 00:14:38 +00001426 // The 'continue' label needs to appear within the cleanup for the
1427 // collection object.
1428 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1429
John McCalld88687f2011-01-07 01:49:06 +00001430 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001431 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001432
1433 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001434 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001435
John McCalld88687f2011-01-07 01:49:06 +00001436 // The second argument is a temporary array with space for NumItems
1437 // pointers. We'll actually be loading elements from the array
1438 // pointer written into the control state; this buffer is so that
1439 // collections that *aren't* backed by arrays can still queue up
1440 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001441 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001442
John McCalld88687f2011-01-07 01:49:06 +00001443 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001444 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001445 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001446 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001447
John McCalld88687f2011-01-07 01:49:06 +00001448 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001449 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001450 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001451 getContext().UnsignedLongTy,
1452 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001453 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001454
John McCalld88687f2011-01-07 01:49:06 +00001455 // The initial number of objects that were returned in the buffer.
1456 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCalld88687f2011-01-07 01:49:06 +00001458 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1459 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001460
John McCalld88687f2011-01-07 01:49:06 +00001461 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001462
John McCalld88687f2011-01-07 01:49:06 +00001463 // If the limit pointer was zero to begin with, the collection is
1464 // empty; skip all this.
1465 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1466 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001467
John McCalld88687f2011-01-07 01:49:06 +00001468 // Otherwise, initialize the loop.
1469 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001470
John McCalld88687f2011-01-07 01:49:06 +00001471 // Save the initial mutations value. This is the value at an
1472 // address that was written into the state object by
1473 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001474 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001475 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001476 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001477 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001478
John McCalld88687f2011-01-07 01:49:06 +00001479 llvm::Value *initialMutations =
1480 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001481
John McCalld88687f2011-01-07 01:49:06 +00001482 // Start looping. This is the point we return to whenever we have a
1483 // fresh, non-empty batch of objects.
1484 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1485 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001486
John McCalld88687f2011-01-07 01:49:06 +00001487 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001488 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001489 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001490
John McCalld88687f2011-01-07 01:49:06 +00001491 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001492 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001493 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001494
John McCalld88687f2011-01-07 01:49:06 +00001495 // Check whether the mutations value has changed from where it was
1496 // at start. StateMutationsPtr should actually be invariant between
1497 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001498 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001499 llvm::Value *currentMutations
1500 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001501
John McCalld88687f2011-01-07 01:49:06 +00001502 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001503 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001504
John McCalld88687f2011-01-07 01:49:06 +00001505 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1506 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001507
John McCalld88687f2011-01-07 01:49:06 +00001508 // If so, call the enumeration-mutation function.
1509 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001510 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001511 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001512 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001513 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001514 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001515 // FIXME: We shouldn't need to get the function info here, the runtime already
1516 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001517 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1518 FunctionType::ExtInfo(),
1519 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001520 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
John McCalld88687f2011-01-07 01:49:06 +00001522 // Otherwise, or if the mutation function returns, just continue.
1523 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001524
John McCalld88687f2011-01-07 01:49:06 +00001525 // Initialize the element variable.
1526 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001527 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001528 LValue elementLValue;
1529 QualType elementType;
1530 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001531 // Initialize the variable, in case it's a __block variable or something.
1532 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001533
John McCall57b3b6a2011-02-22 07:16:58 +00001534 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001535 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001536 VK_LValue, SourceLocation());
1537 elementLValue = EmitLValue(&tempDRE);
1538 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001539 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001540
1541 if (D->isARCPseudoStrong())
1542 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001543 } else {
1544 elementLValue = LValue(); // suppress warning
1545 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001546 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001547 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001548 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001549
1550 // Fetch the buffer out of the enumeration state.
1551 // TODO: this pointer should actually be invariant between
1552 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001553 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001554 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001555 llvm::Value *EnumStateItems =
1556 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001557
John McCalld88687f2011-01-07 01:49:06 +00001558 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001559 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001560 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1561 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001562
John McCalld88687f2011-01-07 01:49:06 +00001563 // Cast that value to the right type.
1564 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1565 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001566
John McCalld88687f2011-01-07 01:49:06 +00001567 // Make sure we have an l-value. Yes, this gets evaluated every
1568 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001569 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001570 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001571 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001572 } else {
1573 EmitScalarInit(CurrentItem, elementLValue);
1574 }
Mike Stump1eb44332009-09-09 15:08:12 +00001575
John McCall57b3b6a2011-02-22 07:16:58 +00001576 // If we do have an element variable, this assignment is the end of
1577 // its initialization.
1578 if (elementIsVariable)
1579 EmitAutoVarCleanups(variable);
1580
John McCalld88687f2011-01-07 01:49:06 +00001581 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001582 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001583 {
1584 RunCleanupsScope Scope(*this);
1585 EmitStmt(S.getBody());
1586 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001587 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001588
John McCalld88687f2011-01-07 01:49:06 +00001589 // Destroy the element variable now.
1590 elementVariableScope.ForceCleanup();
1591
1592 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001593 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001594
John McCalld88687f2011-01-07 01:49:06 +00001595 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001596
John McCalld88687f2011-01-07 01:49:06 +00001597 // First we check in the local buffer.
1598 llvm::Value *indexPlusOne
1599 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001600
John McCalld88687f2011-01-07 01:49:06 +00001601 // If we haven't overrun the buffer yet, we can continue.
1602 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1603 LoopBodyBB, FetchMoreBB);
1604
1605 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1606 count->addIncoming(count, AfterBody.getBlock());
1607
1608 // Otherwise, we have to fetch more elements.
1609 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
1611 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001612 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001613 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001614 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001615 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001616
John McCalld88687f2011-01-07 01:49:06 +00001617 // If we got a zero count, we're done.
1618 llvm::Value *refetchCount = CountRV.getScalarVal();
1619
1620 // (note that the message send might split FetchMoreBB)
1621 index->addIncoming(zero, Builder.GetInsertBlock());
1622 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1623
1624 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1625 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001626
Anders Carlssonf484c312008-08-31 02:33:12 +00001627 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001628 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001629
John McCall57b3b6a2011-02-22 07:16:58 +00001630 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001631 // If the element was not a declaration, set it to be null.
1632
John McCalld88687f2011-01-07 01:49:06 +00001633 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1634 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001635 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001636 }
1637
Eric Christopher73fb3502011-10-13 21:45:18 +00001638 if (DI)
1639 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001640
John McCall990567c2011-07-27 01:07:15 +00001641 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001642 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001643 PopCleanupBlock();
1644
John McCallff8e1152010-07-23 21:56:41 +00001645 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001646}
1647
Mike Stump1eb44332009-09-09 15:08:12 +00001648void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001649 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001650}
1651
Mike Stump1eb44332009-09-09 15:08:12 +00001652void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001653 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1654}
1655
Chris Lattner10cac6f2008-11-15 21:26:17 +00001656void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001657 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001658 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001659}
1660
John McCall33e56f32011-09-10 06:18:15 +00001661/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001662/// primitive retain.
1663llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1664 llvm::Value *value) {
1665 return EmitARCRetain(type, value);
1666}
1667
1668namespace {
1669 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001670 CallObjCRelease(llvm::Value *object) : object(object) {}
1671 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001672
John McCallad346f42011-07-12 20:27:29 +00001673 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001674 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001675 }
1676 };
1677}
1678
John McCall33e56f32011-09-10 06:18:15 +00001679/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001680/// release at the end of the full-expression.
1681llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1682 llvm::Value *object) {
1683 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001684 // conditional.
1685 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001686 return object;
1687}
1688
1689llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1690 llvm::Value *value) {
1691 return EmitARCRetainAutorelease(type, value);
1692}
1693
1694
1695static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001696 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001697 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001698 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1699
John McCall260611a2012-06-20 06:18:46 +00001700 // If the target runtime doesn't naturally support ARC, emit weak
1701 // references to the runtime support library. We don't really
1702 // permit this to fail, but we need a particular relocation style.
Fariborz Jahanianc343dd82012-08-07 21:30:31 +00001703 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
John McCall0a7dd782012-08-21 02:47:43 +00001704 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC())
John McCallf85e1932011-06-15 23:02:42 +00001705 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Fariborz Jahanianc343dd82012-08-07 21:30:31 +00001706 // set nonlazybind attribute for these APIs for performance.
1707 if (fnName == "objc_retain" || fnName == "objc_release")
Bill Wendlingfac63102012-10-10 03:13:20 +00001708 f->addFnAttr(llvm::Attributes::NonLazyBind);
Fariborz Jahanianc343dd82012-08-07 21:30:31 +00001709 }
John McCallf85e1932011-06-15 23:02:42 +00001710
1711 return fn;
1712}
1713
1714/// Perform an operation having the signature
1715/// i8* (i8*)
1716/// where a null input causes a no-op and returns null.
1717static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1718 llvm::Value *value,
1719 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001720 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001721 if (isa<llvm::ConstantPointerNull>(value)) return value;
1722
1723 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001724 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001725 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001726 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1727 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1728 }
1729
1730 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001731 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001732 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1733
1734 // Call the function.
1735 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1736 call->setDoesNotThrow();
1737
1738 // Cast the result back to the original type.
1739 return CGF.Builder.CreateBitCast(call, origType);
1740}
1741
1742/// Perform an operation having the following signature:
1743/// i8* (i8**)
1744static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1745 llvm::Value *addr,
1746 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001747 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001748 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001749 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001750 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001751 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1752 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1753 }
1754
1755 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001756 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001757 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1758
1759 // Call the function.
1760 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1761 call->setDoesNotThrow();
1762
1763 // Cast the result back to a dereference of the original type.
1764 llvm::Value *result = call;
1765 if (origType != CGF.Int8PtrPtrTy)
1766 result = CGF.Builder.CreateBitCast(result,
1767 cast<llvm::PointerType>(origType)->getElementType());
1768
1769 return result;
1770}
1771
1772/// Perform an operation having the following signature:
1773/// i8* (i8**, i8*)
1774static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1775 llvm::Value *addr,
1776 llvm::Value *value,
1777 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001778 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001779 bool ignored) {
1780 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1781 == value->getType());
1782
1783 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001784 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001785
Chris Lattner2acc6e32011-07-18 04:24:23 +00001786 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001787 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1788 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1789 }
1790
Chris Lattner2acc6e32011-07-18 04:24:23 +00001791 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001792
1793 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1794 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1795
1796 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1797 result->setDoesNotThrow();
1798
1799 if (ignored) return 0;
1800
1801 return CGF.Builder.CreateBitCast(result, origType);
1802}
1803
1804/// Perform an operation having the following signature:
1805/// void (i8**, i8**)
1806static void emitARCCopyOperation(CodeGenFunction &CGF,
1807 llvm::Value *dst,
1808 llvm::Value *src,
1809 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001810 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001811 assert(dst->getType() == src->getType());
1812
1813 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001814 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001815 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001816 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1817 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1818 }
1819
1820 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1821 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1822
1823 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1824 result->setDoesNotThrow();
1825}
1826
1827/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001828/// call i8* \@objc_retain(i8* %value)
1829/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001830llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1831 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001832 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001833 else
1834 return EmitARCRetainNonBlock(value);
1835}
1836
1837/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001838/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001839llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1840 return emitARCValueOperation(*this, value,
1841 CGM.getARCEntrypoints().objc_retain,
1842 "objc_retain");
1843}
1844
1845/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001846/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001847///
1848/// \param mandatory - If false, emit the call with metadata
1849/// indicating that it's okay for the optimizer to eliminate this call
1850/// if it can prove that the block never escapes except down the stack.
1851llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1852 bool mandatory) {
1853 llvm::Value *result
1854 = emitARCValueOperation(*this, value,
1855 CGM.getARCEntrypoints().objc_retainBlock,
1856 "objc_retainBlock");
1857
1858 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1859 // tell the optimizer that it doesn't need to do this copy if the
1860 // block doesn't escape, where being passed as an argument doesn't
1861 // count as escaping.
1862 if (!mandatory && isa<llvm::Instruction>(result)) {
1863 llvm::CallInst *call
1864 = cast<llvm::CallInst>(result->stripPointerCasts());
1865 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1866
1867 SmallVector<llvm::Value*,1> args;
1868 call->setMetadata("clang.arc.copy_on_escape",
1869 llvm::MDNode::get(Builder.getContext(), args));
1870 }
1871
1872 return result;
John McCallf85e1932011-06-15 23:02:42 +00001873}
1874
1875/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001876/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001877///
1878/// Yes, this function name is one character away from a different
1879/// call with completely different semantics.
1880llvm::Value *
1881CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1882 // Fetch the void(void) inline asm which marks that we're going to
1883 // retain the autoreleased return value.
1884 llvm::InlineAsm *&marker
1885 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1886 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001887 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001888 = CGM.getTargetCodeGenInfo()
1889 .getARCRetainAutoreleasedReturnValueMarker();
1890
1891 // If we have an empty assembly string, there's nothing to do.
1892 if (assembly.empty()) {
1893
1894 // Otherwise, at -O0, build an inline asm that we're going to call
1895 // in a moment.
1896 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1897 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001898 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001899
1900 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1901
1902 // If we're at -O1 and above, we don't want to litter the code
1903 // with this marker yet, so leave a breadcrumb for the ARC
1904 // optimizer to pick up.
1905 } else {
1906 llvm::NamedMDNode *metadata =
1907 CGM.getModule().getOrInsertNamedMetadata(
1908 "clang.arc.retainAutoreleasedReturnValueMarker");
1909 assert(metadata->getNumOperands() <= 1);
1910 if (metadata->getNumOperands() == 0) {
1911 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001912 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001913 }
1914 }
1915 }
1916
1917 // Call the marker asm if we made one, which we do only at -O0.
1918 if (marker) Builder.CreateCall(marker);
1919
1920 return emitARCValueOperation(*this, value,
1921 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1922 "objc_retainAutoreleasedReturnValue");
1923}
1924
1925/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001926/// call void \@objc_release(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001927void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1928 if (isa<llvm::ConstantPointerNull>(value)) return;
1929
1930 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1931 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001932 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001933 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001934 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1935 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1936 }
1937
1938 // Cast the argument to 'id'.
1939 value = Builder.CreateBitCast(value, Int8PtrTy);
1940
1941 // Call objc_release.
1942 llvm::CallInst *call = Builder.CreateCall(fn, value);
1943 call->setDoesNotThrow();
1944
1945 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001946 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001947 call->setMetadata("clang.imprecise_release",
1948 llvm::MDNode::get(Builder.getContext(), args));
1949 }
1950}
1951
1952/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001953/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001954llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1955 llvm::Value *value,
1956 bool ignored) {
1957 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1958 == value->getType());
1959
1960 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1961 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001962 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001963 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001964 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1965 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1966 }
1967
1968 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1969 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1970
1971 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1972
1973 if (ignored) return 0;
1974 return value;
1975}
1976
1977/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001978/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001979/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001980llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001981 llvm::Value *newValue,
1982 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001983 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001984 bool isBlock = type->isBlockPointerType();
1985
1986 // Use a store barrier at -O0 unless this is a block type or the
1987 // lvalue is inadequately aligned.
1988 if (shouldUseFusedARCCalls() &&
1989 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001990 (dst.getAlignment().isZero() ||
1991 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001992 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1993 }
1994
1995 // Otherwise, split it out.
1996
1997 // Retain the new value.
1998 newValue = EmitARCRetain(type, newValue);
1999
2000 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00002001 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00002002
2003 // Store. We do this before the release so that any deallocs won't
2004 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002005 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002006
2007 // Finally, release the old value.
2008 EmitARCRelease(oldValue, /*precise*/ false);
2009
2010 return newValue;
2011}
2012
2013/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002014/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002015llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2016 return emitARCValueOperation(*this, value,
2017 CGM.getARCEntrypoints().objc_autorelease,
2018 "objc_autorelease");
2019}
2020
2021/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002022/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002023llvm::Value *
2024CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2025 return emitARCValueOperation(*this, value,
2026 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2027 "objc_autoreleaseReturnValue");
2028}
2029
2030/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002031/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002032llvm::Value *
2033CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2034 return emitARCValueOperation(*this, value,
2035 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2036 "objc_retainAutoreleaseReturnValue");
2037}
2038
2039/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002040/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002041/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002042/// %retain = call i8* \@objc_retainBlock(i8* %value)
2043/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002044llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2045 llvm::Value *value) {
2046 if (!type->isBlockPointerType())
2047 return EmitARCRetainAutoreleaseNonBlock(value);
2048
2049 if (isa<llvm::ConstantPointerNull>(value)) return value;
2050
Chris Lattner2acc6e32011-07-18 04:24:23 +00002051 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002052 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002053 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002054 value = EmitARCAutorelease(value);
2055 return Builder.CreateBitCast(value, origType);
2056}
2057
2058/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002059/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002060llvm::Value *
2061CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2062 return emitARCValueOperation(*this, value,
2063 CGM.getARCEntrypoints().objc_retainAutorelease,
2064 "objc_retainAutorelease");
2065}
2066
James Dennett9d96e9c2012-06-22 05:41:30 +00002067/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002068/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2069llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2070 return emitARCLoadOperation(*this, addr,
2071 CGM.getARCEntrypoints().objc_loadWeak,
2072 "objc_loadWeak");
2073}
2074
James Dennett9d96e9c2012-06-22 05:41:30 +00002075/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002076llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2077 return emitARCLoadOperation(*this, addr,
2078 CGM.getARCEntrypoints().objc_loadWeakRetained,
2079 "objc_loadWeakRetained");
2080}
2081
James Dennett9d96e9c2012-06-22 05:41:30 +00002082/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002083/// Returns %value.
2084llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2085 llvm::Value *value,
2086 bool ignored) {
2087 return emitARCStoreOperation(*this, addr, value,
2088 CGM.getARCEntrypoints().objc_storeWeak,
2089 "objc_storeWeak", ignored);
2090}
2091
James Dennett9d96e9c2012-06-22 05:41:30 +00002092/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002093/// Returns %value. %addr is known to not have a current weak entry.
2094/// Essentially equivalent to:
2095/// *addr = nil; objc_storeWeak(addr, value);
2096void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2097 // If we're initializing to null, just write null to memory; no need
2098 // to get the runtime involved. But don't do this if optimization
2099 // is enabled, because accounting for this would make the optimizer
2100 // much more complicated.
2101 if (isa<llvm::ConstantPointerNull>(value) &&
2102 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2103 Builder.CreateStore(value, addr);
2104 return;
2105 }
2106
2107 emitARCStoreOperation(*this, addr, value,
2108 CGM.getARCEntrypoints().objc_initWeak,
2109 "objc_initWeak", /*ignored*/ true);
2110}
2111
James Dennett9d96e9c2012-06-22 05:41:30 +00002112/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002113/// Essentially objc_storeWeak(addr, nil).
2114void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2115 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2116 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002117 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002118 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002119 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2120 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2121 }
2122
2123 // Cast the argument to 'id*'.
2124 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2125
2126 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2127 call->setDoesNotThrow();
2128}
2129
James Dennett9d96e9c2012-06-22 05:41:30 +00002130/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002131/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2132/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2133void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2134 emitARCCopyOperation(*this, dst, src,
2135 CGM.getARCEntrypoints().objc_moveWeak,
2136 "objc_moveWeak");
2137}
2138
James Dennett9d96e9c2012-06-22 05:41:30 +00002139/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002140/// Disregards the current value in %dest. Essentially
2141/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2142void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2143 emitARCCopyOperation(*this, dst, src,
2144 CGM.getARCEntrypoints().objc_copyWeak,
2145 "objc_copyWeak");
2146}
2147
2148/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002149/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002150llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2151 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2152 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002153 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002154 llvm::FunctionType::get(Int8PtrTy, false);
2155 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2156 }
2157
2158 llvm::CallInst *call = Builder.CreateCall(fn);
2159 call->setDoesNotThrow();
2160
2161 return call;
2162}
2163
2164/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002165/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002166void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2167 assert(value->getType() == Int8PtrTy);
2168
2169 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2170 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002171 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002172 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002173 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2174
2175 // We don't want to use a weak import here; instead we should not
2176 // fall into this path.
2177 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2178 }
2179
2180 llvm::CallInst *call = Builder.CreateCall(fn, value);
2181 call->setDoesNotThrow();
2182}
2183
2184/// Produce the code to do an MRR version objc_autoreleasepool_push.
2185/// Which is: [[NSAutoreleasePool alloc] init];
2186/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2187/// init is declared as: - (id) init; in its NSObject super class.
2188///
2189llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2190 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2191 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2192 // [NSAutoreleasePool alloc]
2193 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2194 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2195 CallArgList Args;
2196 RValue AllocRV =
2197 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2198 getContext().getObjCIdType(),
2199 AllocSel, Receiver, Args);
2200
2201 // [Receiver init]
2202 Receiver = AllocRV.getScalarVal();
2203 II = &CGM.getContext().Idents.get("init");
2204 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2205 RValue InitRV =
2206 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2207 getContext().getObjCIdType(),
2208 InitSel, Receiver, Args);
2209 return InitRV.getScalarVal();
2210}
2211
2212/// Produce the code to do a primitive release.
2213/// [tmp drain];
2214void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2215 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2216 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2217 CallArgList Args;
2218 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2219 getContext().VoidTy, DrainSel, Arg, Args);
2220}
2221
John McCallbdc4d802011-07-09 01:37:26 +00002222void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2223 llvm::Value *addr,
2224 QualType type) {
2225 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2226 CGF.EmitARCRelease(ptr, /*precise*/ true);
2227}
2228
2229void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2230 llvm::Value *addr,
2231 QualType type) {
2232 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2233 CGF.EmitARCRelease(ptr, /*precise*/ false);
2234}
2235
2236void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2237 llvm::Value *addr,
2238 QualType type) {
2239 CGF.EmitARCDestroyWeak(addr);
2240}
2241
John McCallf85e1932011-06-15 23:02:42 +00002242namespace {
John McCallf85e1932011-06-15 23:02:42 +00002243 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2244 llvm::Value *Token;
2245
2246 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2247
John McCallad346f42011-07-12 20:27:29 +00002248 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002249 CGF.EmitObjCAutoreleasePoolPop(Token);
2250 }
2251 };
2252 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2253 llvm::Value *Token;
2254
2255 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2256
John McCallad346f42011-07-12 20:27:29 +00002257 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002258 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2259 }
2260 };
2261}
2262
2263void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002264 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002265 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2266 else
2267 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2268}
2269
John McCallf85e1932011-06-15 23:02:42 +00002270static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2271 LValue lvalue,
2272 QualType type) {
2273 switch (type.getObjCLifetime()) {
2274 case Qualifiers::OCL_None:
2275 case Qualifiers::OCL_ExplicitNone:
2276 case Qualifiers::OCL_Strong:
2277 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002278 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002279 false);
2280
2281 case Qualifiers::OCL_Weak:
2282 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2283 true);
2284 }
2285
2286 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002287}
2288
2289static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2290 const Expr *e) {
2291 e = e->IgnoreParens();
2292 QualType type = e->getType();
2293
John McCall21480112011-08-30 00:57:29 +00002294 // If we're loading retained from a __strong xvalue, we can avoid
2295 // an extra retain/release pair by zeroing out the source of this
2296 // "move" operation.
2297 if (e->isXValue() &&
2298 !type.isConstQualified() &&
2299 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2300 // Emit the lvalue.
2301 LValue lv = CGF.EmitLValue(e);
2302
2303 // Load the object pointer.
2304 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2305
2306 // Set the source pointer to NULL.
2307 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2308
2309 return TryEmitResult(result, true);
2310 }
2311
John McCallf85e1932011-06-15 23:02:42 +00002312 // As a very special optimization, in ARC++, if the l-value is the
2313 // result of a non-volatile assignment, do a simple retain of the
2314 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002315 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002316 !type.isVolatileQualified() &&
2317 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2318 isa<BinaryOperator>(e) &&
2319 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2320 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2321
2322 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2323}
2324
2325static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2326 llvm::Value *value);
2327
2328/// Given that the given expression is some sort of call (which does
2329/// not return retained), emit a retain following it.
2330static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2331 llvm::Value *value = CGF.EmitScalarExpr(e);
2332 return emitARCRetainAfterCall(CGF, value);
2333}
2334
2335static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2336 llvm::Value *value) {
2337 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2338 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2339
2340 // Place the retain immediately following the call.
2341 CGF.Builder.SetInsertPoint(call->getParent(),
2342 ++llvm::BasicBlock::iterator(call));
2343 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2344
2345 CGF.Builder.restoreIP(ip);
2346 return value;
2347 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2348 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2349
2350 // Place the retain at the beginning of the normal destination block.
2351 llvm::BasicBlock *BB = invoke->getNormalDest();
2352 CGF.Builder.SetInsertPoint(BB, BB->begin());
2353 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2354
2355 CGF.Builder.restoreIP(ip);
2356 return value;
2357
2358 // Bitcasts can arise because of related-result returns. Rewrite
2359 // the operand.
2360 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2361 llvm::Value *operand = bitcast->getOperand(0);
2362 operand = emitARCRetainAfterCall(CGF, operand);
2363 bitcast->setOperand(0, operand);
2364 return bitcast;
2365
2366 // Generic fall-back case.
2367 } else {
2368 // Retain using the non-block variant: we never need to do a copy
2369 // of a block that's been returned to us.
2370 return CGF.EmitARCRetainNonBlock(value);
2371 }
2372}
2373
John McCalldc05b112011-09-10 01:16:55 +00002374/// Determine whether it might be important to emit a separate
2375/// objc_retain_block on the result of the given expression, or
2376/// whether it's okay to just emit it in a +1 context.
2377static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2378 assert(e->getType()->isBlockPointerType());
2379 e = e->IgnoreParens();
2380
2381 // For future goodness, emit block expressions directly in +1
2382 // contexts if we can.
2383 if (isa<BlockExpr>(e))
2384 return false;
2385
2386 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2387 switch (cast->getCastKind()) {
2388 // Emitting these operations in +1 contexts is goodness.
2389 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002390 case CK_ARCReclaimReturnedObject:
2391 case CK_ARCConsumeObject:
2392 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002393 return false;
2394
2395 // These operations preserve a block type.
2396 case CK_NoOp:
2397 case CK_BitCast:
2398 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2399
2400 // These operations are known to be bad (or haven't been considered).
2401 case CK_AnyPointerToBlockPointerCast:
2402 default:
2403 return true;
2404 }
2405 }
2406
2407 return true;
2408}
2409
John McCall4b9c2d22011-11-06 09:01:30 +00002410/// Try to emit a PseudoObjectExpr at +1.
2411///
2412/// This massively duplicates emitPseudoObjectRValue.
2413static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2414 const PseudoObjectExpr *E) {
2415 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2416
2417 // Find the result expression.
2418 const Expr *resultExpr = E->getResultExpr();
2419 assert(resultExpr);
2420 TryEmitResult result;
2421
2422 for (PseudoObjectExpr::const_semantics_iterator
2423 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2424 const Expr *semantic = *i;
2425
2426 // If this semantic expression is an opaque value, bind it
2427 // to the result of its source expression.
2428 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2429 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2430 OVMA opaqueData;
2431
2432 // If this semantic is the result of the pseudo-object
2433 // expression, try to evaluate the source as +1.
2434 if (ov == resultExpr) {
2435 assert(!OVMA::shouldBindAsLValue(ov));
2436 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2437 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2438
2439 // Otherwise, just bind it.
2440 } else {
2441 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2442 }
2443 opaques.push_back(opaqueData);
2444
2445 // Otherwise, if the expression is the result, evaluate it
2446 // and remember the result.
2447 } else if (semantic == resultExpr) {
2448 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2449
2450 // Otherwise, evaluate the expression in an ignored context.
2451 } else {
2452 CGF.EmitIgnoredExpr(semantic);
2453 }
2454 }
2455
2456 // Unbind all the opaques now.
2457 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2458 opaques[i].unbind(CGF);
2459
2460 return result;
2461}
2462
John McCallf85e1932011-06-15 23:02:42 +00002463static TryEmitResult
2464tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002465 // Look through cleanups.
2466 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002467 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002468 CodeGenFunction::RunCleanupsScope scope(CGF);
2469 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2470 }
2471
John McCallf85e1932011-06-15 23:02:42 +00002472 // The desired result type, if it differs from the type of the
2473 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002474 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002475
2476 while (true) {
2477 e = e->IgnoreParens();
2478
2479 // There's a break at the end of this if-chain; anything
2480 // that wants to keep looping has to explicitly continue.
2481 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2482 switch (ce->getCastKind()) {
2483 // No-op casts don't change the type, so we just ignore them.
2484 case CK_NoOp:
2485 e = ce->getSubExpr();
2486 continue;
2487
2488 case CK_LValueToRValue: {
2489 TryEmitResult loadResult
2490 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2491 if (resultType) {
2492 llvm::Value *value = loadResult.getPointer();
2493 value = CGF.Builder.CreateBitCast(value, resultType);
2494 loadResult.setPointer(value);
2495 }
2496 return loadResult;
2497 }
2498
2499 // These casts can change the type, so remember that and
2500 // soldier on. We only need to remember the outermost such
2501 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002502 case CK_CPointerToObjCPointerCast:
2503 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002504 case CK_AnyPointerToBlockPointerCast:
2505 case CK_BitCast:
2506 if (!resultType)
2507 resultType = CGF.ConvertType(ce->getType());
2508 e = ce->getSubExpr();
2509 assert(e->getType()->hasPointerRepresentation());
2510 continue;
2511
2512 // For consumptions, just emit the subexpression and thus elide
2513 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002514 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002515 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2516 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2517 return TryEmitResult(result, true);
2518 }
2519
John McCalldc05b112011-09-10 01:16:55 +00002520 // Block extends are net +0. Naively, we could just recurse on
2521 // the subexpression, but actually we need to ensure that the
2522 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002523 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002524 llvm::Value *result; // will be a +0 value
2525
2526 // If we can't safely assume the sub-expression will produce a
2527 // block-copied value, emit the sub-expression at +0.
2528 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2529 result = CGF.EmitScalarExpr(ce->getSubExpr());
2530
2531 // Otherwise, try to emit the sub-expression at +1 recursively.
2532 } else {
2533 TryEmitResult subresult
2534 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2535 result = subresult.getPointer();
2536
2537 // If that produced a retained value, just use that,
2538 // possibly casting down.
2539 if (subresult.getInt()) {
2540 if (resultType)
2541 result = CGF.Builder.CreateBitCast(result, resultType);
2542 return TryEmitResult(result, true);
2543 }
2544
2545 // Otherwise it's +0.
2546 }
2547
2548 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002549 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002550 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2551 return TryEmitResult(result, true);
2552 }
2553
John McCall7e5e5f42011-07-07 06:58:02 +00002554 // For reclaims, emit the subexpression as a retained call and
2555 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002556 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002557 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2558 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2559 return TryEmitResult(result, true);
2560 }
2561
John McCallf85e1932011-06-15 23:02:42 +00002562 default:
2563 break;
2564 }
2565
2566 // Skip __extension__.
2567 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2568 if (op->getOpcode() == UO_Extension) {
2569 e = op->getSubExpr();
2570 continue;
2571 }
2572
2573 // For calls and message sends, use the retained-call logic.
2574 // Delegate inits are a special case in that they're the only
2575 // returns-retained expression that *isn't* surrounded by
2576 // a consume.
2577 } else if (isa<CallExpr>(e) ||
2578 (isa<ObjCMessageExpr>(e) &&
2579 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2580 llvm::Value *result = emitARCRetainCall(CGF, e);
2581 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2582 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002583
2584 // Look through pseudo-object expressions.
2585 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2586 TryEmitResult result
2587 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2588 if (resultType) {
2589 llvm::Value *value = result.getPointer();
2590 value = CGF.Builder.CreateBitCast(value, resultType);
2591 result.setPointer(value);
2592 }
2593 return result;
John McCallf85e1932011-06-15 23:02:42 +00002594 }
2595
2596 // Conservatively halt the search at any other expression kind.
2597 break;
2598 }
2599
2600 // We didn't find an obvious production, so emit what we've got and
2601 // tell the caller that we didn't manage to retain.
2602 llvm::Value *result = CGF.EmitScalarExpr(e);
2603 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2604 return TryEmitResult(result, false);
2605}
2606
2607static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2608 LValue lvalue,
2609 QualType type) {
2610 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2611 llvm::Value *value = result.getPointer();
2612 if (!result.getInt())
2613 value = CGF.EmitARCRetain(type, value);
2614 return value;
2615}
2616
2617/// EmitARCRetainScalarExpr - Semantically equivalent to
2618/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2619/// best-effort attempt to peephole expressions that naturally produce
2620/// retained objects.
2621llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2622 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2623 llvm::Value *value = result.getPointer();
2624 if (!result.getInt())
2625 value = EmitARCRetain(e->getType(), value);
2626 return value;
2627}
2628
2629llvm::Value *
2630CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2631 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2632 llvm::Value *value = result.getPointer();
2633 if (result.getInt())
2634 value = EmitARCAutorelease(value);
2635 else
2636 value = EmitARCRetainAutorelease(e->getType(), value);
2637 return value;
2638}
2639
John McCall348f16f2011-10-04 06:23:45 +00002640llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2641 llvm::Value *result;
2642 bool doRetain;
2643
2644 if (shouldEmitSeparateBlockRetain(e)) {
2645 result = EmitScalarExpr(e);
2646 doRetain = true;
2647 } else {
2648 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2649 result = subresult.getPointer();
2650 doRetain = !subresult.getInt();
2651 }
2652
2653 if (doRetain)
2654 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2655 return EmitObjCConsumeObject(e->getType(), result);
2656}
2657
John McCall2b014d62011-10-01 10:32:24 +00002658llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2659 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002660 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002661 // Do so before running any cleanups for the full-expression.
2662 // tryEmitARCRetainScalarExpr does make an effort to do things
2663 // inside cleanups, but there are crazy cases like
2664 // @throw A().foo;
2665 // where a full retain+autorelease is required and would
2666 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002667 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2668 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002669 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002670 }
John McCall2b014d62011-10-01 10:32:24 +00002671
John McCall1a343eb2011-11-10 08:15:53 +00002672 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002673 return EmitARCRetainAutoreleaseScalarExpr(expr);
2674 }
2675
2676 // Otherwise, use the normal scalar-expression emission. The
2677 // exception machinery doesn't do anything special with the
2678 // exception like retaining it, so there's no safety associated with
2679 // only running cleanups after the throw has started, and when it
2680 // matters it tends to be substantially inferior code.
2681 return EmitScalarExpr(expr);
2682}
2683
John McCallf85e1932011-06-15 23:02:42 +00002684std::pair<LValue,llvm::Value*>
2685CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2686 bool ignored) {
2687 // Evaluate the RHS first.
2688 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2689 llvm::Value *value = result.getPointer();
2690
John McCallfb720812011-07-28 07:23:35 +00002691 bool hasImmediateRetain = result.getInt();
2692
2693 // If we didn't emit a retained object, and the l-value is of block
2694 // type, then we need to emit the block-retain immediately in case
2695 // it invalidates the l-value.
2696 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002697 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002698 hasImmediateRetain = true;
2699 }
2700
John McCallf85e1932011-06-15 23:02:42 +00002701 LValue lvalue = EmitLValue(e->getLHS());
2702
2703 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002704 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002705 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002706 EmitLoadOfScalar(lvalue);
2707 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002708 EmitARCRelease(oldValue, /*precise*/ false);
2709 } else {
John McCall545d9962011-06-25 02:11:03 +00002710 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002711 }
2712
2713 return std::pair<LValue,llvm::Value*>(lvalue, value);
2714}
2715
2716std::pair<LValue,llvm::Value*>
2717CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2718 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2719 LValue lvalue = EmitLValue(e->getLHS());
2720
Eli Friedman6da2c712011-12-03 04:14:32 +00002721 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002722
2723 return std::pair<LValue,llvm::Value*>(lvalue, value);
2724}
2725
2726void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002727 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002728 const Stmt *subStmt = ARPS.getSubStmt();
2729 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2730
2731 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002732 if (DI)
2733 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002734
2735 // Keep track of the current cleanup stack depth.
2736 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00002737 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002738 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2739 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2740 } else {
2741 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2742 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2743 }
2744
2745 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2746 E = S.body_end(); I != E; ++I)
2747 EmitStmt(*I);
2748
Eric Christopher73fb3502011-10-13 21:45:18 +00002749 if (DI)
2750 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002751}
John McCall0c24c802011-06-24 23:21:27 +00002752
2753/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2754/// make sure it survives garbage collection until this point.
2755void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2756 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002757 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002758 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002759 llvm::Value *extender
2760 = llvm::InlineAsm::get(extenderType,
2761 /* assembly */ "",
2762 /* constraints */ "r",
2763 /* side effects */ true);
2764
2765 object = Builder.CreateBitCast(object, VoidPtrTy);
2766 Builder.CreateCall(extender, object)->setDoesNotThrow();
2767}
2768
John McCall260611a2012-06-20 06:18:46 +00002769static bool hasAtomicCopyHelperAPI(const ObjCRuntime &runtime) {
2770 // For now, only NeXT has these APIs.
2771 return runtime.isNeXTFamily();
2772}
2773
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002774/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002775/// non-trivial copy assignment function, produce following helper function.
2776/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2777///
2778llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002779CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2780 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002781 // FIXME. This api is for NeXt runtime only for now.
John McCall260611a2012-06-20 06:18:46 +00002782 if (!getLangOpts().CPlusPlus ||
2783 !hasAtomicCopyHelperAPI(getLangOpts().ObjCRuntime))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002784 return 0;
2785 QualType Ty = PID->getPropertyIvarDecl()->getType();
2786 if (!Ty->isRecordType())
2787 return 0;
2788 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002789 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002790 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002791 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002792 if (hasTrivialSetExpr(PID))
2793 return 0;
2794 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2795 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2796 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002797
2798 ASTContext &C = getContext();
2799 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002800 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002801 FunctionDecl *FD = FunctionDecl::Create(C,
2802 C.getTranslationUnitDecl(),
2803 SourceLocation(),
2804 SourceLocation(), II, C.VoidTy, 0,
2805 SC_Static,
2806 SC_None,
2807 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002808 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002809
2810 QualType DestTy = C.getPointerType(Ty);
2811 QualType SrcTy = Ty;
2812 SrcTy.addConst();
2813 SrcTy = C.getPointerType(SrcTy);
2814
2815 FunctionArgList args;
2816 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2817 args.push_back(&dstDecl);
2818 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2819 args.push_back(&srcDecl);
2820
2821 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002822 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2823 FunctionType::ExtInfo(),
2824 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002825
John McCallde5d3c72012-02-17 03:33:10 +00002826 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002827
2828 llvm::Function *Fn =
2829 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002830 "__assign_helper_atomic_property_",
2831 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002832
2833 if (CGM.getModuleDebugInfo())
2834 DebugInfo = CGM.getModuleDebugInfo();
2835
2836
2837 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2838
John McCallf4b88a42012-03-10 09:33:50 +00002839 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2840 VK_RValue, SourceLocation());
2841 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2842 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002843
John McCallf4b88a42012-03-10 09:33:50 +00002844 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2845 VK_RValue, SourceLocation());
2846 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2847 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002848
John McCallf4b88a42012-03-10 09:33:50 +00002849 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002850 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002851 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002852 Args, DestTy->getPointeeType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00002853 VK_LValue, SourceLocation(), false);
John McCallf4b88a42012-03-10 09:33:50 +00002854
2855 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002856
2857 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002858 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002859 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002860 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002861}
2862
2863llvm::Constant *
2864CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2865 const ObjCPropertyImplDecl *PID) {
2866 // FIXME. This api is for NeXt runtime only for now.
John McCall260611a2012-06-20 06:18:46 +00002867 if (!getLangOpts().CPlusPlus ||
2868 !hasAtomicCopyHelperAPI(getLangOpts().ObjCRuntime))
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002869 return 0;
2870 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2871 QualType Ty = PD->getType();
2872 if (!Ty->isRecordType())
2873 return 0;
2874 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2875 return 0;
2876 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002877
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002878 if (hasTrivialGetExpr(PID))
2879 return 0;
2880 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2881 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2882 return HelperFn;
2883
2884
2885 ASTContext &C = getContext();
2886 IdentifierInfo *II
2887 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2888 FunctionDecl *FD = FunctionDecl::Create(C,
2889 C.getTranslationUnitDecl(),
2890 SourceLocation(),
2891 SourceLocation(), II, C.VoidTy, 0,
2892 SC_Static,
2893 SC_None,
2894 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002895 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002896
2897 QualType DestTy = C.getPointerType(Ty);
2898 QualType SrcTy = Ty;
2899 SrcTy.addConst();
2900 SrcTy = C.getPointerType(SrcTy);
2901
2902 FunctionArgList args;
2903 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2904 args.push_back(&dstDecl);
2905 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2906 args.push_back(&srcDecl);
2907
2908 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002909 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2910 FunctionType::ExtInfo(),
2911 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002912
John McCallde5d3c72012-02-17 03:33:10 +00002913 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002914
2915 llvm::Function *Fn =
2916 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2917 "__copy_helper_atomic_property_", &CGM.getModule());
2918
2919 if (CGM.getModuleDebugInfo())
2920 DebugInfo = CGM.getModuleDebugInfo();
2921
2922
2923 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2924
John McCallf4b88a42012-03-10 09:33:50 +00002925 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002926 VK_RValue, SourceLocation());
2927
John McCallf4b88a42012-03-10 09:33:50 +00002928 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2929 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002930
2931 CXXConstructExpr *CXXConstExpr =
2932 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2933
2934 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002935 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002936 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2937 ++A;
2938
2939 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2940 A != AEnd; ++A)
2941 ConstructorArgs.push_back(*A);
2942
2943 CXXConstructExpr *TheCXXConstructExpr =
2944 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2945 CXXConstExpr->getConstructor(),
2946 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002947 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002948 CXXConstExpr->hadMultipleCandidates(),
2949 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002950 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00002951 CXXConstExpr->getConstructionKind(),
2952 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002953
John McCallf4b88a42012-03-10 09:33:50 +00002954 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2955 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002956
John McCallf4b88a42012-03-10 09:33:50 +00002957 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00002958 CharUnits Alignment
2959 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002960 EmitAggExpr(TheCXXConstructExpr,
2961 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2962 AggValueSlot::IsDestructed,
2963 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00002964 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002965
2966 FinishFunction();
2967 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2968 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2969 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002970}
2971
Eli Friedmancae40c42012-02-28 01:08:45 +00002972llvm::Value *
2973CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2974 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002975 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2976 Selector CopySelector =
2977 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00002978 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2979 Selector AutoreleaseSelector =
2980 getContext().Selectors.getNullarySelector(AutoreleaseID);
2981
2982 // Emit calls to retain/autorelease.
2983 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2984 llvm::Value *Val = Block;
2985 RValue Result;
2986 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002987 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00002988 Val, CallArgList(), 0, 0);
2989 Val = Result.getScalarVal();
2990 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2991 Ty, AutoreleaseSelector,
2992 Val, CallArgList(), 0, 0);
2993 Val = Result.getScalarVal();
2994 return Val;
2995}
2996
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002997
Ted Kremenek2979ec72008-04-09 15:51:31 +00002998CGObjCRuntime::~CGObjCRuntime() {}