blob: df571de1b8cbc7b2df5625c8d65c9f82259f8b3b [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);
Douglas Gregore83b9562015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
David Chisnall481e3a82010-01-23 02:40:42 +000048 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000049 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Patrick Beard0caa3942012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000056/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000058///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000059llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000064 const Expr *SubExpr = E->getSubExpr();
Patrick Beard0caa3942012-04-19 00:25:12 +000065 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000070 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000077 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
79
80 // ObjCBoxedExpr supports boxing of structs and unions
81 // via [NSValue valueWithBytes:objCType:]
82 const QualType ValueType(SubExpr->getType().getCanonicalType());
83 if (ValueType->isObjCBoxableRecordType()) {
84 // Emit CodeGen for first parameter
85 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000086 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000087 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000088 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000090
91 // Create char array to store type encoding
92 std::string Str;
93 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000094 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Alex Denisovfde64952015-06-26 05:28:36 +000095
96 // Cast type encoding to correct type
97 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
100
101 Args.add(RValue::get(Cast), EncodingQT);
102 } else {
103 Args.add(EmitAnyExpr(SubExpr), ArgQT);
104 }
Alp Toker314cc812014-01-25 16:55:45 +0000105
106 RValue result = Runtime.GenerateMessageSend(
107 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108 Args, ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000109 return Builder.CreateBitCast(result.getScalarVal(),
110 ConvertType(E->getType()));
111}
112
113llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000114 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000116 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000117 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
118 if (!ALE)
119 DLE = cast<ObjCDictionaryLiteral>(E);
120
121 // Compute the type of the array we're initializing.
122 uint64_t NumElements =
123 ALE ? ALE->getNumElements() : DLE->getNumElements();
124 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
125 NumElements);
126 QualType ElementType = Context.getObjCIdType().withConst();
127 QualType ElementArrayType
128 = Context.getConstantArrayType(ElementType, APNumElements,
129 ArrayType::Normal, /*IndexTypeQuals=*/0);
130
131 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000132 Address Objects = CreateMemTemp(ElementArrayType, "objects");
133 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000134 if (DLE)
135 Keys = CreateMemTemp(ElementArrayType, "keys");
136
John McCall770a4c12013-04-04 00:20:38 +0000137 // In ARC, we may need to do extra work to keep all the keys and
138 // values alive until after the call.
139 SmallVector<llvm::Value *, 16> NeededObjects;
140 bool TrackNeededObjects =
141 (getLangOpts().ObjCAutoRefCount &&
142 CGM.getCodeGenOpts().OptimizationLevel != 0);
143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 // Perform the actual initialialization of the array(s).
145 for (uint64_t i = 0; i < NumElements; i++) {
146 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000147 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 const Expr *Rhs = ALE->getElement(i);
John McCall7f416cc2015-09-08 08:05:57 +0000149 LValue LV = MakeAddrLValue(
150 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
151 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000152
153 llvm::Value *value = EmitScalarExpr(Rhs);
154 EmitStoreThroughLValue(RValue::get(value), LV, true);
155 if (TrackNeededObjects) {
156 NeededObjects.push_back(value);
157 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000158 } else {
John McCall770a4c12013-04-04 00:20:38 +0000159 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000160 const Expr *Key = DLE->getKeyValueElement(i).Key;
John McCall7f416cc2015-09-08 08:05:57 +0000161 LValue KeyLV = MakeAddrLValue(
162 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
163 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000164 llvm::Value *keyValue = EmitScalarExpr(Key);
165 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000166
John McCall770a4c12013-04-04 00:20:38 +0000167 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000168 const Expr *Value = DLE->getKeyValueElement(i).Value;
John McCall7f416cc2015-09-08 08:05:57 +0000169 LValue ValueLV = MakeAddrLValue(
170 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
171 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000172 llvm::Value *valueValue = EmitScalarExpr(Value);
173 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
174 if (TrackNeededObjects) {
175 NeededObjects.push_back(keyValue);
176 NeededObjects.push_back(valueValue);
177 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000178 }
179 }
180
181 // Generate the argument list.
182 CallArgList Args;
183 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
184 const ParmVarDecl *argDecl = *PI++;
185 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000186 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000187 if (DLE) {
188 argDecl = *PI++;
189 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000190 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000191 }
192 argDecl = *PI;
193 ArgQT = argDecl->getType().getUnqualifiedType();
194 llvm::Value *Count =
195 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
196 Args.add(RValue::get(Count), ArgQT);
197
198 // Generate a reference to the class pointer, which will be the receiver.
199 Selector Sel = MethodWithObjects->getSelector();
200 QualType ResultType = E->getType();
201 const ObjCObjectPointerType *InterfacePointerType
202 = ResultType->getAsObjCInterfacePointerType();
203 ObjCInterfaceDecl *Class
204 = InterfacePointerType->getObjectType()->getInterface();
205 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000206 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000207
208 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000209 RValue result = Runtime.GenerateMessageSend(
210 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
211 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000212
213 // The above message send needs these objects, but in ARC they are
214 // passed in a buffer that is essentially __unsafe_unretained.
215 // Therefore we must prevent the optimizer from releasing them until
216 // after the call.
217 if (TrackNeededObjects) {
218 EmitARCIntrinsicUse(NeededObjects);
219 }
220
Ted Kremeneke65b0862012-03-06 20:05:56 +0000221 return Builder.CreateBitCast(result.getScalarVal(),
222 ConvertType(E->getType()));
223}
224
225llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000226 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227}
228
229llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
230 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000231 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000232}
233
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000234/// Emit a selector.
235llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
236 // Untyped selector.
237 // Note that this implementation allows for non-constant strings to be passed
238 // as arguments to @selector(). Currently, the only thing preventing this
239 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000240 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000241}
242
Daniel Dunbar66912a12008-08-20 00:28:19 +0000243llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
244 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000245 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000246}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000247
Douglas Gregore83b9562015-07-07 03:57:53 +0000248/// \brief Adjust the type of an Objective-C object that doesn't match up due
249/// to type erasure at various points, e.g., related result types or the use
250/// of parameterized classes.
251static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
252 RValue Result) {
253 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000254 return Result;
John McCall31168b02011-06-15 23:02:42 +0000255
Douglas Gregore83b9562015-07-07 03:57:53 +0000256 // If the converted types are the same, we're done.
257 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
258 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000259 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000260
261 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000262 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000263 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000264}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000265
John McCallcf166702011-07-22 08:53:00 +0000266/// Decide whether to extend the lifetime of the receiver of a
267/// returns-inner-pointer message.
268static bool
269shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
270 switch (message->getReceiverKind()) {
271
272 // For a normal instance message, we should extend unless the
273 // receiver is loaded from a variable with precise lifetime.
274 case ObjCMessageExpr::Instance: {
275 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000276
277 // Look through OVEs.
278 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
279 if (opaque->getSourceExpr())
280 receiver = opaque->getSourceExpr()->IgnoreParens();
281 }
282
John McCallcf166702011-07-22 08:53:00 +0000283 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
284 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
285 receiver = ice->getSubExpr()->IgnoreParens();
286
John McCall6380a282015-09-09 23:37:17 +0000287 // Look through OVEs.
288 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
289 if (opaque->getSourceExpr())
290 receiver = opaque->getSourceExpr()->IgnoreParens();
291 }
292
John McCallcf166702011-07-22 08:53:00 +0000293 // Only __strong variables.
294 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
295 return true;
296
297 // All ivars and fields have precise lifetime.
298 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
299 return false;
300
301 // Otherwise, check for variables.
302 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
303 if (!declRef) return true;
304 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
305 if (!var) return true;
306
307 // All variables have precise lifetime except local variables with
308 // automatic storage duration that aren't specially marked.
309 return (var->hasLocalStorage() &&
310 !var->hasAttr<ObjCPreciseLifetimeAttr>());
311 }
312
313 case ObjCMessageExpr::Class:
314 case ObjCMessageExpr::SuperClass:
315 // It's never necessary for class objects.
316 return false;
317
318 case ObjCMessageExpr::SuperInstance:
319 // We generally assume that 'self' lives throughout a method call.
320 return false;
321 }
322
323 llvm_unreachable("invalid receiver kind");
324}
325
John McCall460ce582015-10-22 18:38:17 +0000326/// Given an expression of ObjC pointer type, check whether it was
327/// immediately loaded from an ARC __weak l-value.
328static const Expr *findWeakLValue(const Expr *E) {
329 assert(E->getType()->isObjCRetainableType());
330 E = E->IgnoreParens();
331 if (auto CE = dyn_cast<CastExpr>(E)) {
332 if (CE->getCastKind() == CK_LValueToRValue) {
333 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
334 return CE->getSubExpr();
335 }
336 }
337
338 return nullptr;
339}
340
John McCall78a15112010-05-22 01:48:05 +0000341RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
342 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000343 // Only the lookup mechanism and first two arguments of the method
344 // implementation vary between runtimes. We can get the receiver and
345 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000346
John McCall31168b02011-06-15 23:02:42 +0000347 bool isDelegateInit = E->isDelegateInitCall();
348
John McCallcf166702011-07-22 08:53:00 +0000349 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000350
John McCall460ce582015-10-22 18:38:17 +0000351 // If the method is -retain, and the receiver's being loaded from
352 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
353 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
354 method->getMethodFamily() == OMF_retain) {
355 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
356 LValue lvalue = EmitLValue(lvalueExpr);
357 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
358 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
359 }
360 }
361
John McCall31168b02011-06-15 23:02:42 +0000362 // We don't retain the receiver in delegate init calls, and this is
363 // safe because the receiver value is always loaded from 'self',
364 // which we zero out. We don't want to Block_copy block receivers,
365 // though.
366 bool retainSelf =
367 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000368 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000369 method &&
370 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000371
Daniel Dunbar8d480592008-08-11 18:12:00 +0000372 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000373 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000374 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000375 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000376 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000377 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000378 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000379 switch (E->getReceiverKind()) {
380 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000381 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000382 if (retainSelf) {
383 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
384 E->getInstanceReceiver());
385 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000386 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000387 } else
388 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000389 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000390
Douglas Gregor9a129192010-04-21 00:45:42 +0000391 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000392 ReceiverType = E->getClassReceiver();
393 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000394 assert(ObjTy && "Invalid Objective-C class message send");
395 OID = ObjTy->getInterface();
396 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000397 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000398 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000399 break;
400 }
401
402 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000403 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000404 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000405 isSuperMessage = true;
406 break;
407
408 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000409 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000410 Receiver = LoadObjCSelf();
411 isSuperMessage = true;
412 isClassMessage = true;
413 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000414 }
415
John McCallcf166702011-07-22 08:53:00 +0000416 if (retainSelf)
417 Receiver = EmitARCRetainNonBlock(Receiver);
418
419 // In ARC, we sometimes want to "extend the lifetime"
420 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
421 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000422 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000423 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
424 shouldExtendReceiverForInnerPointerMessage(E))
425 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
426
Alp Toker314cc812014-01-25 16:55:45 +0000427 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000428
Daniel Dunbarc722b852008-08-30 03:02:31 +0000429 CallArgList Args;
David Blaikief05779e2015-07-21 18:37:18 +0000430 EmitCallArgs(Args, method, E->arguments());
Mike Stump11289f42009-09-09 15:08:12 +0000431
John McCall31168b02011-06-15 23:02:42 +0000432 // For delegate init calls in ARC, do an unsafe store of null into
433 // self. This represents the call taking direct ownership of that
434 // value. We have to do this after emitting the other call
435 // arguments because they might also reference self, but we don't
436 // have to worry about any of them modifying self because that would
437 // be an undefined read and write of an object in unordered
438 // expressions.
439 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000440 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000441 "delegate init calls should only be marked in ARC");
442
443 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000444 Address selfAddr =
445 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000446 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
447 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000448
Douglas Gregor33823722011-06-11 01:09:30 +0000449 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000450 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000451 // super is only valid in an Objective-C method
452 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000453 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000454 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
455 E->getSelector(),
456 OMD->getClassInterface(),
457 isCategoryImpl,
458 Receiver,
459 isClassMessage,
460 Args,
John McCallcf166702011-07-22 08:53:00 +0000461 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000462 } else {
Pete Cooper94867712016-03-21 20:50:03 +0000463 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
464 E->getSelector(),
465 Receiver, Args, OID,
466 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000467 }
John McCall31168b02011-06-15 23:02:42 +0000468
469 // For delegate init calls in ARC, implicitly store the result of
470 // the call back into self. This takes ownership of the value.
471 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000472 Address selfAddr =
473 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000474 llvm::Value *newSelf = result.getScalarVal();
475
476 // The delegate return type isn't necessarily a matching type; in
477 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000478 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000479 newSelf = Builder.CreateBitCast(newSelf, selfTy);
480
481 Builder.CreateStore(newSelf, selfAddr);
482 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000483
Douglas Gregore83b9562015-07-07 03:57:53 +0000484 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000485}
486
John McCall31168b02011-06-15 23:02:42 +0000487namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000488struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000489 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000490 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000491
492 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000493 const ObjCInterfaceDecl *iface = impl->getClassInterface();
494 if (!iface->getSuperClass()) return;
495
John McCalldffafde2011-07-13 18:26:47 +0000496 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
497
John McCall31168b02011-06-15 23:02:42 +0000498 // Call [super dealloc] if we have a superclass.
499 llvm::Value *self = CGF.LoadObjCSelf();
500
501 CallArgList args;
502 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
503 CGF.getContext().VoidTy,
504 method->getSelector(),
505 iface,
John McCalldffafde2011-07-13 18:26:47 +0000506 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000507 self,
508 /*is class msg*/ false,
509 args,
510 method);
511 }
512};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000513}
John McCall31168b02011-06-15 23:02:42 +0000514
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000515/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
516/// the LLVM function and sets the other context used by
517/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000518void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000519 const ObjCContainerDecl *CD) {
520 SourceLocation StartLoc = OMD->getLocStart();
John McCalla738c252011-03-09 04:27:21 +0000521 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000522 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000523 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000524 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000525
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000526 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000527
John McCalla729c622012-02-17 03:33:10 +0000528 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000529 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000530
John McCalla738c252011-03-09 04:27:21 +0000531 args.push_back(OMD->getSelfDecl());
532 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000533
Benjamin Kramerf9890422015-02-17 16:48:30 +0000534 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000535
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000536 CurGD = OMD;
David Blaikie47d28e02015-01-14 07:10:46 +0000537 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000538
Adrian Prantl42d71b92014-04-10 23:21:53 +0000539 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
540 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000541
542 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000543 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000544 OMD->isInstanceMethod() &&
545 OMD->getSelector().isUnarySelector()) {
546 const IdentifierInfo *ident =
547 OMD->getSelector().getIdentifierInfoForSlot(0);
548 if (ident->isStr("dealloc"))
549 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
550 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000551}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000552
John McCall31168b02011-06-15 23:02:42 +0000553static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
554 LValue lvalue, QualType type);
555
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000556/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000557/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000558void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000559 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000560 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000561 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000562 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000563 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000564 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000565}
566
John McCallb923ece2011-09-12 23:06:44 +0000567/// emitStructGetterCall - Call the runtime function to load a property
568/// into the return value slot.
569static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
570 bool isAtomic, bool hasStrong) {
571 ASTContext &Context = CGF.getContext();
572
John McCall7f416cc2015-09-08 08:05:57 +0000573 Address src =
574 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
575 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000576
577 // objc_copyStruct (ReturnValue, &structIvar,
578 // sizeof (Type of Ivar), isAtomic, false);
579 CallArgList args;
580
John McCall7f416cc2015-09-08 08:05:57 +0000581 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
582 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000583
584 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000585 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000586
587 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
588 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
589 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
590 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
591
592 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallc56a8b32016-03-11 04:30:31 +0000593 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb923ece2011-09-12 23:06:44 +0000594 fn, ReturnValueSlot(), args);
595}
596
John McCallf4528ae2011-09-13 03:34:09 +0000597/// Determine whether the given architecture supports unaligned atomic
598/// accesses. They don't have to be fast, just faster than a function
599/// call and a mutex.
600static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000601 // FIXME: Allow unaligned atomic load/store on x86. (It is not
602 // currently supported by the backend.)
603 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000604}
605
606/// Return the maximum size that permits atomic accesses for the given
607/// architecture.
608static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
609 llvm::Triple::ArchType arch) {
610 // ARM has 8-byte atomic accesses, but it's not clear whether we
611 // want to rely on them here.
612
613 // In the default case, just assume that any size up to a pointer is
614 // fine given adequate alignment.
615 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
616}
617
618namespace {
619 class PropertyImplStrategy {
620 public:
621 enum StrategyKind {
622 /// The 'native' strategy is to use the architecture's provided
623 /// reads and writes.
624 Native,
625
626 /// Use objc_setProperty and objc_getProperty.
627 GetSetProperty,
628
629 /// Use objc_setProperty for the setter, but use expression
630 /// evaluation for the getter.
631 SetPropertyAndExpressionGet,
632
633 /// Use objc_copyStruct.
634 CopyStruct,
635
636 /// The 'expression' strategy is to emit normal assignment or
637 /// lvalue-to-rvalue expressions.
638 Expression
639 };
640
641 StrategyKind getKind() const { return StrategyKind(Kind); }
642
643 bool hasStrongMember() const { return HasStrong; }
644 bool isAtomic() const { return IsAtomic; }
645 bool isCopy() const { return IsCopy; }
646
647 CharUnits getIvarSize() const { return IvarSize; }
648 CharUnits getIvarAlignment() const { return IvarAlignment; }
649
650 PropertyImplStrategy(CodeGenModule &CGM,
651 const ObjCPropertyImplDecl *propImpl);
652
653 private:
654 unsigned Kind : 8;
655 unsigned IsAtomic : 1;
656 unsigned IsCopy : 1;
657 unsigned HasStrong : 1;
658
659 CharUnits IvarSize;
660 CharUnits IvarAlignment;
661 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000662}
John McCallf4528ae2011-09-13 03:34:09 +0000663
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000664/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000665PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
666 const ObjCPropertyImplDecl *propImpl) {
667 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000668 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000669
John McCall43192862011-09-13 18:31:23 +0000670 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
671 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000672 HasStrong = false; // doesn't matter here.
673
674 // Evaluate the ivar's size and alignment.
675 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
676 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000677 std::tie(IvarSize, IvarAlignment) =
678 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000679
680 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000681 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000682 if (IsCopy) {
683 Kind = GetSetProperty;
684 return;
685 }
686
John McCall43192862011-09-13 18:31:23 +0000687 // Handle retain.
688 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000689 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000690 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000691 // fallthrough
692
693 // In ARC, if the property is non-atomic, use expression emission,
694 // which translates to objc_storeStrong. This isn't required, but
695 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000696 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000697 // Using standard expression emission for the setter is only
698 // acceptable if the ivar is __strong, which won't be true if
699 // the property is annotated with __attribute__((NSObject)).
700 // TODO: falling all the way back to objc_setProperty here is
701 // just laziness, though; we could still use objc_storeStrong
702 // if we hacked it right.
703 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
704 Kind = Expression;
705 else
706 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000707 return;
708
709 // Otherwise, we need to at least use setProperty. However, if
710 // the property isn't atomic, we can use normal expression
711 // emission for the getter.
712 } else if (!IsAtomic) {
713 Kind = SetPropertyAndExpressionGet;
714 return;
715
716 // Otherwise, we have to use both setProperty and getProperty.
717 } else {
718 Kind = GetSetProperty;
719 return;
720 }
721 }
722
723 // If we're not atomic, just use expression accesses.
724 if (!IsAtomic) {
725 Kind = Expression;
726 return;
727 }
728
John McCall0e5c0862011-09-13 05:36:29 +0000729 // Properties on bitfield ivars need to be emitted using expression
730 // accesses even if they're nominally atomic.
731 if (ivar->isBitField()) {
732 Kind = Expression;
733 return;
734 }
735
John McCallf4528ae2011-09-13 03:34:09 +0000736 // GC-qualified or ARC-qualified ivars need to be emitted as
737 // expressions. This actually works out to being atomic anyway,
738 // except for ARC __strong, but that should trigger the above code.
739 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000740 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000741 CGM.getContext().getObjCGCAttrKind(ivarType))) {
742 Kind = Expression;
743 return;
744 }
745
746 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000747 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000748 if (const RecordType *recordType = ivarType->getAs<RecordType>())
749 HasStrong = recordType->getDecl()->hasObjectMember();
750
751 // We can never access structs with object members with a native
752 // access, because we need to use write barriers. This is what
753 // objc_copyStruct is for.
754 if (HasStrong) {
755 Kind = CopyStruct;
756 return;
757 }
758
759 // Otherwise, this is target-dependent and based on the size and
760 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000761
762 // If the size of the ivar is not a power of two, give up. We don't
763 // want to get into the business of doing compare-and-swaps.
764 if (!IvarSize.isPowerOfTwo()) {
765 Kind = CopyStruct;
766 return;
767 }
768
John McCallf4528ae2011-09-13 03:34:09 +0000769 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000770 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000771
772 // Most architectures require memory to fit within a single cache
773 // line, so the alignment has to be at least the size of the access.
774 // Otherwise we have to grab a lock.
775 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
776 Kind = CopyStruct;
777 return;
778 }
779
780 // If the ivar's size exceeds the architecture's maximum atomic
781 // access size, we have to use CopyStruct.
782 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
783 Kind = CopyStruct;
784 return;
785 }
786
787 // Otherwise, we can use native loads and stores.
788 Kind = Native;
789}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000790
James Dennettbe302452012-06-15 22:10:14 +0000791/// \brief Generate an Objective-C property getter function.
792///
793/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000794/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000795void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
796 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000797 llvm::Constant *AtomicHelperFn =
798 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000799 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
800 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
801 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000802 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000803
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000804 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000805
806 FinishFunction();
807}
808
John McCallbdd81852011-09-13 06:00:03 +0000809static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
810 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000811 if (!getter) return true;
812
813 // Sema only makes only of these when the ivar has a C++ class type,
814 // so the form is pretty constrained.
815
John McCallbdd81852011-09-13 06:00:03 +0000816 // If the property has a reference type, we might just be binding a
817 // reference, in which case the result will be a gl-value. We should
818 // treat this as a non-trivial operation.
819 if (getter->isGLValue())
820 return false;
821
John McCallf4528ae2011-09-13 03:34:09 +0000822 // If we selected a trivial copy-constructor, we're okay.
823 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
824 return (construct->getConstructor()->isTrivial());
825
826 // The constructor might require cleanups (in which case it's never
827 // trivial).
828 assert(isa<ExprWithCleanups>(getter));
829 return false;
830}
831
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000832/// emitCPPObjectAtomicGetterCall - Call the runtime function to
833/// copy the ivar into the resturn slot.
834static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
835 llvm::Value *returnAddr,
836 ObjCIvarDecl *ivar,
837 llvm::Constant *AtomicHelperFn) {
838 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
839 // AtomicHelperFn);
840 CallArgList args;
841
842 // The 1st argument is the return Slot.
843 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
844
845 // The 2nd argument is the address of the ivar.
846 llvm::Value *ivarAddr =
John McCall7f416cc2015-09-08 08:05:57 +0000847 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
848 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000849 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
850 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
851
852 // Third argument is the helper function.
853 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
854
855 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000856 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallc56a8b32016-03-11 04:30:31 +0000857 CGF.EmitCall(
858 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000859 copyCppAtomicObjectFn, ReturnValueSlot(), args);
860}
861
John McCallf4528ae2011-09-13 03:34:09 +0000862void
863CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000864 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000865 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000866 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000867 // If there's a non-trivial 'get' expression, we just have to emit that.
868 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000869 if (!AtomicHelperFn) {
870 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000871 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000872 EmitReturnStmt(ret);
873 }
874 else {
875 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f416cc2015-09-08 08:05:57 +0000876 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000877 ivar, AtomicHelperFn);
878 }
John McCallf4528ae2011-09-13 03:34:09 +0000879 return;
880 }
881
882 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
883 QualType propType = prop->getType();
884 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
885
886 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
887
888 // Pick an implementation strategy.
889 PropertyImplStrategy strategy(CGM, propImpl);
890 switch (strategy.getKind()) {
891 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000892 // We don't need to do anything for a zero-size struct.
893 if (strategy.getIvarSize().isZero())
894 return;
895
John McCallf4528ae2011-09-13 03:34:09 +0000896 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
897
898 // Currently, all atomic accesses have to be through integer
899 // types, so there's no point in trying to pick a prettier type.
900 llvm::Type *bitcastType =
901 llvm::Type::getIntNTy(getLLVMContext(),
902 getContext().toBits(strategy.getIvarSize()));
903 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
904
905 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +0000906 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +0000907 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
908 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +0000909 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +0000910
911 // Store that value into the return address. Doing this with a
912 // bitcast is likely to produce some pretty ugly IR, but it's not
913 // the *most* terrible thing in the world.
914 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
915
916 // Make sure we don't do an autorelease.
917 AutoreleaseResult = false;
918 return;
919 }
920
921 case PropertyImplStrategy::GetSetProperty: {
922 llvm::Value *getPropertyFn =
923 CGM.getObjCRuntime().GetPropertyGetFunction();
924 if (!getPropertyFn) {
925 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000926 return;
927 }
928
929 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
930 // FIXME: Can't this be simpler? This might even be worse than the
931 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000932 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +0000933 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +0000934 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
935 llvm::Value *ivarOffset =
936 EmitIvarOffset(classImpl->getClassInterface(), ivar);
937
938 CallArgList args;
939 args.add(RValue::get(self), getContext().getObjCIdType());
940 args.add(RValue::get(cmd), getContext().getObjCSelType());
941 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000942 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
943 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000944
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000945 // FIXME: We shouldn't need to get the function info here, the
946 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000947 llvm::Instruction *CallInstruction;
Samuel Antao798f11c2015-11-23 22:04:44 +0000948 RValue RV = EmitCall(
John McCallc56a8b32016-03-11 04:30:31 +0000949 getTypes().arrangeBuiltinFunctionCall(propType, args),
Samuel Antao798f11c2015-11-23 22:04:44 +0000950 getPropertyFn, ReturnValueSlot(), args, CGCalleeInfo(),
951 &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000952 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
953 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000954
Daniel Dunbara08dff12008-09-24 04:04:31 +0000955 // We need to fix the type here. Ivars with copy & retain are
956 // always objects so we don't need to worry about complex or
957 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000958 RV = RValue::get(Builder.CreateBitCast(
959 RV.getScalarVal(),
960 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000961
962 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000963
964 // objc_getProperty does an autorelease, so we should suppress ours.
965 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000966
John McCallf4528ae2011-09-13 03:34:09 +0000967 return;
968 }
969
970 case PropertyImplStrategy::CopyStruct:
971 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
972 strategy.hasStrongMember());
973 return;
974
975 case PropertyImplStrategy::Expression:
976 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
977 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
978
979 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000980 switch (getEvaluationKind(ivarType)) {
981 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000982 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +0000983 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +0000984 /*init*/ true);
985 return;
986 }
987 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000988 // The return value slot is guaranteed to not be aliased, but
989 // that's not necessarily the same as "on the stack", so
990 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000991 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000992 return;
993 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000994 llvm::Value *value;
995 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +0000996 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +0000997 } else {
998 // We want to load and autoreleaseReturnValue ARC __weak ivars.
999 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001000 if (getLangOpts().ObjCAutoRefCount) {
1001 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1002 } else {
1003 value = EmitARCLoadWeak(LV.getAddress());
1004 }
John McCall24fada12011-07-22 05:23:13 +00001005
1006 // Otherwise we want to do a simple load, suppressing the
1007 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001008 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001009 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001010 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001011 }
John McCall31168b02011-06-15 23:02:42 +00001012
John McCall24fada12011-07-22 05:23:13 +00001013 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +00001014 value = Builder.CreateBitCast(
1015 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001016 }
1017
1018 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001019 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001020 }
John McCall47fb9502013-03-07 21:37:08 +00001021 }
1022 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001023 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001024
John McCallf4528ae2011-09-13 03:34:09 +00001025 }
1026 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001027}
1028
John McCallb923ece2011-09-12 23:06:44 +00001029/// emitStructSetterCall - Call the runtime function to store the value
1030/// from the first formal parameter into the given ivar.
1031static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1032 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001033 // objc_copyStruct (&structIvar, &Arg,
1034 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001035 CallArgList args;
1036
1037 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001038 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1039 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001040 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001041 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1042 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001043
1044 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001045 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001046 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +00001047 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001048 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001049 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1050 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001051
1052 // The third argument is the sizeof the type.
1053 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001054 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1055 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001056
John McCallb923ece2011-09-12 23:06:44 +00001057 // The fourth argument is the 'isAtomic' flag.
1058 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001059
John McCallb923ece2011-09-12 23:06:44 +00001060 // The fifth argument is the 'hasStrong' flag.
1061 // FIXME: should this really always be false?
1062 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1063
1064 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallc56a8b32016-03-11 04:30:31 +00001065 CGF.EmitCall(
1066 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb923ece2011-09-12 23:06:44 +00001067 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001068}
1069
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001070/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1071/// the value from the first formal parameter into the given ivar, using
1072/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1073static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1074 ObjCMethodDecl *OMD,
1075 ObjCIvarDecl *ivar,
1076 llvm::Constant *AtomicHelperFn) {
1077 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1078 // AtomicHelperFn);
1079 CallArgList args;
1080
1081 // The first argument is the address of the ivar.
1082 llvm::Value *ivarAddr =
1083 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001084 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001085 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1086 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1087
1088 // The second argument is the address of the parameter variable.
1089 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001090 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001091 VK_LValue, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001092 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001093 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1094 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1095
1096 // Third argument is the helper function.
1097 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1098
1099 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001100 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallc56a8b32016-03-11 04:30:31 +00001101 CGF.EmitCall(
1102 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001103 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001104}
1105
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001106
John McCallf4528ae2011-09-13 03:34:09 +00001107static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1108 Expr *setter = PID->getSetterCXXAssignment();
1109 if (!setter) return true;
1110
1111 // Sema only makes only of these when the ivar has a C++ class type,
1112 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001113
1114 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001115 // This also implies that there's nothing non-trivial going on with
1116 // the arguments, because operator= can only be trivial if it's a
1117 // synthesized assignment operator and therefore both parameters are
1118 // references.
1119 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001120 if (const FunctionDecl *callee
1121 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1122 if (callee->isTrivial())
1123 return true;
1124 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001125 }
John McCall7f16c422011-09-10 09:17:20 +00001126
John McCallf4528ae2011-09-13 03:34:09 +00001127 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001128 return false;
1129}
1130
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001131static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001132 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001133 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001134 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001135}
1136
John McCall7f16c422011-09-10 09:17:20 +00001137void
1138CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001139 const ObjCPropertyImplDecl *propImpl,
1140 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001141 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001142 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001143 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001144
1145 // Just use the setter expression if Sema gave us one and it's
1146 // non-trivial.
1147 if (!hasTrivialSetExpr(propImpl)) {
1148 if (!AtomicHelperFn)
1149 // If non-atomic, assignment is called directly.
1150 EmitStmt(propImpl->getSetterCXXAssignment());
1151 else
1152 // If atomic, assignment is called via a locking api.
1153 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1154 AtomicHelperFn);
1155 return;
1156 }
John McCall7f16c422011-09-10 09:17:20 +00001157
John McCallf4528ae2011-09-13 03:34:09 +00001158 PropertyImplStrategy strategy(CGM, propImpl);
1159 switch (strategy.getKind()) {
1160 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001161 // We don't need to do anything for a zero-size struct.
1162 if (strategy.getIvarSize().isZero())
1163 return;
1164
John McCall7f416cc2015-09-08 08:05:57 +00001165 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001166
John McCallf4528ae2011-09-13 03:34:09 +00001167 LValue ivarLValue =
1168 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001169 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001170
John McCallf4528ae2011-09-13 03:34:09 +00001171 // Currently, all atomic accesses have to be through integer
1172 // types, so there's no point in trying to pick a prettier type.
1173 llvm::Type *bitcastType =
1174 llvm::Type::getIntNTy(getLLVMContext(),
1175 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001176
1177 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001178 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1179 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001180
1181 // This bitcast load is likely to cause some nasty IR.
1182 llvm::Value *load = Builder.CreateLoad(argAddr);
1183
1184 // Perform an atomic store. There are no memory ordering requirements.
1185 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001186 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001187 return;
1188 }
1189
1190 case PropertyImplStrategy::GetSetProperty:
1191 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001192
1193 llvm::Value *setOptimizedPropertyFn = nullptr;
1194 llvm::Value *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001195 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001196 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001197 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001198 CGM.getObjCRuntime()
1199 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1200 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001201 if (!setOptimizedPropertyFn) {
1202 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1203 return;
1204 }
John McCall7f16c422011-09-10 09:17:20 +00001205 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001206 else {
1207 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1208 if (!setPropertyFn) {
1209 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1210 return;
1211 }
1212 }
1213
John McCall7f16c422011-09-10 09:17:20 +00001214 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1215 // <is-atomic>, <is-copy>).
1216 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001217 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001218 llvm::Value *self =
1219 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1220 llvm::Value *ivarOffset =
1221 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001222 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1223 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1224 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001225
1226 CallArgList args;
1227 args.add(RValue::get(self), getContext().getObjCIdType());
1228 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001229 if (setOptimizedPropertyFn) {
1230 args.add(RValue::get(arg), getContext().getObjCIdType());
1231 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallc56a8b32016-03-11 04:30:31 +00001232 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001233 setOptimizedPropertyFn, ReturnValueSlot(), args);
1234 } else {
1235 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1236 args.add(RValue::get(arg), getContext().getObjCIdType());
1237 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1238 getContext().BoolTy);
1239 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1240 getContext().BoolTy);
1241 // FIXME: We shouldn't need to get the function info here, the runtime
1242 // already should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001243 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001244 setPropertyFn, ReturnValueSlot(), args);
1245 }
1246
John McCall7f16c422011-09-10 09:17:20 +00001247 return;
1248 }
1249
John McCallf4528ae2011-09-13 03:34:09 +00001250 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001251 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001252 return;
John McCallf4528ae2011-09-13 03:34:09 +00001253
1254 case PropertyImplStrategy::Expression:
1255 break;
John McCall7f16c422011-09-10 09:17:20 +00001256 }
1257
1258 // Otherwise, fake up some ASTs and emit a normal assignment.
1259 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001260 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1261 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001262 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1263 selfDecl->getType(), CK_LValueToRValue, &self,
1264 VK_RValue);
1265 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001266 SourceLocation(), SourceLocation(),
1267 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001268
1269 ParmVarDecl *argDecl = *setterMethod->param_begin();
1270 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001271 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001272 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1273 argType.getUnqualifiedType(), CK_LValueToRValue,
1274 &arg, VK_RValue);
1275
1276 // The property type can differ from the ivar type in some situations with
1277 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1278 // The following absurdity is just to ensure well-formed IR.
1279 CastKind argCK = CK_NoOp;
1280 if (ivarRef.getType()->isObjCObjectPointerType()) {
1281 if (argLoad.getType()->isObjCObjectPointerType())
1282 argCK = CK_BitCast;
1283 else if (argLoad.getType()->isBlockPointerType())
1284 argCK = CK_BlockPointerToObjCPointerCast;
1285 else
1286 argCK = CK_CPointerToObjCPointerCast;
1287 } else if (ivarRef.getType()->isBlockPointerType()) {
1288 if (argLoad.getType()->isBlockPointerType())
1289 argCK = CK_BitCast;
1290 else
1291 argCK = CK_AnyPointerToBlockPointerCast;
1292 } else if (ivarRef.getType()->isPointerType()) {
1293 argCK = CK_BitCast;
1294 }
1295 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1296 ivarRef.getType(), argCK, &argLoad,
1297 VK_RValue);
1298 Expr *finalArg = &argLoad;
1299 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1300 argLoad.getType()))
1301 finalArg = &argCast;
1302
1303
1304 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1305 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001306 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001307 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001308}
1309
James Dennettbe302452012-06-15 22:10:14 +00001310/// \brief Generate an Objective-C property setter function.
1311///
1312/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001313/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001314void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1315 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001316 llvm::Constant *AtomicHelperFn =
1317 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001318 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1319 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1320 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001321 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001322
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001323 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001324
1325 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001326}
1327
John McCall6a4fa522011-03-22 07:05:39 +00001328namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001329 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001330 private:
1331 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001332 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001333 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001334 bool useEHCleanupForArray;
1335 public:
1336 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1337 CodeGenFunction::Destroyer *destroyer,
1338 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001339 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001340 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001341
Craig Topper4f12f102014-03-12 06:41:41 +00001342 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001343 LValue lvalue
1344 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1345 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001346 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001347 }
1348 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001349}
John McCall6a4fa522011-03-22 07:05:39 +00001350
John McCall4bd0fb12011-07-12 16:41:08 +00001351/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1352static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001353 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001354 QualType type) {
1355 llvm::Value *null = getNullForVariable(addr);
1356 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1357}
John McCall31168b02011-06-15 23:02:42 +00001358
John McCall6a4fa522011-03-22 07:05:39 +00001359static void emitCXXDestructMethod(CodeGenFunction &CGF,
1360 ObjCImplementationDecl *impl) {
1361 CodeGenFunction::RunCleanupsScope scope(CGF);
1362
1363 llvm::Value *self = CGF.LoadObjCSelf();
1364
Jordy Rosea91768e2011-07-22 02:08:32 +00001365 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1366 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001367 ivar; ivar = ivar->getNextIvar()) {
1368 QualType type = ivar->getType();
1369
John McCall6a4fa522011-03-22 07:05:39 +00001370 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001371 QualType::DestructionKind dtorKind = type.isDestructedType();
1372 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001373
Craig Topper8a13c412014-05-21 05:09:00 +00001374 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001375
John McCall4bd0fb12011-07-12 16:41:08 +00001376 // Use a call to objc_storeStrong to destroy strong ivars, for the
1377 // general benefit of the tools.
1378 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001379 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001380
John McCall4bd0fb12011-07-12 16:41:08 +00001381 // Otherwise use the default for the destruction kind.
1382 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001383 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001384 }
John McCall4bd0fb12011-07-12 16:41:08 +00001385
1386 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1387
1388 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1389 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001390 }
1391
1392 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1393}
1394
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001395void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1396 ObjCMethodDecl *MD,
1397 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001398 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001399 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001400
1401 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001402 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001403 // Suppress the final autorelease in ARC.
1404 AutoreleaseResult = false;
1405
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001406 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001407 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001408 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001409 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1410 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001411 EmitAggExpr(IvarInit->getInit(),
1412 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001413 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001414 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001415 }
1416 // constructor returns 'self'.
1417 CodeGenTypes &Types = CGM.getTypes();
1418 QualType IdTy(CGM.getContext().getObjCIdType());
1419 llvm::Value *SelfAsId =
1420 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1421 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001422
1423 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001424 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001425 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001426 }
1427 FinishFunction();
1428}
1429
Daniel Dunbara08dff12008-09-24 04:04:31 +00001430llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001431 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1432 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1433 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001434 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001435}
1436
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001437QualType CodeGenFunction::TypeOfSelfObject() {
1438 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1439 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001440 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1441 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001442 return PTy->getPointeeType();
1443}
1444
Chris Lattnerd4808922009-03-22 21:03:39 +00001445void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001446 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001447 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001448
Daniel Dunbara08dff12008-09-24 04:04:31 +00001449 if (!EnumerationMutationFn) {
1450 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1451 return;
1452 }
1453
Devang Pateld2d66652011-01-19 01:36:36 +00001454 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001455 if (DI)
1456 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001457
Devang Patel297207f2011-06-13 23:15:32 +00001458 // The local variable comes into scope immediately.
1459 AutoVarEmission variable = AutoVarEmission::invalid();
1460 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1461 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1462
John McCall1c926b72011-01-07 01:49:06 +00001463 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001464
Anders Carlsson75658592008-08-31 02:33:12 +00001465 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001466 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001467 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001468 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001469
Anders Carlsson75658592008-08-31 02:33:12 +00001470 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001471 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001472
John McCall1c926b72011-01-07 01:49:06 +00001473 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001474 IdentifierInfo *II[] = {
1475 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1476 &CGM.getContext().Idents.get("objects"),
1477 &CGM.getContext().Idents.get("count")
1478 };
1479 Selector FastEnumSel =
1480 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001481
1482 QualType ItemsTy =
1483 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001484 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001485 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001486 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001487
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001488 RunCleanupsScope ForScope(*this);
1489
John McCall53848232011-07-27 01:07:15 +00001490 // Emit the collection pointer. In ARC, we do a retain.
1491 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001492 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001493 Collection = EmitARCRetainScalarExpr(S.getCollection());
1494
1495 // Enter a cleanup to do the release.
1496 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1497 } else {
1498 Collection = EmitScalarExpr(S.getCollection());
1499 }
Mike Stump11289f42009-09-09 15:08:12 +00001500
John McCall91e82dd2011-08-05 00:14:38 +00001501 // The 'continue' label needs to appear within the cleanup for the
1502 // collection object.
1503 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1504
John McCall1c926b72011-01-07 01:49:06 +00001505 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001506 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001507
1508 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001509 Args.add(RValue::get(StatePtr.getPointer()),
1510 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001511
John McCall1c926b72011-01-07 01:49:06 +00001512 // The second argument is a temporary array with space for NumItems
1513 // pointers. We'll actually be loading elements from the array
1514 // pointer written into the control state; this buffer is so that
1515 // collections that *aren't* backed by arrays can still queue up
1516 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001517 Args.add(RValue::get(ItemsPtr.getPointer()),
1518 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001519
John McCall1c926b72011-01-07 01:49:06 +00001520 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001521 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001522 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001523 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001524
John McCall1c926b72011-01-07 01:49:06 +00001525 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001526 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001527 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001528 getContext().UnsignedLongTy,
1529 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001530 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001531
John McCall1c926b72011-01-07 01:49:06 +00001532 // The initial number of objects that were returned in the buffer.
1533 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001534
John McCall1c926b72011-01-07 01:49:06 +00001535 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1536 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001537
John McCall1c926b72011-01-07 01:49:06 +00001538 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001539
John McCall1c926b72011-01-07 01:49:06 +00001540 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001541 // empty; skip all this. Set the branch weight assuming this has the same
1542 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001543 uint64_t EntryCount = getCurrentProfileCount();
1544 Builder.CreateCondBr(
1545 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1546 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001547 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001548
John McCall1c926b72011-01-07 01:49:06 +00001549 // Otherwise, initialize the loop.
1550 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001551
John McCall1c926b72011-01-07 01:49:06 +00001552 // Save the initial mutations value. This is the value at an
1553 // address that was written into the state object by
1554 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001555 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1556 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1557 llvm::Value *StateMutationsPtr
1558 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001559
John McCall1c926b72011-01-07 01:49:06 +00001560 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001561 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1562 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001563
John McCall1c926b72011-01-07 01:49:06 +00001564 // Start looping. This is the point we return to whenever we have a
1565 // fresh, non-empty batch of objects.
1566 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1567 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001568
John McCall1c926b72011-01-07 01:49:06 +00001569 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001570 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001571 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001572
John McCall1c926b72011-01-07 01:49:06 +00001573 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001574 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001575 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001576
Justin Bogner66242d62015-04-23 23:06:47 +00001577 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001578
John McCall1c926b72011-01-07 01:49:06 +00001579 // Check whether the mutations value has changed from where it was
1580 // at start. StateMutationsPtr should actually be invariant between
1581 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001582 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001583 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001584 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1585 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001586
John McCall1c926b72011-01-07 01:49:06 +00001587 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001588 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001589
John McCall1c926b72011-01-07 01:49:06 +00001590 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1591 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCall1c926b72011-01-07 01:49:06 +00001593 // If so, call the enumeration-mutation function.
1594 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001595 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001596 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001597 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001598 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001599 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001600 // FIXME: We shouldn't need to get the function info here, the runtime already
1601 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001602 EmitCall(
1603 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001604 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001605
John McCall1c926b72011-01-07 01:49:06 +00001606 // Otherwise, or if the mutation function returns, just continue.
1607 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001608
John McCall1c926b72011-01-07 01:49:06 +00001609 // Initialize the element variable.
1610 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001611 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001612 LValue elementLValue;
1613 QualType elementType;
1614 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001615 // Initialize the variable, in case it's a __block variable or something.
1616 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001617
John McCall9e2e22f2011-02-22 07:16:58 +00001618 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001619 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001620 VK_LValue, SourceLocation());
1621 elementLValue = EmitLValue(&tempDRE);
1622 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001623 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001624
1625 if (D->isARCPseudoStrong())
1626 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001627 } else {
1628 elementLValue = LValue(); // suppress warning
1629 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001630 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001631 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001632 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001633
1634 // Fetch the buffer out of the enumeration state.
1635 // TODO: this pointer should actually be invariant between
1636 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001637 Address StateItemsPtr = Builder.CreateStructGEP(
1638 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001639 llvm::Value *EnumStateItems =
1640 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001641
John McCall1c926b72011-01-07 01:49:06 +00001642 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001643 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001644 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001645 llvm::Value *CurrentItem =
1646 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001647
John McCall1c926b72011-01-07 01:49:06 +00001648 // Cast that value to the right type.
1649 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1650 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001651
John McCall1c926b72011-01-07 01:49:06 +00001652 // Make sure we have an l-value. Yes, this gets evaluated every
1653 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001654 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001655 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001656 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001657 } else {
1658 EmitScalarInit(CurrentItem, elementLValue);
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
John McCall9e2e22f2011-02-22 07:16:58 +00001661 // If we do have an element variable, this assignment is the end of
1662 // its initialization.
1663 if (elementIsVariable)
1664 EmitAutoVarCleanups(variable);
1665
John McCall1c926b72011-01-07 01:49:06 +00001666 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001667 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001668 {
1669 RunCleanupsScope Scope(*this);
1670 EmitStmt(S.getBody());
1671 }
Anders Carlsson75658592008-08-31 02:33:12 +00001672 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001673
John McCall1c926b72011-01-07 01:49:06 +00001674 // Destroy the element variable now.
1675 elementVariableScope.ForceCleanup();
1676
1677 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001678 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001679
John McCall1c926b72011-01-07 01:49:06 +00001680 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001681
John McCall1c926b72011-01-07 01:49:06 +00001682 // First we check in the local buffer.
1683 llvm::Value *indexPlusOne
1684 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001685
John McCall1c926b72011-01-07 01:49:06 +00001686 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001687 // Set the branch weights based on the simplifying assumption that this is
1688 // like a while-loop, i.e., ignoring that the false branch fetches more
1689 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001690 Builder.CreateCondBr(
1691 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001692 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001693
1694 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1695 count->addIncoming(count, AfterBody.getBlock());
1696
1697 // Otherwise, we have to fetch more elements.
1698 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001699
1700 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001701 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001702 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001703 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001704 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001705
John McCall1c926b72011-01-07 01:49:06 +00001706 // If we got a zero count, we're done.
1707 llvm::Value *refetchCount = CountRV.getScalarVal();
1708
1709 // (note that the message send might split FetchMoreBB)
1710 index->addIncoming(zero, Builder.GetInsertBlock());
1711 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1712
1713 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1714 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001715
Anders Carlsson75658592008-08-31 02:33:12 +00001716 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001717 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001718
John McCall9e2e22f2011-02-22 07:16:58 +00001719 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001720 // If the element was not a declaration, set it to be null.
1721
John McCall1c926b72011-01-07 01:49:06 +00001722 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1723 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001724 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001725 }
1726
Eric Christopher7cdf9482011-10-13 21:45:18 +00001727 if (DI)
1728 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001729
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001730 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001731 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001732}
1733
Mike Stump11289f42009-09-09 15:08:12 +00001734void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001735 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001736}
1737
Mike Stump11289f42009-09-09 15:08:12 +00001738void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001739 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1740}
1741
Chris Lattnere132e242008-11-15 21:26:17 +00001742void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001743 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001744 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001745}
1746
John McCall31168b02011-06-15 23:02:42 +00001747namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001748 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001749 CallObjCRelease(llvm::Value *object) : object(object) {}
1750 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001751
Craig Topper4f12f102014-03-12 06:41:41 +00001752 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001753 // Releases at the end of the full-expression are imprecise.
1754 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001755 }
1756 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001757}
John McCall31168b02011-06-15 23:02:42 +00001758
John McCall2d637d22011-09-10 06:18:15 +00001759/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001760/// release at the end of the full-expression.
1761llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1762 llvm::Value *object) {
1763 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001764 // conditional.
1765 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001766 return object;
1767}
1768
1769llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1770 llvm::Value *value) {
1771 return EmitARCRetainAutorelease(type, value);
1772}
1773
John McCalleff18842013-03-23 02:35:54 +00001774/// Given a number of pointers, inform the optimizer that they're
1775/// being intrinsically used up until this point in the program.
1776void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
John McCallb04ecb72015-10-21 18:06:43 +00001777 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
John McCalleff18842013-03-23 02:35:54 +00001778 if (!fn) {
1779 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001780 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001781 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1782 }
1783
1784 // This isn't really a "runtime" function, but as an intrinsic it
1785 // doesn't really matter as long as we align things up.
1786 EmitNounwindRuntimeCall(fn, values);
1787}
1788
John McCall31168b02011-06-15 23:02:42 +00001789
1790static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001791 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001792 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001793 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1794
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001795 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001796 // If the target runtime doesn't naturally support ARC, emit weak
1797 // references to the runtime support library. We don't really
1798 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001799 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001800 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001801 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1802 // If we have Native ARC, set nonlazybind attribute for these APIs for
1803 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001804 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001805 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001806 }
John McCall31168b02011-06-15 23:02:42 +00001807
1808 return fn;
1809}
1810
1811/// Perform an operation having the signature
1812/// i8* (i8*)
1813/// where a null input causes a no-op and returns null.
1814static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1815 llvm::Value *value,
1816 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001817 StringRef fnName,
1818 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001819 if (isa<llvm::ConstantPointerNull>(value)) return value;
1820
1821 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001822 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001823 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001824 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1825 }
1826
1827 // Cast the argument to 'id'.
Pete Cooper94867712016-03-21 20:50:03 +00001828 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001829 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1830
1831 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001832 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001833 if (isTailCall)
1834 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001835
1836 // Cast the result back to the original type.
1837 return CGF.Builder.CreateBitCast(call, origType);
1838}
1839
1840/// Perform an operation having the following signature:
1841/// i8* (i8**)
1842static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001843 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001844 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001845 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001846 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001847 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001848 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001849 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1850 }
1851
1852 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001853 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001854 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1855
1856 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001857 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001858
1859 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001860 if (origType != CGF.Int8PtrTy)
1861 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001862
1863 return result;
1864}
1865
1866/// Perform an operation having the following signature:
1867/// i8* (i8**, i8*)
1868static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001869 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001870 llvm::Value *value,
1871 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001872 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001873 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001874 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001875
1876 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001877 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001878
Chris Lattner2192fe52011-07-18 04:24:23 +00001879 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001880 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1881 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1882 }
1883
Chris Lattner2192fe52011-07-18 04:24:23 +00001884 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001885
John McCall882987f2013-02-28 19:01:20 +00001886 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001887 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001888 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1889 };
1890 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001891
Craig Topper8a13c412014-05-21 05:09:00 +00001892 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001893
1894 return CGF.Builder.CreateBitCast(result, origType);
1895}
1896
1897/// Perform an operation having the following signature:
1898/// void (i8**, i8**)
1899static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001900 Address dst,
1901 Address src,
John McCall31168b02011-06-15 23:02:42 +00001902 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001903 StringRef fnName) {
John McCall7f416cc2015-09-08 08:05:57 +00001904 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00001905
1906 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001907 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1908
Chris Lattner2192fe52011-07-18 04:24:23 +00001909 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001910 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1911 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1912 }
1913
John McCall882987f2013-02-28 19:01:20 +00001914 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001915 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1916 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00001917 };
1918 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001919}
1920
1921/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001922/// call i8* \@objc_retain(i8* %value)
1923/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001924llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1925 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001926 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001927 else
1928 return EmitARCRetainNonBlock(value);
1929}
1930
1931/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001932/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00001933llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1934 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00001935 CGM.getObjCEntrypoints().objc_retain,
John McCall31168b02011-06-15 23:02:42 +00001936 "objc_retain");
1937}
1938
1939/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001940/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001941///
1942/// \param mandatory - If false, emit the call with metadata
1943/// indicating that it's okay for the optimizer to eliminate this call
1944/// if it can prove that the block never escapes except down the stack.
1945llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1946 bool mandatory) {
1947 llvm::Value *result
Pete Cooper94867712016-03-21 20:50:03 +00001948 = emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00001949 CGM.getObjCEntrypoints().objc_retainBlock,
John McCallff613032011-10-04 06:23:45 +00001950 "objc_retainBlock");
1951
1952 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1953 // tell the optimizer that it doesn't need to do this copy if the
1954 // block doesn't escape, where being passed as an argument doesn't
1955 // count as escaping.
1956 if (!mandatory && isa<llvm::Instruction>(result)) {
1957 llvm::CallInst *call
1958 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00001959 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00001960
John McCallff613032011-10-04 06:23:45 +00001961 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001962 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00001963 }
1964
1965 return result;
John McCall31168b02011-06-15 23:02:42 +00001966}
1967
John McCalle399e5b2016-01-27 18:32:30 +00001968static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00001969 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00001970 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00001971 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00001972 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00001973 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001974 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00001975 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00001976 .getARCRetainAutoreleasedReturnValueMarker();
1977
1978 // If we have an empty assembly string, there's nothing to do.
1979 if (assembly.empty()) {
1980
1981 // Otherwise, at -O0, build an inline asm that we're going to call
1982 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00001983 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00001984 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00001985 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001986
1987 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1988
1989 // If we're at -O1 and above, we don't want to litter the code
1990 // with this marker yet, so leave a breadcrumb for the ARC
1991 // optimizer to pick up.
1992 } else {
1993 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00001994 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00001995 "clang.arc.retainAutoreleasedReturnValueMarker");
1996 assert(metadata->getNumOperands() <= 1);
1997 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00001998 auto &ctx = CGF.getLLVMContext();
1999 metadata->addOperand(llvm::MDNode::get(ctx,
2000 llvm::MDString::get(ctx, assembly)));
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.
David Blaikie43f9bb72015-05-18 22:14:03 +00002006 if (marker)
John McCalle399e5b2016-01-27 18:32:30 +00002007 CGF.Builder.CreateCall(marker);
2008}
John McCall31168b02011-06-15 23:02:42 +00002009
John McCalle399e5b2016-01-27 18:32:30 +00002010/// Retain the given object which is the result of a function call.
2011/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2012///
2013/// Yes, this function name is one character away from a different
2014/// call with completely different semantics.
2015llvm::Value *
2016CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2017 emitAutoreleasedReturnValueMarker(*this);
Pete Cooper94867712016-03-21 20:50:03 +00002018 return emitARCValueOperation(*this, value,
John McCalle399e5b2016-01-27 18:32:30 +00002019 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
John McCall31168b02011-06-15 23:02:42 +00002020 "objc_retainAutoreleasedReturnValue");
2021}
2022
John McCalle399e5b2016-01-27 18:32:30 +00002023/// Claim a possibly-autoreleased return value at +0. This is only
2024/// valid to do in contexts which do not rely on the retain to keep
2025/// the object valid for for all of its uses; for example, when
2026/// the value is ignored, or when it is being assigned to an
2027/// __unsafe_unretained variable.
2028///
2029/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2030llvm::Value *
2031CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2032 emitAutoreleasedReturnValueMarker(*this);
Pete Cooper94867712016-03-21 20:50:03 +00002033 return emitARCValueOperation(*this, value,
John McCalle399e5b2016-01-27 18:32:30 +00002034 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
2035 "objc_unsafeClaimAutoreleasedReturnValue");
2036}
2037
John McCall31168b02011-06-15 23:02:42 +00002038/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002039/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002040void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2041 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002042 if (isa<llvm::ConstantPointerNull>(value)) return;
2043
John McCallb04ecb72015-10-21 18:06:43 +00002044 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002045 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002046 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002047 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002048 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2049 }
2050
2051 // Cast the argument to 'id'.
2052 value = Builder.CreateBitCast(value, Int8PtrTy);
2053
2054 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002055 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002056
John McCallcdda29c2013-03-13 03:10:54 +00002057 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002058 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002059 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002060 }
2061}
2062
John McCalle68b8f42012-10-17 02:28:37 +00002063/// Destroy a __strong variable.
2064///
2065/// At -O0, emit a call to store 'null' into the address;
2066/// instrumenting tools prefer this because the address is exposed,
2067/// but it's relatively cumbersome to optimize.
2068///
2069/// At -O1 and above, just load and call objc_release.
2070///
2071/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002072void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002073 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002074 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002075 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002076 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2077 return;
2078 }
2079
2080 llvm::Value *value = Builder.CreateLoad(addr);
2081 EmitARCRelease(value, precise);
2082}
2083
John McCall31168b02011-06-15 23:02:42 +00002084/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002085/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002086llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002087 llvm::Value *value,
2088 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002089 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002090
John McCallb04ecb72015-10-21 18:06:43 +00002091 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002092 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002093 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002094 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002095 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2096 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2097 }
2098
John McCall882987f2013-02-28 19:01:20 +00002099 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002100 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002101 Builder.CreateBitCast(value, Int8PtrTy)
2102 };
2103 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002104
Craig Topper8a13c412014-05-21 05:09:00 +00002105 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002106 return value;
2107}
2108
2109/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002110/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002111/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002112llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002113 llvm::Value *newValue,
2114 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002115 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002116 bool isBlock = type->isBlockPointerType();
2117
2118 // Use a store barrier at -O0 unless this is a block type or the
2119 // lvalue is inadequately aligned.
2120 if (shouldUseFusedARCCalls() &&
2121 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002122 (dst.getAlignment().isZero() ||
2123 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002124 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2125 }
2126
2127 // Otherwise, split it out.
2128
2129 // Retain the new value.
2130 newValue = EmitARCRetain(type, newValue);
2131
2132 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002133 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002134
2135 // Store. We do this before the release so that any deallocs won't
2136 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002137 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002138
2139 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002140 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002141
2142 return newValue;
2143}
2144
2145/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002146/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002147llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2148 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002149 CGM.getObjCEntrypoints().objc_autorelease,
John McCall31168b02011-06-15 23:02:42 +00002150 "objc_autorelease");
2151}
2152
2153/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002154/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002155llvm::Value *
2156CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Cooper94867712016-03-21 20:50:03 +00002157 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002158 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002159 "objc_autoreleaseReturnValue",
2160 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002161}
2162
2163/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002164/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002165llvm::Value *
2166CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Cooper94867712016-03-21 20:50:03 +00002167 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002168 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002169 "objc_retainAutoreleaseReturnValue",
2170 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002171}
2172
2173/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002174/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002175/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002176/// %retain = call i8* \@objc_retainBlock(i8* %value)
2177/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002178llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2179 llvm::Value *value) {
2180 if (!type->isBlockPointerType())
2181 return EmitARCRetainAutoreleaseNonBlock(value);
2182
2183 if (isa<llvm::ConstantPointerNull>(value)) return value;
2184
Chris Lattner2192fe52011-07-18 04:24:23 +00002185 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002186 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002187 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002188 value = EmitARCAutorelease(value);
2189 return Builder.CreateBitCast(value, origType);
2190}
2191
2192/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002193/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002194llvm::Value *
2195CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Cooper94867712016-03-21 20:50:03 +00002196 return emitARCValueOperation(*this, value,
John McCallb04ecb72015-10-21 18:06:43 +00002197 CGM.getObjCEntrypoints().objc_retainAutorelease,
John McCall31168b02011-06-15 23:02:42 +00002198 "objc_retainAutorelease");
2199}
2200
John McCallb04ecb72015-10-21 18:06:43 +00002201/// i8* \@objc_loadWeak(i8** %addr)
2202/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2203llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2204 return emitARCLoadOperation(*this, addr,
2205 CGM.getObjCEntrypoints().objc_loadWeak,
2206 "objc_loadWeak");
2207}
2208
James Dennett14c41ea2012-06-22 05:41:30 +00002209/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002210llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002211 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002212 CGM.getObjCEntrypoints().objc_loadWeakRetained,
John McCall31168b02011-06-15 23:02:42 +00002213 "objc_loadWeakRetained");
2214}
2215
James Dennett14c41ea2012-06-22 05:41:30 +00002216/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002217/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002218llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002219 llvm::Value *value,
2220 bool ignored) {
2221 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002222 CGM.getObjCEntrypoints().objc_storeWeak,
John McCall31168b02011-06-15 23:02:42 +00002223 "objc_storeWeak", ignored);
2224}
2225
James Dennett14c41ea2012-06-22 05:41:30 +00002226/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002227/// Returns %value. %addr is known to not have a current weak entry.
2228/// Essentially equivalent to:
2229/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002230void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002231 // If we're initializing to null, just write null to memory; no need
2232 // to get the runtime involved. But don't do this if optimization
2233 // is enabled, because accounting for this would make the optimizer
2234 // much more complicated.
2235 if (isa<llvm::ConstantPointerNull>(value) &&
2236 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2237 Builder.CreateStore(value, addr);
2238 return;
2239 }
2240
2241 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002242 CGM.getObjCEntrypoints().objc_initWeak,
John McCall31168b02011-06-15 23:02:42 +00002243 "objc_initWeak", /*ignored*/ true);
2244}
2245
James Dennett14c41ea2012-06-22 05:41:30 +00002246/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002247/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002248void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCallb04ecb72015-10-21 18:06:43 +00002249 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002250 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002251 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002252 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002253 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2254 }
2255
2256 // Cast the argument to 'id*'.
2257 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2258
John McCall7f416cc2015-09-08 08:05:57 +00002259 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002260}
2261
James Dennett14c41ea2012-06-22 05:41:30 +00002262/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002263/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2264/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002265void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002266 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002267 CGM.getObjCEntrypoints().objc_moveWeak,
John McCall31168b02011-06-15 23:02:42 +00002268 "objc_moveWeak");
2269}
2270
James Dennett14c41ea2012-06-22 05:41:30 +00002271/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002272/// Disregards the current value in %dest. Essentially
2273/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002274void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002275 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002276 CGM.getObjCEntrypoints().objc_copyWeak,
John McCall31168b02011-06-15 23:02:42 +00002277 "objc_copyWeak");
2278}
2279
2280/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002281/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002282llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
John McCallb04ecb72015-10-21 18:06:43 +00002283 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002284 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002285 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002286 llvm::FunctionType::get(Int8PtrTy, false);
2287 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2288 }
2289
John McCall882987f2013-02-28 19:01:20 +00002290 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002291}
2292
2293/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002294/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002295void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2296 assert(value->getType() == Int8PtrTy);
2297
John McCallb04ecb72015-10-21 18:06:43 +00002298 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
John McCall31168b02011-06-15 23:02:42 +00002299 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002300 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002301 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002302
2303 // We don't want to use a weak import here; instead we should not
2304 // fall into this path.
2305 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2306 }
2307
John McCallb7ff6db2013-04-16 21:29:40 +00002308 // objc_autoreleasePoolPop can throw.
2309 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002310}
2311
2312/// Produce the code to do an MRR version objc_autoreleasepool_push.
2313/// Which is: [[NSAutoreleasePool alloc] init];
2314/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2315/// init is declared as: - (id) init; in its NSObject super class.
2316///
2317llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2318 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002319 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002320 // [NSAutoreleasePool alloc]
2321 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2322 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2323 CallArgList Args;
2324 RValue AllocRV =
2325 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2326 getContext().getObjCIdType(),
2327 AllocSel, Receiver, Args);
2328
2329 // [Receiver init]
2330 Receiver = AllocRV.getScalarVal();
2331 II = &CGM.getContext().Idents.get("init");
2332 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2333 RValue InitRV =
2334 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2335 getContext().getObjCIdType(),
2336 InitSel, Receiver, Args);
2337 return InitRV.getScalarVal();
2338}
2339
2340/// Produce the code to do a primitive release.
2341/// [tmp drain];
2342void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2343 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2344 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2345 CallArgList Args;
2346 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2347 getContext().VoidTy, DrainSel, Arg, Args);
2348}
2349
John McCall82fe67b2011-07-09 01:37:26 +00002350void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002351 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002352 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002353 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002354}
2355
2356void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002357 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002358 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002359 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002360}
2361
2362void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002363 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002364 QualType type) {
2365 CGF.EmitARCDestroyWeak(addr);
2366}
2367
John McCall31168b02011-06-15 23:02:42 +00002368namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002369 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002370 llvm::Value *Token;
2371
2372 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2373
Craig Topper4f12f102014-03-12 06:41:41 +00002374 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002375 CGF.EmitObjCAutoreleasePoolPop(Token);
2376 }
2377 };
David Blaikie7e70d682015-08-18 22:40:54 +00002378 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002379 llvm::Value *Token;
2380
2381 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2382
Craig Topper4f12f102014-03-12 06:41:41 +00002383 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002384 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2385 }
2386 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002387}
John McCall31168b02011-06-15 23:02:42 +00002388
2389void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002390 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002391 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2392 else
2393 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2394}
2395
John McCall31168b02011-06-15 23:02:42 +00002396static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2397 LValue lvalue,
2398 QualType type) {
2399 switch (type.getObjCLifetime()) {
2400 case Qualifiers::OCL_None:
2401 case Qualifiers::OCL_ExplicitNone:
2402 case Qualifiers::OCL_Strong:
2403 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002404 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2405 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002406 false);
2407
2408 case Qualifiers::OCL_Weak:
2409 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2410 true);
2411 }
2412
2413 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002414}
2415
2416static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2417 const Expr *e) {
2418 e = e->IgnoreParens();
2419 QualType type = e->getType();
2420
John McCall154a2fd2011-08-30 00:57:29 +00002421 // If we're loading retained from a __strong xvalue, we can avoid
2422 // an extra retain/release pair by zeroing out the source of this
2423 // "move" operation.
2424 if (e->isXValue() &&
2425 !type.isConstQualified() &&
2426 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2427 // Emit the lvalue.
2428 LValue lv = CGF.EmitLValue(e);
2429
2430 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002431 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2432 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002433
2434 // Set the source pointer to NULL.
2435 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2436
2437 return TryEmitResult(result, true);
2438 }
2439
John McCall31168b02011-06-15 23:02:42 +00002440 // As a very special optimization, in ARC++, if the l-value is the
2441 // result of a non-volatile assignment, do a simple retain of the
2442 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002443 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002444 !type.isVolatileQualified() &&
2445 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2446 isa<BinaryOperator>(e) &&
2447 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2448 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2449
2450 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2451}
2452
John McCalle399e5b2016-01-27 18:32:30 +00002453typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2454 llvm::Value *value)>
2455 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002456
John McCalle399e5b2016-01-27 18:32:30 +00002457/// Insert code immediately after a call.
2458static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2459 llvm::Value *value,
2460 ValueTransform doAfterCall,
2461 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002462 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2463 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2464
2465 // Place the retain immediately following the call.
2466 CGF.Builder.SetInsertPoint(call->getParent(),
2467 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002468 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002469
2470 CGF.Builder.restoreIP(ip);
2471 return value;
2472 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2473 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2474
2475 // Place the retain at the beginning of the normal destination block.
2476 llvm::BasicBlock *BB = invoke->getNormalDest();
2477 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002478 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002479
2480 CGF.Builder.restoreIP(ip);
2481 return value;
2482
2483 // Bitcasts can arise because of related-result returns. Rewrite
2484 // the operand.
2485 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2486 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002487 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002488 bitcast->setOperand(0, operand);
2489 return bitcast;
2490
2491 // Generic fall-back case.
2492 } else {
2493 // Retain using the non-block variant: we never need to do a copy
2494 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002495 return doFallback(CGF, value);
2496 }
2497}
2498
2499/// Given that the given expression is some sort of call (which does
2500/// not return retained), emit a retain following it.
2501static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2502 const Expr *e) {
2503 llvm::Value *value = CGF.EmitScalarExpr(e);
2504 return emitARCOperationAfterCall(CGF, value,
2505 [](CodeGenFunction &CGF, llvm::Value *value) {
2506 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2507 },
2508 [](CodeGenFunction &CGF, llvm::Value *value) {
2509 return CGF.EmitARCRetainNonBlock(value);
2510 });
2511}
2512
2513/// Given that the given expression is some sort of call (which does
2514/// not return retained), perform an unsafeClaim following it.
2515static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2516 const Expr *e) {
2517 llvm::Value *value = CGF.EmitScalarExpr(e);
2518 return emitARCOperationAfterCall(CGF, value,
2519 [](CodeGenFunction &CGF, llvm::Value *value) {
2520 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2521 },
2522 [](CodeGenFunction &CGF, llvm::Value *value) {
2523 return value;
2524 });
2525}
2526
2527llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2528 bool allowUnsafeClaim) {
2529 if (allowUnsafeClaim &&
2530 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2531 return emitARCUnsafeClaimCallResult(*this, E);
2532 } else {
2533 llvm::Value *value = emitARCRetainCallResult(*this, E);
2534 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002535 }
2536}
2537
John McCallcd78e802011-09-10 01:16:55 +00002538/// Determine whether it might be important to emit a separate
2539/// objc_retain_block on the result of the given expression, or
2540/// whether it's okay to just emit it in a +1 context.
2541static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2542 assert(e->getType()->isBlockPointerType());
2543 e = e->IgnoreParens();
2544
2545 // For future goodness, emit block expressions directly in +1
2546 // contexts if we can.
2547 if (isa<BlockExpr>(e))
2548 return false;
2549
2550 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2551 switch (cast->getCastKind()) {
2552 // Emitting these operations in +1 contexts is goodness.
2553 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002554 case CK_ARCReclaimReturnedObject:
2555 case CK_ARCConsumeObject:
2556 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002557 return false;
2558
2559 // These operations preserve a block type.
2560 case CK_NoOp:
2561 case CK_BitCast:
2562 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2563
2564 // These operations are known to be bad (or haven't been considered).
2565 case CK_AnyPointerToBlockPointerCast:
2566 default:
2567 return true;
2568 }
2569 }
2570
2571 return true;
2572}
2573
John McCalle399e5b2016-01-27 18:32:30 +00002574namespace {
2575/// A CRTP base class for emitting expressions of retainable object
2576/// pointer type in ARC.
2577template <typename Impl, typename Result> class ARCExprEmitter {
2578protected:
2579 CodeGenFunction &CGF;
2580 Impl &asImpl() { return *static_cast<Impl*>(this); }
2581
2582 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2583
2584public:
2585 Result visit(const Expr *e);
2586 Result visitCastExpr(const CastExpr *e);
2587 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2588 Result visitBinaryOperator(const BinaryOperator *e);
2589 Result visitBinAssign(const BinaryOperator *e);
2590 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2591 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2592 Result visitBinAssignWeak(const BinaryOperator *e);
2593 Result visitBinAssignStrong(const BinaryOperator *e);
2594
2595 // Minimal implementation:
2596 // Result visitLValueToRValue(const Expr *e)
2597 // Result visitConsumeObject(const Expr *e)
2598 // Result visitExtendBlockObject(const Expr *e)
2599 // Result visitReclaimReturnedObject(const Expr *e)
2600 // Result visitCall(const Expr *e)
2601 // Result visitExpr(const Expr *e)
2602 //
2603 // Result emitBitCast(Result result, llvm::Type *resultType)
2604 // llvm::Value *getValueOfResult(Result result)
2605};
2606}
2607
2608/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002609///
2610/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002611template <typename Impl, typename Result>
2612Result
2613ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002614 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002615
2616 // Find the result expression.
2617 const Expr *resultExpr = E->getResultExpr();
2618 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002619 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002620
2621 for (PseudoObjectExpr::const_semantics_iterator
2622 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2623 const Expr *semantic = *i;
2624
2625 // If this semantic expression is an opaque value, bind it
2626 // to the result of its source expression.
2627 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2628 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2629 OVMA opaqueData;
2630
2631 // If this semantic is the result of the pseudo-object
2632 // expression, try to evaluate the source as +1.
2633 if (ov == resultExpr) {
2634 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002635 result = asImpl().visit(ov->getSourceExpr());
2636 opaqueData = OVMA::bind(CGF, ov,
2637 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002638
2639 // Otherwise, just bind it.
2640 } else {
2641 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2642 }
2643 opaques.push_back(opaqueData);
2644
2645 // Otherwise, if the expression is the result, evaluate it
2646 // and remember the result.
2647 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002648 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002649
2650 // Otherwise, evaluate the expression in an ignored context.
2651 } else {
2652 CGF.EmitIgnoredExpr(semantic);
2653 }
2654 }
2655
2656 // Unbind all the opaques now.
2657 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2658 opaques[i].unbind(CGF);
2659
2660 return result;
2661}
2662
John McCalle399e5b2016-01-27 18:32:30 +00002663template <typename Impl, typename Result>
2664Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2665 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002666
John McCalle399e5b2016-01-27 18:32:30 +00002667 // No-op casts don't change the type, so we just ignore them.
2668 case CK_NoOp:
2669 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002670
John McCalle399e5b2016-01-27 18:32:30 +00002671 // These casts can change the type.
2672 case CK_CPointerToObjCPointerCast:
2673 case CK_BlockPointerToObjCPointerCast:
2674 case CK_AnyPointerToBlockPointerCast:
2675 case CK_BitCast: {
2676 llvm::Type *resultType = CGF.ConvertType(e->getType());
2677 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2678 Result result = asImpl().visit(e->getSubExpr());
2679 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002680 }
2681
John McCalle399e5b2016-01-27 18:32:30 +00002682 // Handle some casts specially.
2683 case CK_LValueToRValue:
2684 return asImpl().visitLValueToRValue(e->getSubExpr());
2685 case CK_ARCConsumeObject:
2686 return asImpl().visitConsumeObject(e->getSubExpr());
2687 case CK_ARCExtendBlockObject:
2688 return asImpl().visitExtendBlockObject(e->getSubExpr());
2689 case CK_ARCReclaimReturnedObject:
2690 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2691
2692 // Otherwise, use the default logic.
2693 default:
2694 return asImpl().visitExpr(e);
2695 }
2696}
2697
2698template <typename Impl, typename Result>
2699Result
2700ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2701 switch (e->getOpcode()) {
2702 case BO_Comma:
2703 CGF.EmitIgnoredExpr(e->getLHS());
2704 CGF.EnsureInsertPoint();
2705 return asImpl().visit(e->getRHS());
2706
2707 case BO_Assign:
2708 return asImpl().visitBinAssign(e);
2709
2710 default:
2711 return asImpl().visitExpr(e);
2712 }
2713}
2714
2715template <typename Impl, typename Result>
2716Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2717 switch (e->getLHS()->getType().getObjCLifetime()) {
2718 case Qualifiers::OCL_ExplicitNone:
2719 return asImpl().visitBinAssignUnsafeUnretained(e);
2720
2721 case Qualifiers::OCL_Weak:
2722 return asImpl().visitBinAssignWeak(e);
2723
2724 case Qualifiers::OCL_Autoreleasing:
2725 return asImpl().visitBinAssignAutoreleasing(e);
2726
2727 case Qualifiers::OCL_Strong:
2728 return asImpl().visitBinAssignStrong(e);
2729
2730 case Qualifiers::OCL_None:
2731 return asImpl().visitExpr(e);
2732 }
2733 llvm_unreachable("bad ObjC ownership qualifier");
2734}
2735
2736/// The default rule for __unsafe_unretained emits the RHS recursively,
2737/// stores into the unsafe variable, and propagates the result outward.
2738template <typename Impl, typename Result>
2739Result ARCExprEmitter<Impl,Result>::
2740 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2741 // Recursively emit the RHS.
2742 // For __block safety, do this before emitting the LHS.
2743 Result result = asImpl().visit(e->getRHS());
2744
2745 // Perform the store.
2746 LValue lvalue =
2747 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2748 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2749 lvalue);
2750
2751 return result;
2752}
2753
2754template <typename Impl, typename Result>
2755Result
2756ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2757 return asImpl().visitExpr(e);
2758}
2759
2760template <typename Impl, typename Result>
2761Result
2762ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
2763 return asImpl().visitExpr(e);
2764}
2765
2766template <typename Impl, typename Result>
2767Result
2768ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
2769 return asImpl().visitExpr(e);
2770}
2771
2772/// The general expression-emission logic.
2773template <typename Impl, typename Result>
2774Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
2775 // We should *never* see a nested full-expression here, because if
2776 // we fail to emit at +1, our caller must not retain after we close
2777 // out the full-expression. This isn't as important in the unsafe
2778 // emitter.
2779 assert(!isa<ExprWithCleanups>(e));
2780
2781 // Look through parens, __extension__, generic selection, etc.
2782 e = e->IgnoreParens();
2783
2784 // Handle certain kinds of casts.
2785 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2786 return asImpl().visitCastExpr(ce);
2787
2788 // Handle the comma operator.
2789 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
2790 return asImpl().visitBinaryOperator(op);
2791
2792 // TODO: handle conditional operators here
2793
2794 // For calls and message sends, use the retained-call logic.
2795 // Delegate inits are a special case in that they're the only
2796 // returns-retained expression that *isn't* surrounded by
2797 // a consume.
2798 } else if (isa<CallExpr>(e) ||
2799 (isa<ObjCMessageExpr>(e) &&
2800 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2801 return asImpl().visitCall(e);
2802
2803 // Look through pseudo-object expressions.
2804 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2805 return asImpl().visitPseudoObjectExpr(pseudo);
2806 }
2807
2808 return asImpl().visitExpr(e);
2809}
2810
2811namespace {
2812
2813/// An emitter for +1 results.
2814struct ARCRetainExprEmitter :
2815 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
2816
2817 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
2818
2819 llvm::Value *getValueOfResult(TryEmitResult result) {
2820 return result.getPointer();
2821 }
2822
2823 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
2824 llvm::Value *value = result.getPointer();
2825 value = CGF.Builder.CreateBitCast(value, resultType);
2826 result.setPointer(value);
2827 return result;
2828 }
2829
2830 TryEmitResult visitLValueToRValue(const Expr *e) {
2831 return tryEmitARCRetainLoadOfScalar(CGF, e);
2832 }
2833
2834 /// For consumptions, just emit the subexpression and thus elide
2835 /// the retain/release pair.
2836 TryEmitResult visitConsumeObject(const Expr *e) {
2837 llvm::Value *result = CGF.EmitScalarExpr(e);
2838 return TryEmitResult(result, true);
2839 }
2840
2841 /// Block extends are net +0. Naively, we could just recurse on
2842 /// the subexpression, but actually we need to ensure that the
2843 /// value is copied as a block, so there's a little filter here.
2844 TryEmitResult visitExtendBlockObject(const Expr *e) {
2845 llvm::Value *result; // will be a +0 value
2846
2847 // If we can't safely assume the sub-expression will produce a
2848 // block-copied value, emit the sub-expression at +0.
2849 if (shouldEmitSeparateBlockRetain(e)) {
2850 result = CGF.EmitScalarExpr(e);
2851
2852 // Otherwise, try to emit the sub-expression at +1 recursively.
2853 } else {
2854 TryEmitResult subresult = asImpl().visit(e);
2855
2856 // If that produced a retained value, just use that.
2857 if (subresult.getInt()) {
2858 return subresult;
2859 }
2860
2861 // Otherwise it's +0.
2862 result = subresult.getPointer();
2863 }
2864
2865 // Retain the object as a block.
2866 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2867 return TryEmitResult(result, true);
2868 }
2869
2870 /// For reclaims, emit the subexpression as a retained call and
2871 /// skip the consumption.
2872 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
2873 llvm::Value *result = emitARCRetainCallResult(CGF, e);
2874 return TryEmitResult(result, true);
2875 }
2876
2877 /// When we have an undecorated call, retroactively do a claim.
2878 TryEmitResult visitCall(const Expr *e) {
2879 llvm::Value *result = emitARCRetainCallResult(CGF, e);
2880 return TryEmitResult(result, true);
2881 }
2882
2883 // TODO: maybe special-case visitBinAssignWeak?
2884
2885 TryEmitResult visitExpr(const Expr *e) {
2886 // We didn't find an obvious production, so emit what we've got and
2887 // tell the caller that we didn't manage to retain.
2888 llvm::Value *result = CGF.EmitScalarExpr(e);
2889 return TryEmitResult(result, false);
2890 }
2891};
2892}
2893
2894static TryEmitResult
2895tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2896 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00002897}
2898
2899static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2900 LValue lvalue,
2901 QualType type) {
2902 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2903 llvm::Value *value = result.getPointer();
2904 if (!result.getInt())
2905 value = CGF.EmitARCRetain(type, value);
2906 return value;
2907}
2908
2909/// EmitARCRetainScalarExpr - Semantically equivalent to
2910/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2911/// best-effort attempt to peephole expressions that naturally produce
2912/// retained objects.
2913llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002914 // The retain needs to happen within the full-expression.
2915 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2916 enterFullExpression(cleanups);
2917 RunCleanupsScope scope(*this);
2918 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2919 }
2920
John McCall31168b02011-06-15 23:02:42 +00002921 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2922 llvm::Value *value = result.getPointer();
2923 if (!result.getInt())
2924 value = EmitARCRetain(e->getType(), value);
2925 return value;
2926}
2927
2928llvm::Value *
2929CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002930 // The retain needs to happen within the full-expression.
2931 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2932 enterFullExpression(cleanups);
2933 RunCleanupsScope scope(*this);
2934 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2935 }
2936
John McCall31168b02011-06-15 23:02:42 +00002937 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2938 llvm::Value *value = result.getPointer();
2939 if (result.getInt())
2940 value = EmitARCAutorelease(value);
2941 else
2942 value = EmitARCRetainAutorelease(e->getType(), value);
2943 return value;
2944}
2945
John McCallff613032011-10-04 06:23:45 +00002946llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2947 llvm::Value *result;
2948 bool doRetain;
2949
2950 if (shouldEmitSeparateBlockRetain(e)) {
2951 result = EmitScalarExpr(e);
2952 doRetain = true;
2953 } else {
2954 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2955 result = subresult.getPointer();
2956 doRetain = !subresult.getInt();
2957 }
2958
2959 if (doRetain)
2960 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2961 return EmitObjCConsumeObject(e->getType(), result);
2962}
2963
John McCall248512a2011-10-01 10:32:24 +00002964llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2965 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002966 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002967 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002968 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002969 return EmitARCRetainAutoreleaseScalarExpr(expr);
2970 }
2971
2972 // Otherwise, use the normal scalar-expression emission. The
2973 // exception machinery doesn't do anything special with the
2974 // exception like retaining it, so there's no safety associated with
2975 // only running cleanups after the throw has started, and when it
2976 // matters it tends to be substantially inferior code.
2977 return EmitScalarExpr(expr);
2978}
2979
John McCalle399e5b2016-01-27 18:32:30 +00002980namespace {
2981
2982/// An emitter for assigning into an __unsafe_unretained context.
2983struct ARCUnsafeUnretainedExprEmitter :
2984 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
2985
2986 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
2987
2988 llvm::Value *getValueOfResult(llvm::Value *value) {
2989 return value;
2990 }
2991
2992 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
2993 return CGF.Builder.CreateBitCast(value, resultType);
2994 }
2995
2996 llvm::Value *visitLValueToRValue(const Expr *e) {
2997 return CGF.EmitScalarExpr(e);
2998 }
2999
3000 /// For consumptions, just emit the subexpression and perform the
3001 /// consumption like normal.
3002 llvm::Value *visitConsumeObject(const Expr *e) {
3003 llvm::Value *value = CGF.EmitScalarExpr(e);
3004 return CGF.EmitObjCConsumeObject(e->getType(), value);
3005 }
3006
3007 /// No special logic for block extensions. (This probably can't
3008 /// actually happen in this emitter, though.)
3009 llvm::Value *visitExtendBlockObject(const Expr *e) {
3010 return CGF.EmitARCExtendBlockObject(e);
3011 }
3012
3013 /// For reclaims, perform an unsafeClaim if that's enabled.
3014 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3015 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3016 }
3017
3018 /// When we have an undecorated call, just emit it without adding
3019 /// the unsafeClaim.
3020 llvm::Value *visitCall(const Expr *e) {
3021 return CGF.EmitScalarExpr(e);
3022 }
3023
3024 /// Just do normal scalar emission in the default case.
3025 llvm::Value *visitExpr(const Expr *e) {
3026 return CGF.EmitScalarExpr(e);
3027 }
3028};
3029}
3030
3031static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3032 const Expr *e) {
3033 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3034}
3035
3036/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3037/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3038/// avoiding any spurious retains, including by performing reclaims
3039/// with objc_unsafeClaimAutoreleasedReturnValue.
3040llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3041 // Look through full-expressions.
3042 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3043 enterFullExpression(cleanups);
3044 RunCleanupsScope scope(*this);
3045 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3046 }
3047
3048 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3049}
3050
3051std::pair<LValue,llvm::Value*>
3052CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3053 bool ignored) {
3054 // Evaluate the RHS first. If we're ignoring the result, assume
3055 // that we can emit at an unsafe +0.
3056 llvm::Value *value;
3057 if (ignored) {
3058 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3059 } else {
3060 value = EmitScalarExpr(e->getRHS());
3061 }
3062
3063 // Emit the LHS and perform the store.
3064 LValue lvalue = EmitLValue(e->getLHS());
3065 EmitStoreOfScalar(value, lvalue);
3066
3067 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3068}
3069
John McCall31168b02011-06-15 23:02:42 +00003070std::pair<LValue,llvm::Value*>
3071CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3072 bool ignored) {
3073 // Evaluate the RHS first.
3074 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3075 llvm::Value *value = result.getPointer();
3076
John McCallb726a552011-07-28 07:23:35 +00003077 bool hasImmediateRetain = result.getInt();
3078
3079 // If we didn't emit a retained object, and the l-value is of block
3080 // type, then we need to emit the block-retain immediately in case
3081 // it invalidates the l-value.
3082 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003083 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003084 hasImmediateRetain = true;
3085 }
3086
John McCall31168b02011-06-15 23:02:42 +00003087 LValue lvalue = EmitLValue(e->getLHS());
3088
3089 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003090 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003091 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003092 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003093 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003094 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003095 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003096 }
3097
3098 return std::pair<LValue,llvm::Value*>(lvalue, value);
3099}
3100
3101std::pair<LValue,llvm::Value*>
3102CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3103 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3104 LValue lvalue = EmitLValue(e->getLHS());
3105
Eli Friedmana0544d62011-12-03 04:14:32 +00003106 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003107
3108 return std::pair<LValue,llvm::Value*>(lvalue, value);
3109}
3110
3111void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003112 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003113 const Stmt *subStmt = ARPS.getSubStmt();
3114 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3115
3116 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003117 if (DI)
3118 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003119
3120 // Keep track of the current cleanup stack depth.
3121 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003122 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003123 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3124 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3125 } else {
3126 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3127 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3128 }
3129
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003130 for (const auto *I : S.body())
3131 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003132
Eric Christopher7cdf9482011-10-13 21:45:18 +00003133 if (DI)
3134 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003135}
John McCall1bd25562011-06-24 23:21:27 +00003136
3137/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3138/// make sure it survives garbage collection until this point.
3139void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3140 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003141 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003142 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00003143 llvm::Value *extender
3144 = llvm::InlineAsm::get(extenderType,
3145 /* assembly */ "",
3146 /* constraints */ "r",
3147 /* side effects */ true);
3148
3149 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003150 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003151}
3152
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003153/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003154/// non-trivial copy assignment function, produce following helper function.
3155/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3156///
3157llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003158CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3159 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003160 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003161 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003162 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003163 QualType Ty = PID->getPropertyIvarDecl()->getType();
3164 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003165 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003166 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003167 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003168 return nullptr;
3169 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003170 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003171 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003172 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3173 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3174 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003175
3176 ASTContext &C = getContext();
3177 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003178 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003179 FunctionDecl *FD = FunctionDecl::Create(C,
3180 C.getTranslationUnitDecl(),
3181 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003182 SourceLocation(), II, C.VoidTy,
3183 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003184 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00003185 false);
Craig Topper8a13c412014-05-21 05:09:00 +00003186
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003187 QualType DestTy = C.getPointerType(Ty);
3188 QualType SrcTy = Ty;
3189 SrcTy.addConst();
3190 SrcTy = C.getPointerType(SrcTy);
3191
3192 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00003193 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003194 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00003195 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003196 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003197
John McCallc56a8b32016-03-11 04:30:31 +00003198 const CGFunctionInfo &FI =
3199 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003200
John McCalla729c622012-02-17 03:33:10 +00003201 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003202
3203 llvm::Function *Fn =
3204 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003205 "__assign_helper_atomic_property_",
3206 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003207
3208 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3209
Adrian Prantl22e66b42014-04-11 01:13:04 +00003210 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003211
John McCall113bee02012-03-10 09:33:50 +00003212 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3213 VK_RValue, SourceLocation());
3214 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
3215 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003216
John McCall113bee02012-03-10 09:33:50 +00003217 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
3218 VK_RValue, SourceLocation());
3219 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3220 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003221
John McCall113bee02012-03-10 09:33:50 +00003222 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003223 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00003224 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003225 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00003226 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00003227
3228 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003229
3230 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003231 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003232 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003233 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003234}
3235
3236llvm::Constant *
3237CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3238 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003239 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003240 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003241 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003242 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3243 QualType Ty = PD->getType();
3244 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003245 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003246 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003247 return nullptr;
3248 llvm::Constant *HelperFn = nullptr;
3249
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003250 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003251 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003252 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3253 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3254 return HelperFn;
3255
3256
3257 ASTContext &C = getContext();
3258 IdentifierInfo *II
3259 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3260 FunctionDecl *FD = FunctionDecl::Create(C,
3261 C.getTranslationUnitDecl(),
3262 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00003263 SourceLocation(), II, C.VoidTy,
3264 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003265 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00003266 false);
Craig Topper8a13c412014-05-21 05:09:00 +00003267
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003268 QualType DestTy = C.getPointerType(Ty);
3269 QualType SrcTy = Ty;
3270 SrcTy.addConst();
3271 SrcTy = C.getPointerType(SrcTy);
3272
3273 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00003274 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003275 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00003276 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003277 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003278
John McCallc56a8b32016-03-11 04:30:31 +00003279 const CGFunctionInfo &FI =
3280 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003281
John McCalla729c622012-02-17 03:33:10 +00003282 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003283
3284 llvm::Function *Fn =
3285 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3286 "__copy_helper_atomic_property_", &CGM.getModule());
3287
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003288 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3289
Adrian Prantl22e66b42014-04-11 01:13:04 +00003290 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003291
John McCall113bee02012-03-10 09:33:50 +00003292 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003293 VK_RValue, SourceLocation());
3294
John McCall113bee02012-03-10 09:33:50 +00003295 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3296 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003297
3298 CXXConstructExpr *CXXConstExpr =
3299 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3300
3301 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003302 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003303 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3304 CXXConstExpr->arg_end());
3305
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003306 CXXConstructExpr *TheCXXConstructExpr =
3307 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3308 CXXConstExpr->getConstructor(),
3309 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003310 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003311 CXXConstExpr->hadMultipleCandidates(),
3312 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003313 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003314 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003315 CXXConstExpr->getConstructionKind(),
3316 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003317
John McCall113bee02012-03-10 09:33:50 +00003318 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3319 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003320
John McCall113bee02012-03-10 09:33:50 +00003321 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003322 CharUnits Alignment
3323 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003324 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003325 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3326 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003327 AggValueSlot::IsDestructed,
3328 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003329 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003330
3331 FinishFunction();
3332 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3333 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3334 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003335}
3336
Eli Friedmanec75fec2012-02-28 01:08:45 +00003337llvm::Value *
3338CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3339 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003340 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3341 Selector CopySelector =
3342 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003343 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3344 Selector AutoreleaseSelector =
3345 getContext().Selectors.getNullarySelector(AutoreleaseID);
3346
3347 // Emit calls to retain/autorelease.
3348 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3349 llvm::Value *Val = Block;
3350 RValue Result;
3351 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003352 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003353 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003354 Val = Result.getScalarVal();
3355 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3356 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003357 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003358 Val = Result.getScalarVal();
3359 return Val;
3360}
3361
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003362
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003363CGObjCRuntime::~CGObjCRuntime() {}