blob: 164df93e3140edc5cdb875c1530c1e3a1786e943 [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremeneke65b0862012-03-06 20:05:56 +000034static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +000035 QualType ET,
Ted Kremeneke65b0862012-03-06 20:05:56 +000036 const ObjCMethodDecl *Method,
37 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000038
39/// Given the address of a variable of pointer type, find the correct
40/// null to store into it.
41static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2192fe52011-07-18 04:24:23 +000042 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000043 cast<llvm::PointerType>(addr->getType())->getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
Chris Lattnerb1d329d2008-06-24 17:04:18 +000047/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000048llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000049{
David Chisnall481e3a82010-01-23 02:40:42 +000050 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000052 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000053 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000054}
55
Patrick Beard0caa3942012-04-19 00:25:12 +000056/// EmitObjCBoxedExpr - This routine generates code to call
57/// the appropriate expression boxing method. This will either be
58/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000059///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000060llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000061CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Generate the correct selector for this literal's concrete type.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const Expr *SubExpr = E->getSubExpr();
Ted Kremeneke65b0862012-03-06 20:05:56 +000064 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000065 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
66 assert(BoxingMethod && "BoxingMethod is null");
67 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
68 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000069
70 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000071 // Assumes that the method was introduced in the class that should be
72 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000073 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000074 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000075 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Patrick Beard0caa3942012-04-19 00:25:12 +000076
77 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremeneke65b0862012-03-06 20:05:56 +000078 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beard0caa3942012-04-19 00:25:12 +000079 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremeneke65b0862012-03-06 20:05:56 +000080 CallArgList Args;
81 Args.add(RV, ArgQT);
Alp Toker314cc812014-01-25 16:55:45 +000082
83 RValue result = Runtime.GenerateMessageSend(
84 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
85 Args, ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +000086 return Builder.CreateBitCast(result.getScalarVal(),
87 ConvertType(E->getType()));
88}
89
90llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian413297c2014-08-06 18:13:46 +000091 const ObjCMethodDecl *MethodWithObjects,
92 const ObjCMethodDecl *AllocMethod) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000093 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +000094 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +000095 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
96 if (!ALE)
97 DLE = cast<ObjCDictionaryLiteral>(E);
98
99 // Compute the type of the array we're initializing.
100 uint64_t NumElements =
101 ALE ? ALE->getNumElements() : DLE->getNumElements();
102 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
103 NumElements);
104 QualType ElementType = Context.getObjCIdType().withConst();
105 QualType ElementArrayType
106 = Context.getConstantArrayType(ElementType, APNumElements,
107 ArrayType::Normal, /*IndexTypeQuals=*/0);
108
109 // Allocate the temporary array(s).
Craig Topper8a13c412014-05-21 05:09:00 +0000110 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
111 llvm::Value *Keys = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000112 if (DLE)
113 Keys = CreateMemTemp(ElementArrayType, "keys");
114
John McCall770a4c12013-04-04 00:20:38 +0000115 // In ARC, we may need to do extra work to keep all the keys and
116 // values alive until after the call.
117 SmallVector<llvm::Value *, 16> NeededObjects;
118 bool TrackNeededObjects =
119 (getLangOpts().ObjCAutoRefCount &&
120 CGM.getCodeGenOpts().OptimizationLevel != 0);
121
Ted Kremeneke65b0862012-03-06 20:05:56 +0000122 // Perform the actual initialialization of the array(s).
123 for (uint64_t i = 0; i < NumElements; i++) {
124 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000125 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000126 const Expr *Rhs = ALE->getElement(i);
127 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
128 ElementType,
129 Context.getTypeAlignInChars(Rhs->getType()),
130 Context);
John McCall770a4c12013-04-04 00:20:38 +0000131
132 llvm::Value *value = EmitScalarExpr(Rhs);
133 EmitStoreThroughLValue(RValue::get(value), LV, true);
134 if (TrackNeededObjects) {
135 NeededObjects.push_back(value);
136 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000137 } else {
John McCall770a4c12013-04-04 00:20:38 +0000138 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000139 const Expr *Key = DLE->getKeyValueElement(i).Key;
140 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
141 ElementType,
142 Context.getTypeAlignInChars(Key->getType()),
143 Context);
John McCall770a4c12013-04-04 00:20:38 +0000144 llvm::Value *keyValue = EmitScalarExpr(Key);
145 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000146
John McCall770a4c12013-04-04 00:20:38 +0000147 // Emit the value and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 const Expr *Value = DLE->getKeyValueElement(i).Value;
149 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
150 ElementType,
151 Context.getTypeAlignInChars(Value->getType()),
152 Context);
John McCall770a4c12013-04-04 00:20:38 +0000153 llvm::Value *valueValue = EmitScalarExpr(Value);
154 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
155 if (TrackNeededObjects) {
156 NeededObjects.push_back(keyValue);
157 NeededObjects.push_back(valueValue);
158 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000159 }
160 }
161
162 // Generate the argument list.
163 CallArgList Args;
164 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
165 const ParmVarDecl *argDecl = *PI++;
166 QualType ArgQT = argDecl->getType().getUnqualifiedType();
167 Args.add(RValue::get(Objects), ArgQT);
168 if (DLE) {
169 argDecl = *PI++;
170 ArgQT = argDecl->getType().getUnqualifiedType();
171 Args.add(RValue::get(Keys), ArgQT);
172 }
173 argDecl = *PI;
174 ArgQT = argDecl->getType().getUnqualifiedType();
175 llvm::Value *Count =
176 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
177 Args.add(RValue::get(Count), ArgQT);
178
179 // Generate a reference to the class pointer, which will be the receiver.
180 Selector Sel = MethodWithObjects->getSelector();
181 QualType ResultType = E->getType();
182 const ObjCObjectPointerType *InterfacePointerType
183 = ResultType->getAsObjCInterfacePointerType();
184 ObjCInterfaceDecl *Class
185 = InterfacePointerType->getObjectType()->getInterface();
186 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000187 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000188 if (AllocMethod) {
189 // Generate the "alloc" message send.
190 CallArgList Args;
191 Selector AllocMethodSel = AllocMethod->getSelector();
192 RValue result = Runtime.GenerateMessageSend(
193 *this, ReturnValueSlot(), AllocMethod->getReturnType(), AllocMethodSel,
194 Receiver, Args, Class, AllocMethod);
195 Receiver = result.getScalarVal();
196 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000197
198 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000199 RValue result = Runtime.GenerateMessageSend(
200 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
201 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000202
203 // The above message send needs these objects, but in ARC they are
204 // passed in a buffer that is essentially __unsafe_unretained.
205 // Therefore we must prevent the optimizer from releasing them until
206 // after the call.
207 if (TrackNeededObjects) {
208 EmitARCIntrinsicUse(NeededObjects);
209 }
210
Ted Kremeneke65b0862012-03-06 20:05:56 +0000211 return Builder.CreateBitCast(result.getScalarVal(),
212 ConvertType(E->getType()));
213}
214
215llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian413297c2014-08-06 18:13:46 +0000216 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod(),
217 E->getArrayAllocMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000218}
219
220llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
221 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian413297c2014-08-06 18:13:46 +0000222 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod(),
223 E->getDictAllocMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000224}
225
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000226/// Emit a selector.
227llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
228 // Untyped selector.
229 // Note that this implementation allows for non-constant strings to be passed
230 // as arguments to @selector(). Currently, the only thing preventing this
231 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000232 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000233}
234
Daniel Dunbar66912a12008-08-20 00:28:19 +0000235llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
236 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000237 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000238}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000239
Douglas Gregor33823722011-06-11 01:09:30 +0000240/// \brief Adjust the type of the result of an Objective-C message send
241/// expression when the method has a related result type.
242static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000243 QualType ExpT,
Douglas Gregor33823722011-06-11 01:09:30 +0000244 const ObjCMethodDecl *Method,
245 RValue Result) {
246 if (!Method)
247 return Result;
John McCall31168b02011-06-15 23:02:42 +0000248
Douglas Gregor33823722011-06-11 01:09:30 +0000249 if (!Method->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +0000250 CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
Douglas Gregor33823722011-06-11 01:09:30 +0000251 !Result.isScalar())
252 return Result;
253
254 // We have applied a related result type. Cast the rvalue appropriately.
255 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000256 CGF.ConvertType(ExpT)));
Douglas Gregor33823722011-06-11 01:09:30 +0000257}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000258
John McCallcf166702011-07-22 08:53:00 +0000259/// Decide whether to extend the lifetime of the receiver of a
260/// returns-inner-pointer message.
261static bool
262shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
263 switch (message->getReceiverKind()) {
264
265 // For a normal instance message, we should extend unless the
266 // receiver is loaded from a variable with precise lifetime.
267 case ObjCMessageExpr::Instance: {
268 const Expr *receiver = message->getInstanceReceiver();
269 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
270 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
271 receiver = ice->getSubExpr()->IgnoreParens();
272
273 // Only __strong variables.
274 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
275 return true;
276
277 // All ivars and fields have precise lifetime.
278 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
279 return false;
280
281 // Otherwise, check for variables.
282 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
283 if (!declRef) return true;
284 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
285 if (!var) return true;
286
287 // All variables have precise lifetime except local variables with
288 // automatic storage duration that aren't specially marked.
289 return (var->hasLocalStorage() &&
290 !var->hasAttr<ObjCPreciseLifetimeAttr>());
291 }
292
293 case ObjCMessageExpr::Class:
294 case ObjCMessageExpr::SuperClass:
295 // It's never necessary for class objects.
296 return false;
297
298 case ObjCMessageExpr::SuperInstance:
299 // We generally assume that 'self' lives throughout a method call.
300 return false;
301 }
302
303 llvm_unreachable("invalid receiver kind");
304}
305
John McCall78a15112010-05-22 01:48:05 +0000306RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
307 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000308 // Only the lookup mechanism and first two arguments of the method
309 // implementation vary between runtimes. We can get the receiver and
310 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000311
John McCall31168b02011-06-15 23:02:42 +0000312 bool isDelegateInit = E->isDelegateInitCall();
313
John McCallcf166702011-07-22 08:53:00 +0000314 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000315
John McCall31168b02011-06-15 23:02:42 +0000316 // We don't retain the receiver in delegate init calls, and this is
317 // safe because the receiver value is always loaded from 'self',
318 // which we zero out. We don't want to Block_copy block receivers,
319 // though.
320 bool retainSelf =
321 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000322 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000323 method &&
324 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000325
Daniel Dunbar8d480592008-08-11 18:12:00 +0000326 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000327 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000328 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000329 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000330 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000331 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000332 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000333 switch (E->getReceiverKind()) {
334 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000335 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000336 if (retainSelf) {
337 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
338 E->getInstanceReceiver());
339 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000340 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000341 } else
342 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000343 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000344
Douglas Gregor9a129192010-04-21 00:45:42 +0000345 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000346 ReceiverType = E->getClassReceiver();
347 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000348 assert(ObjTy && "Invalid Objective-C class message send");
349 OID = ObjTy->getInterface();
350 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000351 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000352 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000353 break;
354 }
355
356 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000357 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000358 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000359 isSuperMessage = true;
360 break;
361
362 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000363 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000364 Receiver = LoadObjCSelf();
365 isSuperMessage = true;
366 isClassMessage = true;
367 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000368 }
369
John McCallcf166702011-07-22 08:53:00 +0000370 if (retainSelf)
371 Receiver = EmitARCRetainNonBlock(Receiver);
372
373 // In ARC, we sometimes want to "extend the lifetime"
374 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
375 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000376 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000377 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
378 shouldExtendReceiverForInnerPointerMessage(E))
379 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
380
Alp Toker314cc812014-01-25 16:55:45 +0000381 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000382
Daniel Dunbarc722b852008-08-30 03:02:31 +0000383 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000384 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000385
John McCall31168b02011-06-15 23:02:42 +0000386 // For delegate init calls in ARC, do an unsafe store of null into
387 // self. This represents the call taking direct ownership of that
388 // value. We have to do this after emitting the other call
389 // arguments because they might also reference self, but we don't
390 // have to worry about any of them modifying self because that would
391 // be an undefined read and write of an object in unordered
392 // expressions.
393 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000394 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000395 "delegate init calls should only be marked in ARC");
396
397 // Do an unsafe store of null into self.
398 llvm::Value *selfAddr =
399 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
400 assert(selfAddr && "no self entry for a delegate init call?");
401
402 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
403 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000404
Douglas Gregor33823722011-06-11 01:09:30 +0000405 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000406 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000407 // super is only valid in an Objective-C method
408 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000409 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000410 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
411 E->getSelector(),
412 OMD->getClassInterface(),
413 isCategoryImpl,
414 Receiver,
415 isClassMessage,
416 Args,
John McCallcf166702011-07-22 08:53:00 +0000417 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000418 } else {
419 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
420 E->getSelector(),
421 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000422 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000423 }
John McCall31168b02011-06-15 23:02:42 +0000424
425 // For delegate init calls in ARC, implicitly store the result of
426 // the call back into self. This takes ownership of the value.
427 if (isDelegateInit) {
428 llvm::Value *selfAddr =
429 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
430 llvm::Value *newSelf = result.getScalarVal();
431
432 // The delegate return type isn't necessarily a matching type; in
433 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000434 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000435 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
436 newSelf = Builder.CreateBitCast(newSelf, selfTy);
437
438 Builder.CreateStore(newSelf, selfAddr);
439 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000440
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000441 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000442}
443
John McCall31168b02011-06-15 23:02:42 +0000444namespace {
445struct FinishARCDealloc : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000446 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000447 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000448
449 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000450 const ObjCInterfaceDecl *iface = impl->getClassInterface();
451 if (!iface->getSuperClass()) return;
452
John McCalldffafde2011-07-13 18:26:47 +0000453 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
454
John McCall31168b02011-06-15 23:02:42 +0000455 // Call [super dealloc] if we have a superclass.
456 llvm::Value *self = CGF.LoadObjCSelf();
457
458 CallArgList args;
459 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
460 CGF.getContext().VoidTy,
461 method->getSelector(),
462 iface,
John McCalldffafde2011-07-13 18:26:47 +0000463 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000464 self,
465 /*is class msg*/ false,
466 args,
467 method);
468 }
469};
470}
471
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000472/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
473/// the LLVM function and sets the other context used by
474/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000475void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000476 const ObjCContainerDecl *CD,
477 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000478 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000479 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000480 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000481 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000482
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000483 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000484
John McCalla729c622012-02-17 03:33:10 +0000485 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000486 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000487
John McCalla738c252011-03-09 04:27:21 +0000488 args.push_back(OMD->getSelfDecl());
489 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000490
Aaron Ballman43b68be2014-03-07 17:50:17 +0000491 for (const auto *PI : OMD->params())
492 args.push_back(PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000493
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000494 CurGD = OMD;
495
Adrian Prantl42d71b92014-04-10 23:21:53 +0000496 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
497 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000498
499 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000500 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000501 OMD->isInstanceMethod() &&
502 OMD->getSelector().isUnarySelector()) {
503 const IdentifierInfo *ident =
504 OMD->getSelector().getIdentifierInfoForSlot(0);
505 if (ident->isStr("dealloc"))
506 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
507 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000508}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000509
John McCall31168b02011-06-15 23:02:42 +0000510static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
511 LValue lvalue, QualType type);
512
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000513/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000514/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000515void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000516 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000517 PGO.assignRegionCounters(OMD, CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000518 assert(isa<CompoundStmt>(OMD->getBody()));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000519 RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
520 Cnt.beginRegion(Builder);
Adrian Prantl56741e22014-01-07 22:05:55 +0000521 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000522 FinishFunction(OMD->getBodyRBrace());
Duncan P. N. Exon Smith2fe531c2014-03-17 21:18:30 +0000523 PGO.emitInstrumentationData();
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000524 PGO.destroyRegionCounters();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000525}
526
John McCallb923ece2011-09-12 23:06:44 +0000527/// emitStructGetterCall - Call the runtime function to load a property
528/// into the return value slot.
529static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
530 bool isAtomic, bool hasStrong) {
531 ASTContext &Context = CGF.getContext();
532
533 llvm::Value *src =
534 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
535 ivar, 0).getAddress();
536
537 // objc_copyStruct (ReturnValue, &structIvar,
538 // sizeof (Type of Ivar), isAtomic, false);
539 CallArgList args;
540
541 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
542 args.add(RValue::get(dest), Context.VoidPtrTy);
543
544 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
545 args.add(RValue::get(src), Context.VoidPtrTy);
546
547 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
548 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
549 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
550 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
551
552 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000553 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
554 FunctionType::ExtInfo(),
555 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000556 fn, ReturnValueSlot(), args);
557}
558
John McCallf4528ae2011-09-13 03:34:09 +0000559/// Determine whether the given architecture supports unaligned atomic
560/// accesses. They don't have to be fast, just faster than a function
561/// call and a mutex.
562static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000563 // FIXME: Allow unaligned atomic load/store on x86. (It is not
564 // currently supported by the backend.)
565 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000566}
567
568/// Return the maximum size that permits atomic accesses for the given
569/// architecture.
570static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
571 llvm::Triple::ArchType arch) {
572 // ARM has 8-byte atomic accesses, but it's not clear whether we
573 // want to rely on them here.
574
575 // In the default case, just assume that any size up to a pointer is
576 // fine given adequate alignment.
577 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
578}
579
580namespace {
581 class PropertyImplStrategy {
582 public:
583 enum StrategyKind {
584 /// The 'native' strategy is to use the architecture's provided
585 /// reads and writes.
586 Native,
587
588 /// Use objc_setProperty and objc_getProperty.
589 GetSetProperty,
590
591 /// Use objc_setProperty for the setter, but use expression
592 /// evaluation for the getter.
593 SetPropertyAndExpressionGet,
594
595 /// Use objc_copyStruct.
596 CopyStruct,
597
598 /// The 'expression' strategy is to emit normal assignment or
599 /// lvalue-to-rvalue expressions.
600 Expression
601 };
602
603 StrategyKind getKind() const { return StrategyKind(Kind); }
604
605 bool hasStrongMember() const { return HasStrong; }
606 bool isAtomic() const { return IsAtomic; }
607 bool isCopy() const { return IsCopy; }
608
609 CharUnits getIvarSize() const { return IvarSize; }
610 CharUnits getIvarAlignment() const { return IvarAlignment; }
611
612 PropertyImplStrategy(CodeGenModule &CGM,
613 const ObjCPropertyImplDecl *propImpl);
614
615 private:
616 unsigned Kind : 8;
617 unsigned IsAtomic : 1;
618 unsigned IsCopy : 1;
619 unsigned HasStrong : 1;
620
621 CharUnits IvarSize;
622 CharUnits IvarAlignment;
623 };
624}
625
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000626/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000627PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
628 const ObjCPropertyImplDecl *propImpl) {
629 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000630 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000631
John McCall43192862011-09-13 18:31:23 +0000632 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
633 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000634 HasStrong = false; // doesn't matter here.
635
636 // Evaluate the ivar's size and alignment.
637 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
638 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000639 std::tie(IvarSize, IvarAlignment) =
640 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000641
642 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000643 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000644 if (IsCopy) {
645 Kind = GetSetProperty;
646 return;
647 }
648
John McCall43192862011-09-13 18:31:23 +0000649 // Handle retain.
650 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000651 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000652 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000653 // fallthrough
654
655 // In ARC, if the property is non-atomic, use expression emission,
656 // which translates to objc_storeStrong. This isn't required, but
657 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000658 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000659 // Using standard expression emission for the setter is only
660 // acceptable if the ivar is __strong, which won't be true if
661 // the property is annotated with __attribute__((NSObject)).
662 // TODO: falling all the way back to objc_setProperty here is
663 // just laziness, though; we could still use objc_storeStrong
664 // if we hacked it right.
665 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
666 Kind = Expression;
667 else
668 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000669 return;
670
671 // Otherwise, we need to at least use setProperty. However, if
672 // the property isn't atomic, we can use normal expression
673 // emission for the getter.
674 } else if (!IsAtomic) {
675 Kind = SetPropertyAndExpressionGet;
676 return;
677
678 // Otherwise, we have to use both setProperty and getProperty.
679 } else {
680 Kind = GetSetProperty;
681 return;
682 }
683 }
684
685 // If we're not atomic, just use expression accesses.
686 if (!IsAtomic) {
687 Kind = Expression;
688 return;
689 }
690
John McCall0e5c0862011-09-13 05:36:29 +0000691 // Properties on bitfield ivars need to be emitted using expression
692 // accesses even if they're nominally atomic.
693 if (ivar->isBitField()) {
694 Kind = Expression;
695 return;
696 }
697
John McCallf4528ae2011-09-13 03:34:09 +0000698 // GC-qualified or ARC-qualified ivars need to be emitted as
699 // expressions. This actually works out to being atomic anyway,
700 // except for ARC __strong, but that should trigger the above code.
701 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000702 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000703 CGM.getContext().getObjCGCAttrKind(ivarType))) {
704 Kind = Expression;
705 return;
706 }
707
708 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000709 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000710 if (const RecordType *recordType = ivarType->getAs<RecordType>())
711 HasStrong = recordType->getDecl()->hasObjectMember();
712
713 // We can never access structs with object members with a native
714 // access, because we need to use write barriers. This is what
715 // objc_copyStruct is for.
716 if (HasStrong) {
717 Kind = CopyStruct;
718 return;
719 }
720
721 // Otherwise, this is target-dependent and based on the size and
722 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000723
724 // If the size of the ivar is not a power of two, give up. We don't
725 // want to get into the business of doing compare-and-swaps.
726 if (!IvarSize.isPowerOfTwo()) {
727 Kind = CopyStruct;
728 return;
729 }
730
John McCallf4528ae2011-09-13 03:34:09 +0000731 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000732 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000733
734 // Most architectures require memory to fit within a single cache
735 // line, so the alignment has to be at least the size of the access.
736 // Otherwise we have to grab a lock.
737 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
738 Kind = CopyStruct;
739 return;
740 }
741
742 // If the ivar's size exceeds the architecture's maximum atomic
743 // access size, we have to use CopyStruct.
744 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
745 Kind = CopyStruct;
746 return;
747 }
748
749 // Otherwise, we can use native loads and stores.
750 Kind = Native;
751}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000752
James Dennettbe302452012-06-15 22:10:14 +0000753/// \brief Generate an Objective-C property getter function.
754///
755/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000756/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000757void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
758 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000759 llvm::Constant *AtomicHelperFn =
760 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000761 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
762 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
763 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +0000764 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000765
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000766 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000767
768 FinishFunction();
769}
770
John McCallbdd81852011-09-13 06:00:03 +0000771static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
772 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000773 if (!getter) return true;
774
775 // Sema only makes only of these when the ivar has a C++ class type,
776 // so the form is pretty constrained.
777
John McCallbdd81852011-09-13 06:00:03 +0000778 // If the property has a reference type, we might just be binding a
779 // reference, in which case the result will be a gl-value. We should
780 // treat this as a non-trivial operation.
781 if (getter->isGLValue())
782 return false;
783
John McCallf4528ae2011-09-13 03:34:09 +0000784 // If we selected a trivial copy-constructor, we're okay.
785 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
786 return (construct->getConstructor()->isTrivial());
787
788 // The constructor might require cleanups (in which case it's never
789 // trivial).
790 assert(isa<ExprWithCleanups>(getter));
791 return false;
792}
793
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000794/// emitCPPObjectAtomicGetterCall - Call the runtime function to
795/// copy the ivar into the resturn slot.
796static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
797 llvm::Value *returnAddr,
798 ObjCIvarDecl *ivar,
799 llvm::Constant *AtomicHelperFn) {
800 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
801 // AtomicHelperFn);
802 CallArgList args;
803
804 // The 1st argument is the return Slot.
805 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
806
807 // The 2nd argument is the address of the ivar.
808 llvm::Value *ivarAddr =
809 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
810 CGF.LoadObjCSelf(), ivar, 0).getAddress();
811 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
812 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
813
814 // Third argument is the helper function.
815 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
816
817 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000818 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000819 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
820 args,
821 FunctionType::ExtInfo(),
822 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000823 copyCppAtomicObjectFn, ReturnValueSlot(), args);
824}
825
John McCallf4528ae2011-09-13 03:34:09 +0000826void
827CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000828 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000829 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000830 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000831 // If there's a non-trivial 'get' expression, we just have to emit that.
832 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000833 if (!AtomicHelperFn) {
834 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000835 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000836 EmitReturnStmt(ret);
837 }
838 else {
839 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
840 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
841 ivar, AtomicHelperFn);
842 }
John McCallf4528ae2011-09-13 03:34:09 +0000843 return;
844 }
845
846 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
847 QualType propType = prop->getType();
848 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
849
850 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
851
852 // Pick an implementation strategy.
853 PropertyImplStrategy strategy(CGM, propImpl);
854 switch (strategy.getKind()) {
855 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000856 // We don't need to do anything for a zero-size struct.
857 if (strategy.getIvarSize().isZero())
858 return;
859
John McCallf4528ae2011-09-13 03:34:09 +0000860 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
861
862 // Currently, all atomic accesses have to be through integer
863 // types, so there's no point in trying to pick a prettier type.
864 llvm::Type *bitcastType =
865 llvm::Type::getIntNTy(getLLVMContext(),
866 getContext().toBits(strategy.getIvarSize()));
867 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
868
869 // Perform an atomic load. This does not impose ordering constraints.
870 llvm::Value *ivarAddr = LV.getAddress();
871 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
872 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
873 load->setAlignment(strategy.getIvarAlignment().getQuantity());
874 load->setAtomic(llvm::Unordered);
875
876 // Store that value into the return address. Doing this with a
877 // bitcast is likely to produce some pretty ugly IR, but it's not
878 // the *most* terrible thing in the world.
879 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
880
881 // Make sure we don't do an autorelease.
882 AutoreleaseResult = false;
883 return;
884 }
885
886 case PropertyImplStrategy::GetSetProperty: {
887 llvm::Value *getPropertyFn =
888 CGM.getObjCRuntime().GetPropertyGetFunction();
889 if (!getPropertyFn) {
890 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000891 return;
892 }
893
894 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
895 // FIXME: Can't this be simpler? This might even be worse than the
896 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000897 llvm::Value *cmd =
898 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
899 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
900 llvm::Value *ivarOffset =
901 EmitIvarOffset(classImpl->getClassInterface(), ivar);
902
903 CallArgList args;
904 args.add(RValue::get(self), getContext().getObjCIdType());
905 args.add(RValue::get(cmd), getContext().getObjCSelType());
906 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000907 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
908 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000909
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000910 // FIXME: We shouldn't need to get the function info here, the
911 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000912 llvm::Instruction *CallInstruction;
John McCall8dda7b22012-07-07 06:41:13 +0000913 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
914 FunctionType::ExtInfo(),
915 RequiredArgs::All),
Craig Topper8a13c412014-05-21 05:09:00 +0000916 getPropertyFn, ReturnValueSlot(), args, nullptr,
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000917 &CallInstruction);
918 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
919 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000920
Daniel Dunbara08dff12008-09-24 04:04:31 +0000921 // We need to fix the type here. Ivars with copy & retain are
922 // always objects so we don't need to worry about complex or
923 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000924 RV = RValue::get(Builder.CreateBitCast(
925 RV.getScalarVal(),
926 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000927
928 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000929
930 // objc_getProperty does an autorelease, so we should suppress ours.
931 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000932
John McCallf4528ae2011-09-13 03:34:09 +0000933 return;
934 }
935
936 case PropertyImplStrategy::CopyStruct:
937 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
938 strategy.hasStrongMember());
939 return;
940
941 case PropertyImplStrategy::Expression:
942 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
943 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
944
945 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000946 switch (getEvaluationKind(ivarType)) {
947 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000948 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall47fb9502013-03-07 21:37:08 +0000949 EmitStoreOfComplex(pair,
950 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
951 /*init*/ true);
952 return;
953 }
954 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000955 // The return value slot is guaranteed to not be aliased, but
956 // that's not necessarily the same as "on the stack", so
957 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000958 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000959 return;
960 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000961 llvm::Value *value;
962 if (propType->isReferenceType()) {
963 value = LV.getAddress();
964 } else {
965 // We want to load and autoreleaseReturnValue ARC __weak ivars.
966 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000967 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000968
969 // Otherwise we want to do a simple load, suppressing the
970 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000971 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000972 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000973 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000974 }
John McCall31168b02011-06-15 23:02:42 +0000975
John McCall24fada12011-07-22 05:23:13 +0000976 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +0000977 value = Builder.CreateBitCast(
978 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +0000979 }
980
981 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000982 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000983 }
John McCall47fb9502013-03-07 21:37:08 +0000984 }
985 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000986 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000987
John McCallf4528ae2011-09-13 03:34:09 +0000988 }
989 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000990}
991
John McCallb923ece2011-09-12 23:06:44 +0000992/// emitStructSetterCall - Call the runtime function to store the value
993/// from the first formal parameter into the given ivar.
994static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
995 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000996 // objc_copyStruct (&structIvar, &Arg,
997 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000998 CallArgList args;
999
1000 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001001 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1002 CGF.LoadObjCSelf(), ivar, 0)
1003 .getAddress();
1004 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1005 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001006
1007 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001008 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001009 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +00001010 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +00001011 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1012 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1013 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001014
1015 // The third argument is the sizeof the type.
1016 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001017 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1018 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001019
John McCallb923ece2011-09-12 23:06:44 +00001020 // The fourth argument is the 'isAtomic' flag.
1021 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001022
John McCallb923ece2011-09-12 23:06:44 +00001023 // The fifth argument is the 'hasStrong' flag.
1024 // FIXME: should this really always be false?
1025 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1026
1027 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001028 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1029 args,
1030 FunctionType::ExtInfo(),
1031 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001032 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001033}
1034
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001035/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1036/// the value from the first formal parameter into the given ivar, using
1037/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1038static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1039 ObjCMethodDecl *OMD,
1040 ObjCIvarDecl *ivar,
1041 llvm::Constant *AtomicHelperFn) {
1042 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1043 // AtomicHelperFn);
1044 CallArgList args;
1045
1046 // The first argument is the address of the ivar.
1047 llvm::Value *ivarAddr =
1048 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1049 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1050 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1051 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1052
1053 // The second argument is the address of the parameter variable.
1054 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001055 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001056 VK_LValue, SourceLocation());
1057 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1058 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1059 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1060
1061 // Third argument is the helper function.
1062 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1063
1064 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001065 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001066 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1067 args,
1068 FunctionType::ExtInfo(),
1069 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001070 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001071}
1072
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001073
John McCallf4528ae2011-09-13 03:34:09 +00001074static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1075 Expr *setter = PID->getSetterCXXAssignment();
1076 if (!setter) return true;
1077
1078 // Sema only makes only of these when the ivar has a C++ class type,
1079 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001080
1081 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001082 // This also implies that there's nothing non-trivial going on with
1083 // the arguments, because operator= can only be trivial if it's a
1084 // synthesized assignment operator and therefore both parameters are
1085 // references.
1086 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001087 if (const FunctionDecl *callee
1088 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1089 if (callee->isTrivial())
1090 return true;
1091 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001092 }
John McCall7f16c422011-09-10 09:17:20 +00001093
John McCallf4528ae2011-09-13 03:34:09 +00001094 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001095 return false;
1096}
1097
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001098static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001099 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001100 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001101 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001102}
1103
John McCall7f16c422011-09-10 09:17:20 +00001104void
1105CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001106 const ObjCPropertyImplDecl *propImpl,
1107 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001108 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001109 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001110 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001111
1112 // Just use the setter expression if Sema gave us one and it's
1113 // non-trivial.
1114 if (!hasTrivialSetExpr(propImpl)) {
1115 if (!AtomicHelperFn)
1116 // If non-atomic, assignment is called directly.
1117 EmitStmt(propImpl->getSetterCXXAssignment());
1118 else
1119 // If atomic, assignment is called via a locking api.
1120 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1121 AtomicHelperFn);
1122 return;
1123 }
John McCall7f16c422011-09-10 09:17:20 +00001124
John McCallf4528ae2011-09-13 03:34:09 +00001125 PropertyImplStrategy strategy(CGM, propImpl);
1126 switch (strategy.getKind()) {
1127 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001128 // We don't need to do anything for a zero-size struct.
1129 if (strategy.getIvarSize().isZero())
1130 return;
1131
John McCallf4528ae2011-09-13 03:34:09 +00001132 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +00001133
John McCallf4528ae2011-09-13 03:34:09 +00001134 LValue ivarLValue =
1135 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1136 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001137
John McCallf4528ae2011-09-13 03:34:09 +00001138 // Currently, all atomic accesses have to be through integer
1139 // types, so there's no point in trying to pick a prettier type.
1140 llvm::Type *bitcastType =
1141 llvm::Type::getIntNTy(getLLVMContext(),
1142 getContext().toBits(strategy.getIvarSize()));
1143 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1144
1145 // Cast both arguments to the chosen operation type.
1146 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1147 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1148
1149 // This bitcast load is likely to cause some nasty IR.
1150 llvm::Value *load = Builder.CreateLoad(argAddr);
1151
1152 // Perform an atomic store. There are no memory ordering requirements.
1153 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1154 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1155 store->setAtomic(llvm::Unordered);
1156 return;
1157 }
1158
1159 case PropertyImplStrategy::GetSetProperty:
1160 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001161
1162 llvm::Value *setOptimizedPropertyFn = nullptr;
1163 llvm::Value *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001164 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001165 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001166 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001167 CGM.getObjCRuntime()
1168 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1169 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001170 if (!setOptimizedPropertyFn) {
1171 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1172 return;
1173 }
John McCall7f16c422011-09-10 09:17:20 +00001174 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001175 else {
1176 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1177 if (!setPropertyFn) {
1178 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1179 return;
1180 }
1181 }
1182
John McCall7f16c422011-09-10 09:17:20 +00001183 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1184 // <is-atomic>, <is-copy>).
1185 llvm::Value *cmd =
1186 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1187 llvm::Value *self =
1188 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1189 llvm::Value *ivarOffset =
1190 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1191 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1192 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1193
1194 CallArgList args;
1195 args.add(RValue::get(self), getContext().getObjCIdType());
1196 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001197 if (setOptimizedPropertyFn) {
1198 args.add(RValue::get(arg), getContext().getObjCIdType());
1199 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001200 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1201 FunctionType::ExtInfo(),
1202 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001203 setOptimizedPropertyFn, ReturnValueSlot(), args);
1204 } else {
1205 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1206 args.add(RValue::get(arg), getContext().getObjCIdType());
1207 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1208 getContext().BoolTy);
1209 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1210 getContext().BoolTy);
1211 // FIXME: We shouldn't need to get the function info here, the runtime
1212 // already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001213 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1214 FunctionType::ExtInfo(),
1215 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001216 setPropertyFn, ReturnValueSlot(), args);
1217 }
1218
John McCall7f16c422011-09-10 09:17:20 +00001219 return;
1220 }
1221
John McCallf4528ae2011-09-13 03:34:09 +00001222 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001223 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001224 return;
John McCallf4528ae2011-09-13 03:34:09 +00001225
1226 case PropertyImplStrategy::Expression:
1227 break;
John McCall7f16c422011-09-10 09:17:20 +00001228 }
1229
1230 // Otherwise, fake up some ASTs and emit a normal assignment.
1231 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001232 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1233 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001234 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1235 selfDecl->getType(), CK_LValueToRValue, &self,
1236 VK_RValue);
1237 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001238 SourceLocation(), SourceLocation(),
1239 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001240
1241 ParmVarDecl *argDecl = *setterMethod->param_begin();
1242 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001243 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001244 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1245 argType.getUnqualifiedType(), CK_LValueToRValue,
1246 &arg, VK_RValue);
1247
1248 // The property type can differ from the ivar type in some situations with
1249 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1250 // The following absurdity is just to ensure well-formed IR.
1251 CastKind argCK = CK_NoOp;
1252 if (ivarRef.getType()->isObjCObjectPointerType()) {
1253 if (argLoad.getType()->isObjCObjectPointerType())
1254 argCK = CK_BitCast;
1255 else if (argLoad.getType()->isBlockPointerType())
1256 argCK = CK_BlockPointerToObjCPointerCast;
1257 else
1258 argCK = CK_CPointerToObjCPointerCast;
1259 } else if (ivarRef.getType()->isBlockPointerType()) {
1260 if (argLoad.getType()->isBlockPointerType())
1261 argCK = CK_BitCast;
1262 else
1263 argCK = CK_AnyPointerToBlockPointerCast;
1264 } else if (ivarRef.getType()->isPointerType()) {
1265 argCK = CK_BitCast;
1266 }
1267 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1268 ivarRef.getType(), argCK, &argLoad,
1269 VK_RValue);
1270 Expr *finalArg = &argLoad;
1271 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1272 argLoad.getType()))
1273 finalArg = &argCast;
1274
1275
1276 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1277 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001278 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001279 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001280}
1281
James Dennettbe302452012-06-15 22:10:14 +00001282/// \brief Generate an Objective-C property setter function.
1283///
1284/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001285/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001286void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1287 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001288 llvm::Constant *AtomicHelperFn =
1289 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001290 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1291 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1292 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +00001293 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001294
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001295 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001296
1297 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001298}
1299
John McCall6a4fa522011-03-22 07:05:39 +00001300namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001301 struct DestroyIvar : EHScopeStack::Cleanup {
1302 private:
1303 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001304 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001305 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001306 bool useEHCleanupForArray;
1307 public:
1308 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1309 CodeGenFunction::Destroyer *destroyer,
1310 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001311 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001312 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001313
Craig Topper4f12f102014-03-12 06:41:41 +00001314 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001315 LValue lvalue
1316 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1317 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001318 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001319 }
1320 };
1321}
1322
John McCall4bd0fb12011-07-12 16:41:08 +00001323/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1324static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1325 llvm::Value *addr,
1326 QualType type) {
1327 llvm::Value *null = getNullForVariable(addr);
1328 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1329}
John McCall31168b02011-06-15 23:02:42 +00001330
John McCall6a4fa522011-03-22 07:05:39 +00001331static void emitCXXDestructMethod(CodeGenFunction &CGF,
1332 ObjCImplementationDecl *impl) {
1333 CodeGenFunction::RunCleanupsScope scope(CGF);
1334
1335 llvm::Value *self = CGF.LoadObjCSelf();
1336
Jordy Rosea91768e2011-07-22 02:08:32 +00001337 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1338 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001339 ivar; ivar = ivar->getNextIvar()) {
1340 QualType type = ivar->getType();
1341
John McCall6a4fa522011-03-22 07:05:39 +00001342 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001343 QualType::DestructionKind dtorKind = type.isDestructedType();
1344 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001345
Craig Topper8a13c412014-05-21 05:09:00 +00001346 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001347
John McCall4bd0fb12011-07-12 16:41:08 +00001348 // Use a call to objc_storeStrong to destroy strong ivars, for the
1349 // general benefit of the tools.
1350 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001351 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001352
John McCall4bd0fb12011-07-12 16:41:08 +00001353 // Otherwise use the default for the destruction kind.
1354 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001355 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001356 }
John McCall4bd0fb12011-07-12 16:41:08 +00001357
1358 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1359
1360 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1361 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001362 }
1363
1364 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1365}
1366
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001367void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1368 ObjCMethodDecl *MD,
1369 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001370 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001371 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001372
1373 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001374 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001375 // Suppress the final autorelease in ARC.
1376 AutoreleaseResult = false;
1377
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001378 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001379 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001380 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001381 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1382 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001383 EmitAggExpr(IvarInit->getInit(),
1384 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001385 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001386 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001387 }
1388 // constructor returns 'self'.
1389 CodeGenTypes &Types = CGM.getTypes();
1390 QualType IdTy(CGM.getContext().getObjCIdType());
1391 llvm::Value *SelfAsId =
1392 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1393 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001394
1395 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001396 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001397 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001398 }
1399 FinishFunction();
1400}
1401
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001402bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1403 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1404 it++; it++;
1405 const ABIArgInfo &AI = it->info;
1406 // FIXME. Is this sufficient check?
1407 return (AI.getKind() == ABIArgInfo::Indirect);
1408}
1409
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001410bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001411 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001412 return false;
1413 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1414 return FDTTy->getDecl()->hasObjectMember();
1415 return false;
1416}
1417
Daniel Dunbara08dff12008-09-24 04:04:31 +00001418llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001419 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1420 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1421 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001422 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001423}
1424
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001425QualType CodeGenFunction::TypeOfSelfObject() {
1426 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1427 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001428 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1429 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001430 return PTy->getPointeeType();
1431}
1432
Chris Lattnerd4808922009-03-22 21:03:39 +00001433void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001434 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001435 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001436
Daniel Dunbara08dff12008-09-24 04:04:31 +00001437 if (!EnumerationMutationFn) {
1438 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1439 return;
1440 }
1441
Devang Pateld2d66652011-01-19 01:36:36 +00001442 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001443 if (DI)
1444 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001445
Devang Patel297207f2011-06-13 23:15:32 +00001446 // The local variable comes into scope immediately.
1447 AutoVarEmission variable = AutoVarEmission::invalid();
1448 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1449 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1450
John McCall1c926b72011-01-07 01:49:06 +00001451 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001452
Anders Carlsson75658592008-08-31 02:33:12 +00001453 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001454 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001455 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001456 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001457
Anders Carlsson75658592008-08-31 02:33:12 +00001458 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001459 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001460
John McCall1c926b72011-01-07 01:49:06 +00001461 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001462 IdentifierInfo *II[] = {
1463 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1464 &CGM.getContext().Idents.get("objects"),
1465 &CGM.getContext().Idents.get("count")
1466 };
1467 Selector FastEnumSel =
1468 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001469
1470 QualType ItemsTy =
1471 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001472 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001473 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001474 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001475
John McCall53848232011-07-27 01:07:15 +00001476 // Emit the collection pointer. In ARC, we do a retain.
1477 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001478 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001479 Collection = EmitARCRetainScalarExpr(S.getCollection());
1480
1481 // Enter a cleanup to do the release.
1482 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1483 } else {
1484 Collection = EmitScalarExpr(S.getCollection());
1485 }
Mike Stump11289f42009-09-09 15:08:12 +00001486
John McCall91e82dd2011-08-05 00:14:38 +00001487 // The 'continue' label needs to appear within the cleanup for the
1488 // collection object.
1489 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1490
John McCall1c926b72011-01-07 01:49:06 +00001491 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001492 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001493
1494 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001495 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001496
John McCall1c926b72011-01-07 01:49:06 +00001497 // The second argument is a temporary array with space for NumItems
1498 // pointers. We'll actually be loading elements from the array
1499 // pointer written into the control state; this buffer is so that
1500 // collections that *aren't* backed by arrays can still queue up
1501 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001502 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001503
John McCall1c926b72011-01-07 01:49:06 +00001504 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001505 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001506 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001507 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001508
John McCall1c926b72011-01-07 01:49:06 +00001509 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001510 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001511 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001512 getContext().UnsignedLongTy,
1513 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001514 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001515
John McCall1c926b72011-01-07 01:49:06 +00001516 // The initial number of objects that were returned in the buffer.
1517 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001518
John McCall1c926b72011-01-07 01:49:06 +00001519 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1520 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001521
John McCall1c926b72011-01-07 01:49:06 +00001522 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001523
John McCall1c926b72011-01-07 01:49:06 +00001524 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001525 // empty; skip all this. Set the branch weight assuming this has the same
1526 // probability of exiting the loop as any other loop exit.
1527 uint64_t EntryCount = PGO.getCurrentRegionCount();
1528 RegionCounter Cnt = getPGORegionCounter(&S);
John McCall1c926b72011-01-07 01:49:06 +00001529 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001530 EmptyBB, LoopInitBB,
1531 PGO.createBranchWeights(EntryCount, Cnt.getCount()));
Anders Carlsson75658592008-08-31 02:33:12 +00001532
John McCall1c926b72011-01-07 01:49:06 +00001533 // Otherwise, initialize the loop.
1534 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001535
John McCall1c926b72011-01-07 01:49:06 +00001536 // Save the initial mutations value. This is the value at an
1537 // address that was written into the state object by
1538 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001539 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001540 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001541 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001542 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001543
John McCall1c926b72011-01-07 01:49:06 +00001544 llvm::Value *initialMutations =
1545 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001546
John McCall1c926b72011-01-07 01:49:06 +00001547 // Start looping. This is the point we return to whenever we have a
1548 // fresh, non-empty batch of objects.
1549 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1550 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001551
John McCall1c926b72011-01-07 01:49:06 +00001552 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001553 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001554 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001555
John McCall1c926b72011-01-07 01:49:06 +00001556 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001557 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001558 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001559
Bob Wilson8ab16912014-02-24 01:13:09 +00001560 Cnt.beginRegion(Builder);
1561
John McCall1c926b72011-01-07 01:49:06 +00001562 // Check whether the mutations value has changed from where it was
1563 // at start. StateMutationsPtr should actually be invariant between
1564 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001565 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001566 llvm::Value *currentMutations
1567 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001568
John McCall1c926b72011-01-07 01:49:06 +00001569 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001570 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001571
John McCall1c926b72011-01-07 01:49:06 +00001572 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1573 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001574
John McCall1c926b72011-01-07 01:49:06 +00001575 // If so, call the enumeration-mutation function.
1576 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001577 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001578 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001579 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001580 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001581 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001582 // FIXME: We shouldn't need to get the function info here, the runtime already
1583 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001584 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1585 FunctionType::ExtInfo(),
1586 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001587 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001588
John McCall1c926b72011-01-07 01:49:06 +00001589 // Otherwise, or if the mutation function returns, just continue.
1590 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001591
John McCall1c926b72011-01-07 01:49:06 +00001592 // Initialize the element variable.
1593 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001594 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001595 LValue elementLValue;
1596 QualType elementType;
1597 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001598 // Initialize the variable, in case it's a __block variable or something.
1599 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001600
John McCall9e2e22f2011-02-22 07:16:58 +00001601 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001602 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001603 VK_LValue, SourceLocation());
1604 elementLValue = EmitLValue(&tempDRE);
1605 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001606 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001607
1608 if (D->isARCPseudoStrong())
1609 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001610 } else {
1611 elementLValue = LValue(); // suppress warning
1612 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001613 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001614 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001615 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001616
1617 // Fetch the buffer out of the enumeration state.
1618 // TODO: this pointer should actually be invariant between
1619 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001620 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001621 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001622 llvm::Value *EnumStateItems =
1623 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001624
John McCall1c926b72011-01-07 01:49:06 +00001625 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001626 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001627 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1628 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001629
John McCall1c926b72011-01-07 01:49:06 +00001630 // Cast that value to the right type.
1631 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1632 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001633
John McCall1c926b72011-01-07 01:49:06 +00001634 // Make sure we have an l-value. Yes, this gets evaluated every
1635 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001636 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001637 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001638 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001639 } else {
1640 EmitScalarInit(CurrentItem, elementLValue);
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCall9e2e22f2011-02-22 07:16:58 +00001643 // If we do have an element variable, this assignment is the end of
1644 // its initialization.
1645 if (elementIsVariable)
1646 EmitAutoVarCleanups(variable);
1647
John McCall1c926b72011-01-07 01:49:06 +00001648 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001649 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001650 {
1651 RunCleanupsScope Scope(*this);
1652 EmitStmt(S.getBody());
1653 }
Anders Carlsson75658592008-08-31 02:33:12 +00001654 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001655
John McCall1c926b72011-01-07 01:49:06 +00001656 // Destroy the element variable now.
1657 elementVariableScope.ForceCleanup();
1658
1659 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001660 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001661
John McCall1c926b72011-01-07 01:49:06 +00001662 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001663
John McCall1c926b72011-01-07 01:49:06 +00001664 // First we check in the local buffer.
1665 llvm::Value *indexPlusOne
1666 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001667
John McCall1c926b72011-01-07 01:49:06 +00001668 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001669 // Set the branch weights based on the simplifying assumption that this is
1670 // like a while-loop, i.e., ignoring that the false branch fetches more
1671 // elements and then returns to the loop.
John McCall1c926b72011-01-07 01:49:06 +00001672 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001673 LoopBodyBB, FetchMoreBB,
1674 PGO.createBranchWeights(Cnt.getCount(), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001675
1676 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1677 count->addIncoming(count, AfterBody.getBlock());
1678
1679 // Otherwise, we have to fetch more elements.
1680 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001681
1682 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001683 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001684 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001685 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001686 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001687
John McCall1c926b72011-01-07 01:49:06 +00001688 // If we got a zero count, we're done.
1689 llvm::Value *refetchCount = CountRV.getScalarVal();
1690
1691 // (note that the message send might split FetchMoreBB)
1692 index->addIncoming(zero, Builder.GetInsertBlock());
1693 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1694
1695 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1696 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001697
Anders Carlsson75658592008-08-31 02:33:12 +00001698 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001699 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001700
John McCall9e2e22f2011-02-22 07:16:58 +00001701 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001702 // If the element was not a declaration, set it to be null.
1703
John McCall1c926b72011-01-07 01:49:06 +00001704 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1705 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001706 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001707 }
1708
Eric Christopher7cdf9482011-10-13 21:45:18 +00001709 if (DI)
1710 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001711
John McCall53848232011-07-27 01:07:15 +00001712 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001713 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001714 PopCleanupBlock();
1715
John McCallad5d61e2010-07-23 21:56:41 +00001716 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001717}
1718
Mike Stump11289f42009-09-09 15:08:12 +00001719void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001720 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001721}
1722
Mike Stump11289f42009-09-09 15:08:12 +00001723void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001724 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1725}
1726
Chris Lattnere132e242008-11-15 21:26:17 +00001727void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001728 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001729 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001730}
1731
John McCall2d637d22011-09-10 06:18:15 +00001732/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001733/// primitive retain.
1734llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1735 llvm::Value *value) {
1736 return EmitARCRetain(type, value);
1737}
1738
1739namespace {
1740 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001741 CallObjCRelease(llvm::Value *object) : object(object) {}
1742 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001743
Craig Topper4f12f102014-03-12 06:41:41 +00001744 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001745 // Releases at the end of the full-expression are imprecise.
1746 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001747 }
1748 };
1749}
1750
John McCall2d637d22011-09-10 06:18:15 +00001751/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001752/// release at the end of the full-expression.
1753llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1754 llvm::Value *object) {
1755 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001756 // conditional.
1757 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001758 return object;
1759}
1760
1761llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1762 llvm::Value *value) {
1763 return EmitARCRetainAutorelease(type, value);
1764}
1765
John McCalleff18842013-03-23 02:35:54 +00001766/// Given a number of pointers, inform the optimizer that they're
1767/// being intrinsically used up until this point in the program.
1768void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1769 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1770 if (!fn) {
1771 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001772 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001773 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1774 }
1775
1776 // This isn't really a "runtime" function, but as an intrinsic it
1777 // doesn't really matter as long as we align things up.
1778 EmitNounwindRuntimeCall(fn, values);
1779}
1780
John McCall31168b02011-06-15 23:02:42 +00001781
1782static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001783 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001784 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001785 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1786
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001787 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001788 // If the target runtime doesn't naturally support ARC, emit weak
1789 // references to the runtime support library. We don't really
1790 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001791 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001792 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001793 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1794 // If we have Native ARC, set nonlazybind attribute for these APIs for
1795 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001796 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001797 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001798 }
John McCall31168b02011-06-15 23:02:42 +00001799
1800 return fn;
1801}
1802
1803/// Perform an operation having the signature
1804/// i8* (i8*)
1805/// where a null input causes a no-op and returns null.
1806static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1807 llvm::Value *value,
1808 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001809 StringRef fnName,
1810 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001811 if (isa<llvm::ConstantPointerNull>(value)) return value;
1812
1813 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001814 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001815 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001816 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1817 }
1818
1819 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001820 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001821 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1822
1823 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001824 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001825 if (isTailCall)
1826 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001827
1828 // Cast the result back to the original type.
1829 return CGF.Builder.CreateBitCast(call, origType);
1830}
1831
1832/// Perform an operation having the following signature:
1833/// i8* (i8**)
1834static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1835 llvm::Value *addr,
1836 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001837 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001838 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001839 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001840 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001841 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1842 }
1843
1844 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001845 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001846 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1847
1848 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001849 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00001850
1851 // Cast the result back to a dereference of the original type.
John McCall31168b02011-06-15 23:02:42 +00001852 if (origType != CGF.Int8PtrPtrTy)
1853 result = CGF.Builder.CreateBitCast(result,
1854 cast<llvm::PointerType>(origType)->getElementType());
1855
1856 return result;
1857}
1858
1859/// Perform an operation having the following signature:
1860/// i8* (i8**, i8*)
1861static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1862 llvm::Value *addr,
1863 llvm::Value *value,
1864 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001865 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001866 bool ignored) {
1867 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1868 == value->getType());
1869
1870 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001871 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001872
Chris Lattner2192fe52011-07-18 04:24:23 +00001873 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001874 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1875 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1876 }
1877
Chris Lattner2192fe52011-07-18 04:24:23 +00001878 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001879
John McCall882987f2013-02-28 19:01:20 +00001880 llvm::Value *args[] = {
1881 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1882 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1883 };
1884 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001885
Craig Topper8a13c412014-05-21 05:09:00 +00001886 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001887
1888 return CGF.Builder.CreateBitCast(result, origType);
1889}
1890
1891/// Perform an operation having the following signature:
1892/// void (i8**, i8**)
1893static void emitARCCopyOperation(CodeGenFunction &CGF,
1894 llvm::Value *dst,
1895 llvm::Value *src,
1896 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001897 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001898 assert(dst->getType() == src->getType());
1899
1900 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001901 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1902
Chris Lattner2192fe52011-07-18 04:24:23 +00001903 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001904 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1905 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1906 }
1907
John McCall882987f2013-02-28 19:01:20 +00001908 llvm::Value *args[] = {
1909 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1910 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1911 };
1912 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001913}
1914
1915/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001916/// call i8* \@objc_retain(i8* %value)
1917/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001918llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1919 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001920 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001921 else
1922 return EmitARCRetainNonBlock(value);
1923}
1924
1925/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001926/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001927llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1928 return emitARCValueOperation(*this, value,
1929 CGM.getARCEntrypoints().objc_retain,
1930 "objc_retain");
1931}
1932
1933/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001934/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001935///
1936/// \param mandatory - If false, emit the call with metadata
1937/// indicating that it's okay for the optimizer to eliminate this call
1938/// if it can prove that the block never escapes except down the stack.
1939llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1940 bool mandatory) {
1941 llvm::Value *result
1942 = emitARCValueOperation(*this, value,
1943 CGM.getARCEntrypoints().objc_retainBlock,
1944 "objc_retainBlock");
1945
1946 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1947 // tell the optimizer that it doesn't need to do this copy if the
1948 // block doesn't escape, where being passed as an argument doesn't
1949 // count as escaping.
1950 if (!mandatory && isa<llvm::Instruction>(result)) {
1951 llvm::CallInst *call
1952 = cast<llvm::CallInst>(result->stripPointerCasts());
1953 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1954
1955 SmallVector<llvm::Value*,1> args;
1956 call->setMetadata("clang.arc.copy_on_escape",
1957 llvm::MDNode::get(Builder.getContext(), args));
1958 }
1959
1960 return result;
John McCall31168b02011-06-15 23:02:42 +00001961}
1962
1963/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001964/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001965///
1966/// Yes, this function name is one character away from a different
1967/// call with completely different semantics.
1968llvm::Value *
1969CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1970 // Fetch the void(void) inline asm which marks that we're going to
1971 // retain the autoreleased return value.
1972 llvm::InlineAsm *&marker
1973 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1974 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001975 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001976 = CGM.getTargetCodeGenInfo()
1977 .getARCRetainAutoreleasedReturnValueMarker();
1978
1979 // If we have an empty assembly string, there's nothing to do.
1980 if (assembly.empty()) {
1981
1982 // Otherwise, at -O0, build an inline asm that we're going to call
1983 // in a moment.
1984 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1985 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001986 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001987
1988 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1989
1990 // If we're at -O1 and above, we don't want to litter the code
1991 // with this marker yet, so leave a breadcrumb for the ARC
1992 // optimizer to pick up.
1993 } else {
1994 llvm::NamedMDNode *metadata =
1995 CGM.getModule().getOrInsertNamedMetadata(
1996 "clang.arc.retainAutoreleasedReturnValueMarker");
1997 assert(metadata->getNumOperands() <= 1);
1998 if (metadata->getNumOperands() == 0) {
1999 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00002000 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00002001 }
2002 }
2003 }
2004
2005 // Call the marker asm if we made one, which we do only at -O0.
2006 if (marker) Builder.CreateCall(marker);
2007
2008 return emitARCValueOperation(*this, value,
2009 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
2010 "objc_retainAutoreleasedReturnValue");
2011}
2012
2013/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002014/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002015void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2016 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002017 if (isa<llvm::ConstantPointerNull>(value)) return;
2018
2019 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
2020 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002021 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002022 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002023 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2024 }
2025
2026 // Cast the argument to 'id'.
2027 value = Builder.CreateBitCast(value, Int8PtrTy);
2028
2029 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002030 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002031
John McCallcdda29c2013-03-13 03:10:54 +00002032 if (precise == ARCImpreciseLifetime) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002033 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00002034 call->setMetadata("clang.imprecise_release",
2035 llvm::MDNode::get(Builder.getContext(), args));
2036 }
2037}
2038
John McCalle68b8f42012-10-17 02:28:37 +00002039/// Destroy a __strong variable.
2040///
2041/// At -O0, emit a call to store 'null' into the address;
2042/// instrumenting tools prefer this because the address is exposed,
2043/// but it's relatively cumbersome to optimize.
2044///
2045/// At -O1 and above, just load and call objc_release.
2046///
2047/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCallcdda29c2013-03-13 03:10:54 +00002048void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2049 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002050 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2051 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2052 llvm::Value *null = llvm::ConstantPointerNull::get(
2053 cast<llvm::PointerType>(addrTy->getElementType()));
2054 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2055 return;
2056 }
2057
2058 llvm::Value *value = Builder.CreateLoad(addr);
2059 EmitARCRelease(value, precise);
2060}
2061
John McCall31168b02011-06-15 23:02:42 +00002062/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002063/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002064llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2065 llvm::Value *value,
2066 bool ignored) {
2067 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2068 == value->getType());
2069
2070 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2071 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002072 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002073 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002074 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2075 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2076 }
2077
John McCall882987f2013-02-28 19:01:20 +00002078 llvm::Value *args[] = {
2079 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2080 Builder.CreateBitCast(value, Int8PtrTy)
2081 };
2082 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002083
Craig Topper8a13c412014-05-21 05:09:00 +00002084 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002085 return value;
2086}
2087
2088/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002089/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002090/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002091llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002092 llvm::Value *newValue,
2093 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002094 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002095 bool isBlock = type->isBlockPointerType();
2096
2097 // Use a store barrier at -O0 unless this is a block type or the
2098 // lvalue is inadequately aligned.
2099 if (shouldUseFusedARCCalls() &&
2100 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002101 (dst.getAlignment().isZero() ||
2102 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002103 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2104 }
2105
2106 // Otherwise, split it out.
2107
2108 // Retain the new value.
2109 newValue = EmitARCRetain(type, newValue);
2110
2111 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002112 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002113
2114 // Store. We do this before the release so that any deallocs won't
2115 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002116 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002117
2118 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002119 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002120
2121 return newValue;
2122}
2123
2124/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002125/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002126llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2127 return emitARCValueOperation(*this, value,
2128 CGM.getARCEntrypoints().objc_autorelease,
2129 "objc_autorelease");
2130}
2131
2132/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002133/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002134llvm::Value *
2135CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2136 return emitARCValueOperation(*this, value,
2137 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002138 "objc_autoreleaseReturnValue",
2139 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002140}
2141
2142/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002143/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002144llvm::Value *
2145CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2146 return emitARCValueOperation(*this, value,
2147 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002148 "objc_retainAutoreleaseReturnValue",
2149 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002150}
2151
2152/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002153/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002154/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002155/// %retain = call i8* \@objc_retainBlock(i8* %value)
2156/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002157llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2158 llvm::Value *value) {
2159 if (!type->isBlockPointerType())
2160 return EmitARCRetainAutoreleaseNonBlock(value);
2161
2162 if (isa<llvm::ConstantPointerNull>(value)) return value;
2163
Chris Lattner2192fe52011-07-18 04:24:23 +00002164 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002165 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002166 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002167 value = EmitARCAutorelease(value);
2168 return Builder.CreateBitCast(value, origType);
2169}
2170
2171/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002172/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002173llvm::Value *
2174CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2175 return emitARCValueOperation(*this, value,
2176 CGM.getARCEntrypoints().objc_retainAutorelease,
2177 "objc_retainAutorelease");
2178}
2179
James Dennett14c41ea2012-06-22 05:41:30 +00002180/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002181/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2182llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2183 return emitARCLoadOperation(*this, addr,
2184 CGM.getARCEntrypoints().objc_loadWeak,
2185 "objc_loadWeak");
2186}
2187
James Dennett14c41ea2012-06-22 05:41:30 +00002188/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002189llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2190 return emitARCLoadOperation(*this, addr,
2191 CGM.getARCEntrypoints().objc_loadWeakRetained,
2192 "objc_loadWeakRetained");
2193}
2194
James Dennett14c41ea2012-06-22 05:41:30 +00002195/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002196/// Returns %value.
2197llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2198 llvm::Value *value,
2199 bool ignored) {
2200 return emitARCStoreOperation(*this, addr, value,
2201 CGM.getARCEntrypoints().objc_storeWeak,
2202 "objc_storeWeak", ignored);
2203}
2204
James Dennett14c41ea2012-06-22 05:41:30 +00002205/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002206/// Returns %value. %addr is known to not have a current weak entry.
2207/// Essentially equivalent to:
2208/// *addr = nil; objc_storeWeak(addr, value);
2209void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2210 // If we're initializing to null, just write null to memory; no need
2211 // to get the runtime involved. But don't do this if optimization
2212 // is enabled, because accounting for this would make the optimizer
2213 // much more complicated.
2214 if (isa<llvm::ConstantPointerNull>(value) &&
2215 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2216 Builder.CreateStore(value, addr);
2217 return;
2218 }
2219
2220 emitARCStoreOperation(*this, addr, value,
2221 CGM.getARCEntrypoints().objc_initWeak,
2222 "objc_initWeak", /*ignored*/ true);
2223}
2224
James Dennett14c41ea2012-06-22 05:41:30 +00002225/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002226/// Essentially objc_storeWeak(addr, nil).
2227void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2228 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2229 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002230 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002231 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002232 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2233 }
2234
2235 // Cast the argument to 'id*'.
2236 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2237
John McCall882987f2013-02-28 19:01:20 +00002238 EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00002239}
2240
James Dennett14c41ea2012-06-22 05:41:30 +00002241/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002242/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2243/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2244void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2245 emitARCCopyOperation(*this, dst, src,
2246 CGM.getARCEntrypoints().objc_moveWeak,
2247 "objc_moveWeak");
2248}
2249
James Dennett14c41ea2012-06-22 05:41:30 +00002250/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002251/// Disregards the current value in %dest. Essentially
2252/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2253void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2254 emitARCCopyOperation(*this, dst, src,
2255 CGM.getARCEntrypoints().objc_copyWeak,
2256 "objc_copyWeak");
2257}
2258
2259/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002260/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002261llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2262 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2263 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002264 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002265 llvm::FunctionType::get(Int8PtrTy, false);
2266 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2267 }
2268
John McCall882987f2013-02-28 19:01:20 +00002269 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002270}
2271
2272/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002273/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002274void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2275 assert(value->getType() == Int8PtrTy);
2276
2277 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2278 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002279 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002280 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002281
2282 // We don't want to use a weak import here; instead we should not
2283 // fall into this path.
2284 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2285 }
2286
John McCallb7ff6db2013-04-16 21:29:40 +00002287 // objc_autoreleasePoolPop can throw.
2288 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002289}
2290
2291/// Produce the code to do an MRR version objc_autoreleasepool_push.
2292/// Which is: [[NSAutoreleasePool alloc] init];
2293/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2294/// init is declared as: - (id) init; in its NSObject super class.
2295///
2296llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2297 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002298 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002299 // [NSAutoreleasePool alloc]
2300 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2301 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2302 CallArgList Args;
2303 RValue AllocRV =
2304 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2305 getContext().getObjCIdType(),
2306 AllocSel, Receiver, Args);
2307
2308 // [Receiver init]
2309 Receiver = AllocRV.getScalarVal();
2310 II = &CGM.getContext().Idents.get("init");
2311 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2312 RValue InitRV =
2313 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2314 getContext().getObjCIdType(),
2315 InitSel, Receiver, Args);
2316 return InitRV.getScalarVal();
2317}
2318
2319/// Produce the code to do a primitive release.
2320/// [tmp drain];
2321void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2322 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2323 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2324 CallArgList Args;
2325 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2326 getContext().VoidTy, DrainSel, Arg, Args);
2327}
2328
John McCall82fe67b2011-07-09 01:37:26 +00002329void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2330 llvm::Value *addr,
2331 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002332 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002333}
2334
2335void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2336 llvm::Value *addr,
2337 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002338 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002339}
2340
2341void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2342 llvm::Value *addr,
2343 QualType type) {
2344 CGF.EmitARCDestroyWeak(addr);
2345}
2346
John McCall31168b02011-06-15 23:02:42 +00002347namespace {
John McCall31168b02011-06-15 23:02:42 +00002348 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2349 llvm::Value *Token;
2350
2351 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2352
Craig Topper4f12f102014-03-12 06:41:41 +00002353 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002354 CGF.EmitObjCAutoreleasePoolPop(Token);
2355 }
2356 };
2357 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2358 llvm::Value *Token;
2359
2360 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2361
Craig Topper4f12f102014-03-12 06:41:41 +00002362 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002363 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2364 }
2365 };
2366}
2367
2368void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002369 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002370 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2371 else
2372 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2373}
2374
John McCall31168b02011-06-15 23:02:42 +00002375static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2376 LValue lvalue,
2377 QualType type) {
2378 switch (type.getObjCLifetime()) {
2379 case Qualifiers::OCL_None:
2380 case Qualifiers::OCL_ExplicitNone:
2381 case Qualifiers::OCL_Strong:
2382 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002383 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2384 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002385 false);
2386
2387 case Qualifiers::OCL_Weak:
2388 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2389 true);
2390 }
2391
2392 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002393}
2394
2395static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2396 const Expr *e) {
2397 e = e->IgnoreParens();
2398 QualType type = e->getType();
2399
John McCall154a2fd2011-08-30 00:57:29 +00002400 // If we're loading retained from a __strong xvalue, we can avoid
2401 // an extra retain/release pair by zeroing out the source of this
2402 // "move" operation.
2403 if (e->isXValue() &&
2404 !type.isConstQualified() &&
2405 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2406 // Emit the lvalue.
2407 LValue lv = CGF.EmitLValue(e);
2408
2409 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002410 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2411 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002412
2413 // Set the source pointer to NULL.
2414 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2415
2416 return TryEmitResult(result, true);
2417 }
2418
John McCall31168b02011-06-15 23:02:42 +00002419 // As a very special optimization, in ARC++, if the l-value is the
2420 // result of a non-volatile assignment, do a simple retain of the
2421 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002422 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002423 !type.isVolatileQualified() &&
2424 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2425 isa<BinaryOperator>(e) &&
2426 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2427 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2428
2429 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2430}
2431
2432static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2433 llvm::Value *value);
2434
2435/// Given that the given expression is some sort of call (which does
2436/// not return retained), emit a retain following it.
2437static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2438 llvm::Value *value = CGF.EmitScalarExpr(e);
2439 return emitARCRetainAfterCall(CGF, value);
2440}
2441
2442static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2443 llvm::Value *value) {
2444 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2445 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2446
2447 // Place the retain immediately following the call.
2448 CGF.Builder.SetInsertPoint(call->getParent(),
2449 ++llvm::BasicBlock::iterator(call));
2450 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2451
2452 CGF.Builder.restoreIP(ip);
2453 return value;
2454 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2455 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2456
2457 // Place the retain at the beginning of the normal destination block.
2458 llvm::BasicBlock *BB = invoke->getNormalDest();
2459 CGF.Builder.SetInsertPoint(BB, BB->begin());
2460 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2461
2462 CGF.Builder.restoreIP(ip);
2463 return value;
2464
2465 // Bitcasts can arise because of related-result returns. Rewrite
2466 // the operand.
2467 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2468 llvm::Value *operand = bitcast->getOperand(0);
2469 operand = emitARCRetainAfterCall(CGF, operand);
2470 bitcast->setOperand(0, operand);
2471 return bitcast;
2472
2473 // Generic fall-back case.
2474 } else {
2475 // Retain using the non-block variant: we never need to do a copy
2476 // of a block that's been returned to us.
2477 return CGF.EmitARCRetainNonBlock(value);
2478 }
2479}
2480
John McCallcd78e802011-09-10 01:16:55 +00002481/// Determine whether it might be important to emit a separate
2482/// objc_retain_block on the result of the given expression, or
2483/// whether it's okay to just emit it in a +1 context.
2484static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2485 assert(e->getType()->isBlockPointerType());
2486 e = e->IgnoreParens();
2487
2488 // For future goodness, emit block expressions directly in +1
2489 // contexts if we can.
2490 if (isa<BlockExpr>(e))
2491 return false;
2492
2493 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2494 switch (cast->getCastKind()) {
2495 // Emitting these operations in +1 contexts is goodness.
2496 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002497 case CK_ARCReclaimReturnedObject:
2498 case CK_ARCConsumeObject:
2499 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002500 return false;
2501
2502 // These operations preserve a block type.
2503 case CK_NoOp:
2504 case CK_BitCast:
2505 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2506
2507 // These operations are known to be bad (or haven't been considered).
2508 case CK_AnyPointerToBlockPointerCast:
2509 default:
2510 return true;
2511 }
2512 }
2513
2514 return true;
2515}
2516
John McCallfe96e0b2011-11-06 09:01:30 +00002517/// Try to emit a PseudoObjectExpr at +1.
2518///
2519/// This massively duplicates emitPseudoObjectRValue.
2520static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2521 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002522 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002523
2524 // Find the result expression.
2525 const Expr *resultExpr = E->getResultExpr();
2526 assert(resultExpr);
2527 TryEmitResult result;
2528
2529 for (PseudoObjectExpr::const_semantics_iterator
2530 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2531 const Expr *semantic = *i;
2532
2533 // If this semantic expression is an opaque value, bind it
2534 // to the result of its source expression.
2535 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2536 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2537 OVMA opaqueData;
2538
2539 // If this semantic is the result of the pseudo-object
2540 // expression, try to evaluate the source as +1.
2541 if (ov == resultExpr) {
2542 assert(!OVMA::shouldBindAsLValue(ov));
2543 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2544 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2545
2546 // Otherwise, just bind it.
2547 } else {
2548 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2549 }
2550 opaques.push_back(opaqueData);
2551
2552 // Otherwise, if the expression is the result, evaluate it
2553 // and remember the result.
2554 } else if (semantic == resultExpr) {
2555 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2556
2557 // Otherwise, evaluate the expression in an ignored context.
2558 } else {
2559 CGF.EmitIgnoredExpr(semantic);
2560 }
2561 }
2562
2563 // Unbind all the opaques now.
2564 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2565 opaques[i].unbind(CGF);
2566
2567 return result;
2568}
2569
John McCall31168b02011-06-15 23:02:42 +00002570static TryEmitResult
2571tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002572 // We should *never* see a nested full-expression here, because if
2573 // we fail to emit at +1, our caller must not retain after we close
2574 // out the full-expression.
2575 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002576
John McCall31168b02011-06-15 23:02:42 +00002577 // The desired result type, if it differs from the type of the
2578 // ultimate opaque expression.
Craig Topper8a13c412014-05-21 05:09:00 +00002579 llvm::Type *resultType = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002580
2581 while (true) {
2582 e = e->IgnoreParens();
2583
2584 // There's a break at the end of this if-chain; anything
2585 // that wants to keep looping has to explicitly continue.
2586 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2587 switch (ce->getCastKind()) {
2588 // No-op casts don't change the type, so we just ignore them.
2589 case CK_NoOp:
2590 e = ce->getSubExpr();
2591 continue;
2592
2593 case CK_LValueToRValue: {
2594 TryEmitResult loadResult
2595 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2596 if (resultType) {
2597 llvm::Value *value = loadResult.getPointer();
2598 value = CGF.Builder.CreateBitCast(value, resultType);
2599 loadResult.setPointer(value);
2600 }
2601 return loadResult;
2602 }
2603
2604 // These casts can change the type, so remember that and
2605 // soldier on. We only need to remember the outermost such
2606 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002607 case CK_CPointerToObjCPointerCast:
2608 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002609 case CK_AnyPointerToBlockPointerCast:
2610 case CK_BitCast:
2611 if (!resultType)
2612 resultType = CGF.ConvertType(ce->getType());
2613 e = ce->getSubExpr();
2614 assert(e->getType()->hasPointerRepresentation());
2615 continue;
2616
2617 // For consumptions, just emit the subexpression and thus elide
2618 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002619 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002620 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2621 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2622 return TryEmitResult(result, true);
2623 }
2624
John McCallcd78e802011-09-10 01:16:55 +00002625 // Block extends are net +0. Naively, we could just recurse on
2626 // the subexpression, but actually we need to ensure that the
2627 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002628 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002629 llvm::Value *result; // will be a +0 value
2630
2631 // If we can't safely assume the sub-expression will produce a
2632 // block-copied value, emit the sub-expression at +0.
2633 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2634 result = CGF.EmitScalarExpr(ce->getSubExpr());
2635
2636 // Otherwise, try to emit the sub-expression at +1 recursively.
2637 } else {
2638 TryEmitResult subresult
2639 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2640 result = subresult.getPointer();
2641
2642 // If that produced a retained value, just use that,
2643 // possibly casting down.
2644 if (subresult.getInt()) {
2645 if (resultType)
2646 result = CGF.Builder.CreateBitCast(result, resultType);
2647 return TryEmitResult(result, true);
2648 }
2649
2650 // Otherwise it's +0.
2651 }
2652
2653 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002654 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002655 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2656 return TryEmitResult(result, true);
2657 }
2658
John McCall4db5c3c2011-07-07 06:58:02 +00002659 // For reclaims, emit the subexpression as a retained call and
2660 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002661 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002662 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2663 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2664 return TryEmitResult(result, true);
2665 }
2666
John McCall31168b02011-06-15 23:02:42 +00002667 default:
2668 break;
2669 }
2670
2671 // Skip __extension__.
2672 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2673 if (op->getOpcode() == UO_Extension) {
2674 e = op->getSubExpr();
2675 continue;
2676 }
2677
2678 // For calls and message sends, use the retained-call logic.
2679 // Delegate inits are a special case in that they're the only
2680 // returns-retained expression that *isn't* surrounded by
2681 // a consume.
2682 } else if (isa<CallExpr>(e) ||
2683 (isa<ObjCMessageExpr>(e) &&
2684 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2685 llvm::Value *result = emitARCRetainCall(CGF, e);
2686 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2687 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002688
2689 // Look through pseudo-object expressions.
2690 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2691 TryEmitResult result
2692 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2693 if (resultType) {
2694 llvm::Value *value = result.getPointer();
2695 value = CGF.Builder.CreateBitCast(value, resultType);
2696 result.setPointer(value);
2697 }
2698 return result;
John McCall31168b02011-06-15 23:02:42 +00002699 }
2700
2701 // Conservatively halt the search at any other expression kind.
2702 break;
2703 }
2704
2705 // We didn't find an obvious production, so emit what we've got and
2706 // tell the caller that we didn't manage to retain.
2707 llvm::Value *result = CGF.EmitScalarExpr(e);
2708 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2709 return TryEmitResult(result, false);
2710}
2711
2712static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2713 LValue lvalue,
2714 QualType type) {
2715 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2716 llvm::Value *value = result.getPointer();
2717 if (!result.getInt())
2718 value = CGF.EmitARCRetain(type, value);
2719 return value;
2720}
2721
2722/// EmitARCRetainScalarExpr - Semantically equivalent to
2723/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2724/// best-effort attempt to peephole expressions that naturally produce
2725/// retained objects.
2726llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002727 // The retain needs to happen within the full-expression.
2728 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2729 enterFullExpression(cleanups);
2730 RunCleanupsScope scope(*this);
2731 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2732 }
2733
John McCall31168b02011-06-15 23:02:42 +00002734 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2735 llvm::Value *value = result.getPointer();
2736 if (!result.getInt())
2737 value = EmitARCRetain(e->getType(), value);
2738 return value;
2739}
2740
2741llvm::Value *
2742CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002743 // The retain needs to happen within the full-expression.
2744 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2745 enterFullExpression(cleanups);
2746 RunCleanupsScope scope(*this);
2747 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2748 }
2749
John McCall31168b02011-06-15 23:02:42 +00002750 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2751 llvm::Value *value = result.getPointer();
2752 if (result.getInt())
2753 value = EmitARCAutorelease(value);
2754 else
2755 value = EmitARCRetainAutorelease(e->getType(), value);
2756 return value;
2757}
2758
John McCallff613032011-10-04 06:23:45 +00002759llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2760 llvm::Value *result;
2761 bool doRetain;
2762
2763 if (shouldEmitSeparateBlockRetain(e)) {
2764 result = EmitScalarExpr(e);
2765 doRetain = true;
2766 } else {
2767 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2768 result = subresult.getPointer();
2769 doRetain = !subresult.getInt();
2770 }
2771
2772 if (doRetain)
2773 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2774 return EmitObjCConsumeObject(e->getType(), result);
2775}
2776
John McCall248512a2011-10-01 10:32:24 +00002777llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2778 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002779 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002780 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002781 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002782 return EmitARCRetainAutoreleaseScalarExpr(expr);
2783 }
2784
2785 // Otherwise, use the normal scalar-expression emission. The
2786 // exception machinery doesn't do anything special with the
2787 // exception like retaining it, so there's no safety associated with
2788 // only running cleanups after the throw has started, and when it
2789 // matters it tends to be substantially inferior code.
2790 return EmitScalarExpr(expr);
2791}
2792
John McCall31168b02011-06-15 23:02:42 +00002793std::pair<LValue,llvm::Value*>
2794CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2795 bool ignored) {
2796 // Evaluate the RHS first.
2797 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2798 llvm::Value *value = result.getPointer();
2799
John McCallb726a552011-07-28 07:23:35 +00002800 bool hasImmediateRetain = result.getInt();
2801
2802 // If we didn't emit a retained object, and the l-value is of block
2803 // type, then we need to emit the block-retain immediately in case
2804 // it invalidates the l-value.
2805 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002806 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002807 hasImmediateRetain = true;
2808 }
2809
John McCall31168b02011-06-15 23:02:42 +00002810 LValue lvalue = EmitLValue(e->getLHS());
2811
2812 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002813 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002814 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002815 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002816 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002817 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002818 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002819 }
2820
2821 return std::pair<LValue,llvm::Value*>(lvalue, value);
2822}
2823
2824std::pair<LValue,llvm::Value*>
2825CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2826 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2827 LValue lvalue = EmitLValue(e->getLHS());
2828
Eli Friedmana0544d62011-12-03 04:14:32 +00002829 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002830
2831 return std::pair<LValue,llvm::Value*>(lvalue, value);
2832}
2833
2834void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002835 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002836 const Stmt *subStmt = ARPS.getSubStmt();
2837 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2838
2839 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002840 if (DI)
2841 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002842
2843 // Keep track of the current cleanup stack depth.
2844 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002845 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002846 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2847 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2848 } else {
2849 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2850 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2851 }
2852
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00002853 for (const auto *I : S.body())
2854 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00002855
Eric Christopher7cdf9482011-10-13 21:45:18 +00002856 if (DI)
2857 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002858}
John McCall1bd25562011-06-24 23:21:27 +00002859
2860/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2861/// make sure it survives garbage collection until this point.
2862void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2863 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002864 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002865 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002866 llvm::Value *extender
2867 = llvm::InlineAsm::get(extenderType,
2868 /* assembly */ "",
2869 /* constraints */ "r",
2870 /* side effects */ true);
2871
2872 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00002873 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00002874}
2875
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002876/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002877/// non-trivial copy assignment function, produce following helper function.
2878/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2879///
2880llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002881CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2882 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002883 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002884 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002885 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002886 QualType Ty = PID->getPropertyIvarDecl()->getType();
2887 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002888 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002889 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002890 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002891 return nullptr;
2892 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002893 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002894 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002895 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2896 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2897 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002898
2899 ASTContext &C = getContext();
2900 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002901 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002902 FunctionDecl *FD = FunctionDecl::Create(C,
2903 C.getTranslationUnitDecl(),
2904 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002905 SourceLocation(), II, C.VoidTy,
2906 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002907 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002908 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002909
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002910 QualType DestTy = C.getPointerType(Ty);
2911 QualType SrcTy = Ty;
2912 SrcTy.addConst();
2913 SrcTy = C.getPointerType(SrcTy);
2914
2915 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002916 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002917 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002918 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002919 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002920
2921 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2922 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2923
John McCalla729c622012-02-17 03:33:10 +00002924 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002925
2926 llvm::Function *Fn =
2927 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002928 "__assign_helper_atomic_property_",
2929 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002930
Adrian Prantl22e66b42014-04-11 01:13:04 +00002931 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002932
John McCall113bee02012-03-10 09:33:50 +00002933 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2934 VK_RValue, SourceLocation());
2935 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2936 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002937
John McCall113bee02012-03-10 09:33:50 +00002938 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2939 VK_RValue, SourceLocation());
2940 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2941 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002942
John McCall113bee02012-03-10 09:33:50 +00002943 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002944 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002945 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002946 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002947 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002948
2949 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002950
2951 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002952 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002953 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002954 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002955}
2956
2957llvm::Constant *
2958CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2959 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002960 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002961 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002962 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002963 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2964 QualType Ty = PD->getType();
2965 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002966 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002967 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002968 return nullptr;
2969 llvm::Constant *HelperFn = nullptr;
2970
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002971 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002972 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002973 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2974 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2975 return HelperFn;
2976
2977
2978 ASTContext &C = getContext();
2979 IdentifierInfo *II
2980 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2981 FunctionDecl *FD = FunctionDecl::Create(C,
2982 C.getTranslationUnitDecl(),
2983 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002984 SourceLocation(), II, C.VoidTy,
2985 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002986 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002987 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002988
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002989 QualType DestTy = C.getPointerType(Ty);
2990 QualType SrcTy = Ty;
2991 SrcTy.addConst();
2992 SrcTy = C.getPointerType(SrcTy);
2993
2994 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002995 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002996 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002997 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002998 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002999
3000 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
3001 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
3002
John McCalla729c622012-02-17 03:33:10 +00003003 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003004
3005 llvm::Function *Fn =
3006 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3007 "__copy_helper_atomic_property_", &CGM.getModule());
3008
Adrian Prantl22e66b42014-04-11 01:13:04 +00003009 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003010
John McCall113bee02012-03-10 09:33:50 +00003011 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003012 VK_RValue, SourceLocation());
3013
John McCall113bee02012-03-10 09:33:50 +00003014 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3015 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003016
3017 CXXConstructExpr *CXXConstExpr =
3018 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3019
3020 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003021 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003022 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3023 ++A;
3024
3025 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3026 A != AEnd; ++A)
3027 ConstructorArgs.push_back(*A);
3028
3029 CXXConstructExpr *TheCXXConstructExpr =
3030 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3031 CXXConstExpr->getConstructor(),
3032 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003033 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003034 CXXConstExpr->hadMultipleCandidates(),
3035 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003036 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003037 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003038 CXXConstExpr->getConstructionKind(),
3039 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003040
John McCall113bee02012-03-10 09:33:50 +00003041 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3042 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003043
John McCall113bee02012-03-10 09:33:50 +00003044 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003045 CharUnits Alignment
3046 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003047 EmitAggExpr(TheCXXConstructExpr,
3048 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3049 AggValueSlot::IsDestructed,
3050 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003051 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003052
3053 FinishFunction();
3054 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3055 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3056 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003057}
3058
Eli Friedmanec75fec2012-02-28 01:08:45 +00003059llvm::Value *
3060CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3061 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003062 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3063 Selector CopySelector =
3064 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003065 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3066 Selector AutoreleaseSelector =
3067 getContext().Selectors.getNullarySelector(AutoreleaseID);
3068
3069 // Emit calls to retain/autorelease.
3070 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3071 llvm::Value *Val = Block;
3072 RValue Result;
3073 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003074 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003075 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003076 Val = Result.getScalarVal();
3077 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3078 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003079 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003080 Val = Result.getScalarVal();
3081 return Val;
3082}
3083
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003084
Ted Kremenek43e06332008-04-09 15:51:31 +00003085CGObjCRuntime::~CGObjCRuntime() {}