blob: 7063517efc35d2c61d8437eb10620cac2c601471 [file] [log] [blame]
Erik Pilkington9227e102017-02-21 20:31:01 +00001//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
Anders Carlsson76f4a902007-08-21 17:43:55 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson76f4a902007-08-21 17:43:55 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Objective-C code as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
Devang Pateld2d66652011-01-19 01:36:36 +000013#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000014#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000017#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000021#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000022#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000032static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
33 QualType ET,
34 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000035
36/// Given the address of a variable of pointer type, find the correct
37/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000038static llvm::Constant *getNullForVariable(Address addr) {
39 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000040 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
41}
42
Chris Lattnerb1d329d2008-06-24 17:04:18 +000043/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000044llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000045{
Fangrui Song6907ce22018-07-30 19:24:48 +000046 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000047 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000048 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000049 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000050}
51
Patrick Beard0caa3942012-04-19 00:25:12 +000052/// EmitObjCBoxedExpr - This routine generates code to call
53/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000054/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
55/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000056///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000057llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000058CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000059 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000060 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000061 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000062 const Expr *SubExpr = E->getSubExpr();
Patrick Beard0caa3942012-04-19 00:25:12 +000063 assert(BoxingMethod && "BoxingMethod is null");
64 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
65 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000066
Ted Kremeneke65b0862012-03-06 20:05:56 +000067 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000068 // Assumes that the method was introduced in the class that should be
69 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000070 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000071 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000072 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000073
Ted Kremeneke65b0862012-03-06 20:05:56 +000074 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000075 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
76 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000077
78 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000079 // via [NSValue valueWithBytes:objCType:]
80 const QualType ValueType(SubExpr->getType().getCanonicalType());
81 if (ValueType->isObjCBoxableRecordType()) {
82 // Emit CodeGen for first parameter
83 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000084 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000085 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000086 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
87 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000088
89 // Create char array to store type encoding
90 std::string Str;
91 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000092 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +000093
Alex Denisovfde64952015-06-26 05:28:36 +000094 // Cast type encoding to correct type
95 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
96 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
97 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
98
99 Args.add(RValue::get(Cast), EncodingQT);
100 } else {
101 Args.add(EmitAnyExpr(SubExpr), ArgQT);
102 }
Alp Toker314cc812014-01-25 16:55:45 +0000103
104 RValue result = Runtime.GenerateMessageSend(
105 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
106 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000107 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000108 ConvertType(E->getType()));
109}
110
111llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000112 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000113 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000114 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
116 if (!ALE)
117 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000118
119 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000120 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000122 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
123 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
124 QualType IdTy(CGM.getContext().getObjCIdType());
125 llvm::Constant *Constant =
126 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000127 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000128 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000129 cast<llvm::LoadInst>(Ptr)->setMetadata(
130 CGM.getModule().getMDKindID("invariant.load"),
131 llvm::MDNode::get(getLLVMContext(), None));
132 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000133 }
134
135 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000136 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
137 NumElements);
138 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000139 QualType ElementArrayType
140 = Context.getConstantArrayType(ElementType, APNumElements,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000141 ArrayType::Normal, /*IndexTypeQuals=*/0);
142
143 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000144 Address Objects = CreateMemTemp(ElementArrayType, "objects");
145 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000146 if (DLE)
147 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000148
John McCall770a4c12013-04-04 00:20:38 +0000149 // In ARC, we may need to do extra work to keep all the keys and
150 // values alive until after the call.
151 SmallVector<llvm::Value *, 16> NeededObjects;
152 bool TrackNeededObjects =
153 (getLangOpts().ObjCAutoRefCount &&
154 CGM.getCodeGenOpts().OptimizationLevel != 0);
155
Ted Kremeneke65b0862012-03-06 20:05:56 +0000156 // Perform the actual initialialization of the array(s).
157 for (uint64_t i = 0; i < NumElements; i++) {
158 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000159 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000160 const Expr *Rhs = ALE->getElement(i);
James Y Knight751fe282019-02-09 22:22:28 +0000161 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
162 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000163
164 llvm::Value *value = EmitScalarExpr(Rhs);
165 EmitStoreThroughLValue(RValue::get(value), LV, true);
166 if (TrackNeededObjects) {
167 NeededObjects.push_back(value);
168 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000169 } else {
John McCall770a4c12013-04-04 00:20:38 +0000170 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171 const Expr *Key = DLE->getKeyValueElement(i).Key;
James Y Knight751fe282019-02-09 22:22:28 +0000172 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
173 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000174 llvm::Value *keyValue = EmitScalarExpr(Key);
175 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000176
John McCall770a4c12013-04-04 00:20:38 +0000177 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000178 const Expr *Value = DLE->getKeyValueElement(i).Value;
James Y Knight751fe282019-02-09 22:22:28 +0000179 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
180 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000181 llvm::Value *valueValue = EmitScalarExpr(Value);
182 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
183 if (TrackNeededObjects) {
184 NeededObjects.push_back(keyValue);
185 NeededObjects.push_back(valueValue);
186 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000187 }
188 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000189
Ted Kremeneke65b0862012-03-06 20:05:56 +0000190 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000191 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000192 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
193 const ParmVarDecl *argDecl = *PI++;
194 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000195 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000196 if (DLE) {
197 argDecl = *PI++;
198 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000199 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000200 }
201 argDecl = *PI;
202 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000203 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000204 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
205 Args.add(RValue::get(Count), ArgQT);
206
207 // Generate a reference to the class pointer, which will be the receiver.
208 Selector Sel = MethodWithObjects->getSelector();
209 QualType ResultType = E->getType();
210 const ObjCObjectPointerType *InterfacePointerType
211 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000212 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000213 = InterfacePointerType->getObjectType()->getInterface();
214 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000215 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000216
217 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000218 RValue result = Runtime.GenerateMessageSend(
219 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
220 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000221
222 // The above message send needs these objects, but in ARC they are
223 // passed in a buffer that is essentially __unsafe_unretained.
224 // Therefore we must prevent the optimizer from releasing them until
225 // after the call.
226 if (TrackNeededObjects) {
227 EmitARCIntrinsicUse(NeededObjects);
228 }
229
Fangrui Song6907ce22018-07-30 19:24:48 +0000230 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000231 ConvertType(E->getType()));
232}
233
234llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000235 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000236}
237
238llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
239 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000240 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000241}
242
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000243/// Emit a selector.
244llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
245 // Untyped selector.
246 // Note that this implementation allows for non-constant strings to be passed
247 // as arguments to @selector(). Currently, the only thing preventing this
248 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000249 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000250}
251
Daniel Dunbar66912a12008-08-20 00:28:19 +0000252llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
253 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000254 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000255}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000256
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000257/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000258/// to type erasure at various points, e.g., related result types or the use
259/// of parameterized classes.
260static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
261 RValue Result) {
262 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000263 return Result;
John McCall31168b02011-06-15 23:02:42 +0000264
Douglas Gregore83b9562015-07-07 03:57:53 +0000265 // If the converted types are the same, we're done.
266 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
267 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000268 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000269
270 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000271 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000272 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000273}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000274
John McCallcf166702011-07-22 08:53:00 +0000275/// Decide whether to extend the lifetime of the receiver of a
276/// returns-inner-pointer message.
277static bool
278shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
279 switch (message->getReceiverKind()) {
280
281 // For a normal instance message, we should extend unless the
282 // receiver is loaded from a variable with precise lifetime.
283 case ObjCMessageExpr::Instance: {
284 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000285
286 // Look through OVEs.
287 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
288 if (opaque->getSourceExpr())
289 receiver = opaque->getSourceExpr()->IgnoreParens();
290 }
291
John McCallcf166702011-07-22 08:53:00 +0000292 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
293 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
294 receiver = ice->getSubExpr()->IgnoreParens();
295
John McCall6380a282015-09-09 23:37:17 +0000296 // Look through OVEs.
297 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
298 if (opaque->getSourceExpr())
299 receiver = opaque->getSourceExpr()->IgnoreParens();
300 }
301
John McCallcf166702011-07-22 08:53:00 +0000302 // Only __strong variables.
303 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
304 return true;
305
306 // All ivars and fields have precise lifetime.
307 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
308 return false;
309
310 // Otherwise, check for variables.
311 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
312 if (!declRef) return true;
313 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
314 if (!var) return true;
315
316 // All variables have precise lifetime except local variables with
317 // automatic storage duration that aren't specially marked.
318 return (var->hasLocalStorage() &&
319 !var->hasAttr<ObjCPreciseLifetimeAttr>());
320 }
321
322 case ObjCMessageExpr::Class:
323 case ObjCMessageExpr::SuperClass:
324 // It's never necessary for class objects.
325 return false;
326
327 case ObjCMessageExpr::SuperInstance:
328 // We generally assume that 'self' lives throughout a method call.
329 return false;
330 }
331
332 llvm_unreachable("invalid receiver kind");
333}
334
John McCall460ce582015-10-22 18:38:17 +0000335/// Given an expression of ObjC pointer type, check whether it was
336/// immediately loaded from an ARC __weak l-value.
337static const Expr *findWeakLValue(const Expr *E) {
338 assert(E->getType()->isObjCRetainableType());
339 E = E->IgnoreParens();
340 if (auto CE = dyn_cast<CastExpr>(E)) {
341 if (CE->getCastKind() == CK_LValueToRValue) {
342 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
343 return CE->getSubExpr();
344 }
345 }
346
347 return nullptr;
348}
349
Pete Coopere3886802018-12-08 05:13:50 +0000350/// The ObjC runtime may provide entrypoints that are likely to be faster
351/// than an ordinary message send of the appropriate selector.
352///
353/// The entrypoints are guaranteed to be equivalent to just sending the
354/// corresponding message. If the entrypoint is implemented naively as just a
355/// message send, using it is a trade-off: it sacrifices a few cycles of
356/// overhead to save a small amount of code. However, it's possible for
357/// runtimes to detect and special-case classes that use "standard"
358/// behavior; if that's dynamically a large proportion of all objects, using
359/// the entrypoint will also be faster than using a message send.
360///
361/// If the runtime does support a required entrypoint, then this method will
362/// generate a call and return the resulting value. Otherwise it will return
363/// None and the caller can generate a msgSend instead.
364static Optional<llvm::Value *>
365tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
366 llvm::Value *Receiver,
367 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000368 const ObjCMethodDecl *method,
369 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000370 auto &CGM = CGF.CGM;
371 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
372 return None;
373
374 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
375 switch (Sel.getMethodFamily()) {
376 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000377 if (isClassMessage &&
378 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000379 ResultType->isObjCObjectPointerType()) {
380 // [Foo alloc] -> objc_alloc(Foo)
381 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
382 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
383 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
384 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
385 Args.size() == 1 && Args.front().getType()->isPointerType() &&
386 Sel.getNameForSlot(0) == "allocWithZone") {
387 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
388 if (isa<llvm::ConstantPointerNull>(arg))
389 return CGF.EmitObjCAllocWithZone(Receiver,
390 CGF.ConvertType(ResultType));
391 return None;
392 }
393 }
394 break;
395
Pete Coopere5b64ea2018-12-21 21:00:32 +0000396 case OMF_autorelease:
397 if (ResultType->isObjCObjectPointerType() &&
398 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
399 Runtime.shouldUseARCFunctionsForRetainRelease())
400 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
401 break;
402
403 case OMF_retain:
404 if (ResultType->isObjCObjectPointerType() &&
405 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
406 Runtime.shouldUseARCFunctionsForRetainRelease())
407 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
408 break;
409
410 case OMF_release:
411 if (ResultType->isVoidType() &&
412 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
413 Runtime.shouldUseARCFunctionsForRetainRelease()) {
414 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
415 return nullptr;
416 }
417 break;
418
Pete Coopere3886802018-12-08 05:13:50 +0000419 default:
420 break;
421 }
422 return None;
423}
424
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000425/// Instead of '[[MyClass alloc] init]', try to generate
426/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
427/// caller side, as well as the optimized objc_alloc.
428static Optional<llvm::Value *>
429tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
430 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
431 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
432 return None;
433
434 // Match the exact pattern '[[MyClass alloc] init]'.
435 Selector Sel = OME->getSelector();
Erik Pilkington55e703a2019-02-25 21:35:14 +0000436 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
437 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
438 Sel.getNameForSlot(0) != "init")
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000439 return None;
440
441 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]'.
442 auto *SubOME =
443 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParens());
444 if (!SubOME)
445 return None;
446 Selector SubSel = SubOME->getSelector();
447 if (SubOME->getReceiverKind() != ObjCMessageExpr::Class ||
448 !SubOME->getType()->isObjCObjectPointerType() ||
449 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
450 return None;
451
452 QualType ReceiverType = SubOME->getClassReceiver();
453 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
454 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
455 assert(ID && "null interface should be impossible here");
456 llvm::Value *Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
457 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
458}
459
John McCall78a15112010-05-22 01:48:05 +0000460RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
461 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000462 // Only the lookup mechanism and first two arguments of the method
463 // implementation vary between runtimes. We can get the receiver and
464 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000465
John McCall31168b02011-06-15 23:02:42 +0000466 bool isDelegateInit = E->isDelegateInitCall();
467
John McCallcf166702011-07-22 08:53:00 +0000468 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000469
John McCall460ce582015-10-22 18:38:17 +0000470 // If the method is -retain, and the receiver's being loaded from
471 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
472 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
473 method->getMethodFamily() == OMF_retain) {
474 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
475 LValue lvalue = EmitLValue(lvalueExpr);
476 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
477 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
478 }
479 }
480
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000481 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
482 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
483
John McCall31168b02011-06-15 23:02:42 +0000484 // We don't retain the receiver in delegate init calls, and this is
485 // safe because the receiver value is always loaded from 'self',
486 // which we zero out. We don't want to Block_copy block receivers,
487 // though.
488 bool retainSelf =
489 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000490 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000491 method &&
492 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000493
Daniel Dunbar8d480592008-08-11 18:12:00 +0000494 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000495 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000496 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000497 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000498 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000499 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000500 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000501 switch (E->getReceiverKind()) {
502 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000503 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000504 if (retainSelf) {
505 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
506 E->getInstanceReceiver());
507 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000508 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000509 } else
510 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000511 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000512
Douglas Gregor9a129192010-04-21 00:45:42 +0000513 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000514 ReceiverType = E->getClassReceiver();
515 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000516 assert(ObjTy && "Invalid Objective-C class message send");
517 OID = ObjTy->getInterface();
518 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000519 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000520 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000521 break;
522 }
523
524 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000525 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000526 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000527 isSuperMessage = true;
528 break;
529
530 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000531 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000532 Receiver = LoadObjCSelf();
533 isSuperMessage = true;
534 isClassMessage = true;
535 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000536 }
537
John McCallcf166702011-07-22 08:53:00 +0000538 if (retainSelf)
539 Receiver = EmitARCRetainNonBlock(Receiver);
540
541 // In ARC, we sometimes want to "extend the lifetime"
542 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
543 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000544 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000545 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
546 shouldExtendReceiverForInnerPointerMessage(E))
547 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
548
Alp Toker314cc812014-01-25 16:55:45 +0000549 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000550
Daniel Dunbarc722b852008-08-30 03:02:31 +0000551 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000552 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000553
John McCall31168b02011-06-15 23:02:42 +0000554 // For delegate init calls in ARC, do an unsafe store of null into
555 // self. This represents the call taking direct ownership of that
556 // value. We have to do this after emitting the other call
557 // arguments because they might also reference self, but we don't
558 // have to worry about any of them modifying self because that would
559 // be an undefined read and write of an object in unordered
560 // expressions.
561 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000562 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000563 "delegate init calls should only be marked in ARC");
564
565 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000566 Address selfAddr =
567 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000568 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
569 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000570
Douglas Gregor33823722011-06-11 01:09:30 +0000571 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000572 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000573 // super is only valid in an Objective-C method
574 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000575 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000576 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
577 E->getSelector(),
578 OMD->getClassInterface(),
579 isCategoryImpl,
580 Receiver,
581 isClassMessage,
582 Args,
John McCallcf166702011-07-22 08:53:00 +0000583 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000584 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000585 // Call runtime methods directly if we can.
586 if (Optional<llvm::Value *> SpecializedResult =
587 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000588 E->getSelector(), method,
589 isClassMessage)) {
Pete Coopere3886802018-12-08 05:13:50 +0000590 result = RValue::get(SpecializedResult.getValue());
591 } else {
592 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
593 E->getSelector(), Receiver, Args,
594 OID, method);
595 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000596 }
John McCall31168b02011-06-15 23:02:42 +0000597
598 // For delegate init calls in ARC, implicitly store the result of
599 // the call back into self. This takes ownership of the value.
600 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000601 Address selfAddr =
602 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000603 llvm::Value *newSelf = result.getScalarVal();
604
605 // The delegate return type isn't necessarily a matching type; in
606 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000607 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000608 newSelf = Builder.CreateBitCast(newSelf, selfTy);
609
610 Builder.CreateStore(newSelf, selfAddr);
611 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000612
Douglas Gregore83b9562015-07-07 03:57:53 +0000613 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000614}
615
John McCall31168b02011-06-15 23:02:42 +0000616namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000617struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000618 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000619 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000620
621 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000622 const ObjCInterfaceDecl *iface = impl->getClassInterface();
623 if (!iface->getSuperClass()) return;
624
John McCalldffafde2011-07-13 18:26:47 +0000625 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
626
John McCall31168b02011-06-15 23:02:42 +0000627 // Call [super dealloc] if we have a superclass.
628 llvm::Value *self = CGF.LoadObjCSelf();
629
630 CallArgList args;
631 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
632 CGF.getContext().VoidTy,
633 method->getSelector(),
634 iface,
John McCalldffafde2011-07-13 18:26:47 +0000635 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000636 self,
637 /*is class msg*/ false,
638 args,
639 method);
640 }
641};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000642}
John McCall31168b02011-06-15 23:02:42 +0000643
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000644/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
645/// the LLVM function and sets the other context used by
646/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000647void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000648 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000649 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000650 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000651 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000652 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000653 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000654
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000655 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000656
John McCalla729c622012-02-17 03:33:10 +0000657 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000658 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000659
John McCalla738c252011-03-09 04:27:21 +0000660 args.push_back(OMD->getSelfDecl());
661 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000662
Benjamin Kramerf9890422015-02-17 16:48:30 +0000663 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000664
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000665 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000666 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000667
Adrian Prantl42d71b92014-04-10 23:21:53 +0000668 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
669 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000670
671 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000672 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000673 OMD->isInstanceMethod() &&
674 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000675 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000676 OMD->getSelector().getIdentifierInfoForSlot(0);
677 if (ident->isStr("dealloc"))
678 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
679 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000680}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000681
John McCall31168b02011-06-15 23:02:42 +0000682static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
683 LValue lvalue, QualType type);
684
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000685/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000686/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000687void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000688 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000689 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000690 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000691 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000692 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000693 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000694}
695
John McCallb923ece2011-09-12 23:06:44 +0000696/// emitStructGetterCall - Call the runtime function to load a property
697/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000698static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000699 bool isAtomic, bool hasStrong) {
700 ASTContext &Context = CGF.getContext();
701
John McCall7f416cc2015-09-08 08:05:57 +0000702 Address src =
703 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
704 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000705
Fangrui Song6907ce22018-07-30 19:24:48 +0000706 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000707 // sizeof (Type of Ivar), isAtomic, false);
708 CallArgList args;
709
John McCall7f416cc2015-09-08 08:05:57 +0000710 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
711 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000712
713 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000714 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000715
716 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
717 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
718 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
719 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
720
James Y Knight9871db02019-02-05 16:42:33 +0000721 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000722 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000723 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000724 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000725}
726
John McCallf4528ae2011-09-13 03:34:09 +0000727/// Determine whether the given architecture supports unaligned atomic
728/// accesses. They don't have to be fast, just faster than a function
729/// call and a mutex.
730static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000731 // FIXME: Allow unaligned atomic load/store on x86. (It is not
732 // currently supported by the backend.)
733 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000734}
735
736/// Return the maximum size that permits atomic accesses for the given
737/// architecture.
738static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
739 llvm::Triple::ArchType arch) {
740 // ARM has 8-byte atomic accesses, but it's not clear whether we
741 // want to rely on them here.
742
743 // In the default case, just assume that any size up to a pointer is
744 // fine given adequate alignment.
745 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
746}
747
748namespace {
749 class PropertyImplStrategy {
750 public:
751 enum StrategyKind {
752 /// The 'native' strategy is to use the architecture's provided
753 /// reads and writes.
754 Native,
755
756 /// Use objc_setProperty and objc_getProperty.
757 GetSetProperty,
758
759 /// Use objc_setProperty for the setter, but use expression
760 /// evaluation for the getter.
761 SetPropertyAndExpressionGet,
762
763 /// Use objc_copyStruct.
764 CopyStruct,
765
766 /// The 'expression' strategy is to emit normal assignment or
767 /// lvalue-to-rvalue expressions.
768 Expression
769 };
770
771 StrategyKind getKind() const { return StrategyKind(Kind); }
772
773 bool hasStrongMember() const { return HasStrong; }
774 bool isAtomic() const { return IsAtomic; }
775 bool isCopy() const { return IsCopy; }
776
777 CharUnits getIvarSize() const { return IvarSize; }
778 CharUnits getIvarAlignment() const { return IvarAlignment; }
779
780 PropertyImplStrategy(CodeGenModule &CGM,
781 const ObjCPropertyImplDecl *propImpl);
782
783 private:
784 unsigned Kind : 8;
785 unsigned IsAtomic : 1;
786 unsigned IsCopy : 1;
787 unsigned HasStrong : 1;
788
789 CharUnits IvarSize;
790 CharUnits IvarAlignment;
791 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000792}
John McCallf4528ae2011-09-13 03:34:09 +0000793
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000794/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000795PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
796 const ObjCPropertyImplDecl *propImpl) {
797 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000798 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000799
John McCall43192862011-09-13 18:31:23 +0000800 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
801 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000802 HasStrong = false; // doesn't matter here.
803
804 // Evaluate the ivar's size and alignment.
805 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
806 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000807 std::tie(IvarSize, IvarAlignment) =
808 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000809
810 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000811 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000812 if (IsCopy) {
813 Kind = GetSetProperty;
814 return;
815 }
816
John McCall43192862011-09-13 18:31:23 +0000817 // Handle retain.
818 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000819 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000820 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000821 // fallthrough
822
823 // In ARC, if the property is non-atomic, use expression emission,
824 // which translates to objc_storeStrong. This isn't required, but
825 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000826 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000827 // Using standard expression emission for the setter is only
828 // acceptable if the ivar is __strong, which won't be true if
829 // the property is annotated with __attribute__((NSObject)).
830 // TODO: falling all the way back to objc_setProperty here is
831 // just laziness, though; we could still use objc_storeStrong
832 // if we hacked it right.
833 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
834 Kind = Expression;
835 else
836 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000837 return;
838
839 // Otherwise, we need to at least use setProperty. However, if
840 // the property isn't atomic, we can use normal expression
841 // emission for the getter.
842 } else if (!IsAtomic) {
843 Kind = SetPropertyAndExpressionGet;
844 return;
845
846 // Otherwise, we have to use both setProperty and getProperty.
847 } else {
848 Kind = GetSetProperty;
849 return;
850 }
851 }
852
853 // If we're not atomic, just use expression accesses.
854 if (!IsAtomic) {
855 Kind = Expression;
856 return;
857 }
858
John McCall0e5c0862011-09-13 05:36:29 +0000859 // Properties on bitfield ivars need to be emitted using expression
860 // accesses even if they're nominally atomic.
861 if (ivar->isBitField()) {
862 Kind = Expression;
863 return;
864 }
865
John McCallf4528ae2011-09-13 03:34:09 +0000866 // GC-qualified or ARC-qualified ivars need to be emitted as
867 // expressions. This actually works out to being atomic anyway,
868 // except for ARC __strong, but that should trigger the above code.
869 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000870 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000871 CGM.getContext().getObjCGCAttrKind(ivarType))) {
872 Kind = Expression;
873 return;
874 }
875
876 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000877 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000878 if (const RecordType *recordType = ivarType->getAs<RecordType>())
879 HasStrong = recordType->getDecl()->hasObjectMember();
880
881 // We can never access structs with object members with a native
882 // access, because we need to use write barriers. This is what
883 // objc_copyStruct is for.
884 if (HasStrong) {
885 Kind = CopyStruct;
886 return;
887 }
888
889 // Otherwise, this is target-dependent and based on the size and
890 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000891
892 // If the size of the ivar is not a power of two, give up. We don't
893 // want to get into the business of doing compare-and-swaps.
894 if (!IvarSize.isPowerOfTwo()) {
895 Kind = CopyStruct;
896 return;
897 }
898
John McCallf4528ae2011-09-13 03:34:09 +0000899 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000900 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000901
902 // Most architectures require memory to fit within a single cache
903 // line, so the alignment has to be at least the size of the access.
904 // Otherwise we have to grab a lock.
905 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
906 Kind = CopyStruct;
907 return;
908 }
909
910 // If the ivar's size exceeds the architecture's maximum atomic
911 // access size, we have to use CopyStruct.
912 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
913 Kind = CopyStruct;
914 return;
915 }
916
917 // Otherwise, we can use native loads and stores.
918 Kind = Native;
919}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000920
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000921/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000922///
923/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000924/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000925void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
926 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000927 llvm::Constant *AtomicHelperFn =
928 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000929 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
930 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
931 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000932 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000933
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000934 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000935
936 FinishFunction();
937}
938
John McCallbdd81852011-09-13 06:00:03 +0000939static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
940 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000941 if (!getter) return true;
942
943 // Sema only makes only of these when the ivar has a C++ class type,
944 // so the form is pretty constrained.
945
John McCallbdd81852011-09-13 06:00:03 +0000946 // If the property has a reference type, we might just be binding a
947 // reference, in which case the result will be a gl-value. We should
948 // treat this as a non-trivial operation.
949 if (getter->isGLValue())
950 return false;
951
John McCallf4528ae2011-09-13 03:34:09 +0000952 // If we selected a trivial copy-constructor, we're okay.
953 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
954 return (construct->getConstructor()->isTrivial());
955
956 // The constructor might require cleanups (in which case it's never
957 // trivial).
958 assert(isa<ExprWithCleanups>(getter));
959 return false;
960}
961
Fangrui Song6907ce22018-07-30 19:24:48 +0000962/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000963/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000964static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000965 llvm::Value *returnAddr,
966 ObjCIvarDecl *ivar,
967 llvm::Constant *AtomicHelperFn) {
968 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
969 // AtomicHelperFn);
970 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000971
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000972 // The 1st argument is the return Slot.
973 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000974
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000975 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +0000976 llvm::Value *ivarAddr =
977 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +0000978 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000979 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
980 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000981
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000982 // Third argument is the helper function.
983 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000984
James Y Knight9871db02019-02-05 16:42:33 +0000985 llvm::FunctionCallee copyCppAtomicObjectFn =
986 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000987 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000988 CGF.EmitCall(
989 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000990 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000991}
992
John McCallf4528ae2011-09-13 03:34:09 +0000993void
994CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000995 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000996 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000997 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000998 // If there's a non-trivial 'get' expression, we just have to emit that.
999 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001000 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001001 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1002 propImpl->getGetterCXXConstructor(),
1003 /* NRVOCandidate=*/nullptr);
1004 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001005 }
1006 else {
1007 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001008 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001009 ivar, AtomicHelperFn);
1010 }
John McCallf4528ae2011-09-13 03:34:09 +00001011 return;
1012 }
1013
1014 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1015 QualType propType = prop->getType();
1016 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
1017
Fangrui Song6907ce22018-07-30 19:24:48 +00001018 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001019
1020 // Pick an implementation strategy.
1021 PropertyImplStrategy strategy(CGM, propImpl);
1022 switch (strategy.getKind()) {
1023 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001024 // We don't need to do anything for a zero-size struct.
1025 if (strategy.getIvarSize().isZero())
1026 return;
1027
John McCallf4528ae2011-09-13 03:34:09 +00001028 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1029
1030 // Currently, all atomic accesses have to be through integer
1031 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001032 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1033 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001034 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1035
1036 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +00001037 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +00001038 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1039 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001040 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001041
1042 // Store that value into the return address. Doing this with a
1043 // bitcast is likely to produce some pretty ugly IR, but it's not
1044 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001045 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1046 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1047 llvm::Value *ivarVal = load;
1048 if (ivarSize > retTySize) {
1049 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1050 ivarVal = Builder.CreateTrunc(load, newTy);
1051 bitcastType = newTy->getPointerTo();
1052 }
1053 Builder.CreateStore(ivarVal,
1054 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001055
1056 // Make sure we don't do an autorelease.
1057 AutoreleaseResult = false;
1058 return;
1059 }
1060
1061 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001062 llvm::FunctionCallee getPropertyFn =
1063 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001064 if (!getPropertyFn) {
1065 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001066 return;
1067 }
John McCallb92ab1a2016-10-26 23:46:34 +00001068 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001069
1070 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1071 // FIXME: Can't this be simpler? This might even be worse than the
1072 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001073 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001074 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001075 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1076 llvm::Value *ivarOffset =
1077 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1078
1079 CallArgList args;
1080 args.add(RValue::get(self), getContext().getObjCIdType());
1081 args.add(RValue::get(cmd), getContext().getObjCSelType());
1082 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001083 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1084 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001085
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001086 // FIXME: We shouldn't need to get the function info here, the
1087 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001088 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001089 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1090 getContext().getObjCIdType(), args),
1091 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001092 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1093 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001094
Daniel Dunbara08dff12008-09-24 04:04:31 +00001095 // We need to fix the type here. Ivars with copy & retain are
1096 // always objects so we don't need to worry about complex or
1097 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001098 RV = RValue::get(Builder.CreateBitCast(
1099 RV.getScalarVal(),
1100 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001101
1102 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001103
1104 // objc_getProperty does an autorelease, so we should suppress ours.
1105 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001106
John McCallf4528ae2011-09-13 03:34:09 +00001107 return;
1108 }
1109
1110 case PropertyImplStrategy::CopyStruct:
1111 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1112 strategy.hasStrongMember());
1113 return;
1114
1115 case PropertyImplStrategy::Expression:
1116 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1117 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1118
1119 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001120 switch (getEvaluationKind(ivarType)) {
1121 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001122 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001123 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001124 /*init*/ true);
1125 return;
1126 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001127 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001128 // The return value slot is guaranteed to not be aliased, but
1129 // that's not necessarily the same as "on the stack", so
1130 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001131 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smithe78fac52018-04-05 20:52:58 +00001132 /* Src= */ LV, ivarType, overlapForReturnValue());
1133 return;
1134 }
John McCall47fb9502013-03-07 21:37:08 +00001135 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001136 llvm::Value *value;
1137 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001138 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001139 } else {
1140 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1141 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001142 if (getLangOpts().ObjCAutoRefCount) {
1143 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1144 } else {
1145 value = EmitARCLoadWeak(LV.getAddress());
1146 }
John McCall24fada12011-07-22 05:23:13 +00001147
1148 // Otherwise we want to do a simple load, suppressing the
1149 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001150 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001151 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001152 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001153 }
John McCall31168b02011-06-15 23:02:42 +00001154
Alp Toker314cc812014-01-25 16:55:45 +00001155 value = Builder.CreateBitCast(
1156 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001157 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001158
John McCall24fada12011-07-22 05:23:13 +00001159 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001160 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001161 }
John McCall47fb9502013-03-07 21:37:08 +00001162 }
1163 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001164 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001165
John McCallf4528ae2011-09-13 03:34:09 +00001166 }
1167 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001168}
1169
John McCallb923ece2011-09-12 23:06:44 +00001170/// emitStructSetterCall - Call the runtime function to store the value
1171/// from the first formal parameter into the given ivar.
1172static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1173 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001174 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001175 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001176 CallArgList args;
1177
1178 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001179 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1180 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001181 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001182 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1183 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001184
1185 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001186 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001187 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1188 argVar->getType().getNonReferenceType(), VK_LValue,
1189 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001190 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001191 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1192 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001193
1194 // The third argument is the sizeof the type.
1195 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001196 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1197 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001198
John McCallb923ece2011-09-12 23:06:44 +00001199 // The fourth argument is the 'isAtomic' flag.
1200 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001201
John McCallb923ece2011-09-12 23:06:44 +00001202 // The fifth argument is the 'hasStrong' flag.
1203 // FIXME: should this really always be false?
1204 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1205
James Y Knight9871db02019-02-05 16:42:33 +00001206 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001207 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001208 CGF.EmitCall(
1209 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001210 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001211}
1212
Fangrui Song6907ce22018-07-30 19:24:48 +00001213/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1214/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001215/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001216static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001217 ObjCMethodDecl *OMD,
1218 ObjCIvarDecl *ivar,
1219 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001220 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001221 // AtomicHelperFn);
1222 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001223
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001224 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001225 llvm::Value *ivarAddr =
1226 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001227 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001228 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1229 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001230
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001231 // The second argument is the address of the parameter variable.
1232 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001233 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1234 argVar->getType().getNonReferenceType(), VK_LValue,
1235 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001236 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001237 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1238 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001239
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001240 // Third argument is the helper function.
1241 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001242
James Y Knight9871db02019-02-05 16:42:33 +00001243 llvm::FunctionCallee fn =
1244 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001245 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001246 CGF.EmitCall(
1247 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001248 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001249}
1250
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001251
John McCallf4528ae2011-09-13 03:34:09 +00001252static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1253 Expr *setter = PID->getSetterCXXAssignment();
1254 if (!setter) return true;
1255
1256 // Sema only makes only of these when the ivar has a C++ class type,
1257 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001258
1259 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001260 // This also implies that there's nothing non-trivial going on with
1261 // the arguments, because operator= can only be trivial if it's a
1262 // synthesized assignment operator and therefore both parameters are
1263 // references.
1264 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001265 if (const FunctionDecl *callee
1266 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1267 if (callee->isTrivial())
1268 return true;
1269 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001270 }
John McCall7f16c422011-09-10 09:17:20 +00001271
John McCallf4528ae2011-09-13 03:34:09 +00001272 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001273 return false;
1274}
1275
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001276static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001277 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001278 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001279 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001280}
1281
John McCall7f16c422011-09-10 09:17:20 +00001282void
1283CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001284 const ObjCPropertyImplDecl *propImpl,
1285 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001286 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001287 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001288 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001289
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001290 // Just use the setter expression if Sema gave us one and it's
1291 // non-trivial.
1292 if (!hasTrivialSetExpr(propImpl)) {
1293 if (!AtomicHelperFn)
1294 // If non-atomic, assignment is called directly.
1295 EmitStmt(propImpl->getSetterCXXAssignment());
1296 else
1297 // If atomic, assignment is called via a locking api.
1298 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1299 AtomicHelperFn);
1300 return;
1301 }
John McCall7f16c422011-09-10 09:17:20 +00001302
John McCallf4528ae2011-09-13 03:34:09 +00001303 PropertyImplStrategy strategy(CGM, propImpl);
1304 switch (strategy.getKind()) {
1305 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001306 // We don't need to do anything for a zero-size struct.
1307 if (strategy.getIvarSize().isZero())
1308 return;
1309
John McCall7f416cc2015-09-08 08:05:57 +00001310 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001311
John McCallf4528ae2011-09-13 03:34:09 +00001312 LValue ivarLValue =
1313 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001314 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001315
John McCallf4528ae2011-09-13 03:34:09 +00001316 // Currently, all atomic accesses have to be through integer
1317 // types, so there's no point in trying to pick a prettier type.
1318 llvm::Type *bitcastType =
1319 llvm::Type::getIntNTy(getLLVMContext(),
1320 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001321
1322 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001323 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1324 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001325
1326 // This bitcast load is likely to cause some nasty IR.
1327 llvm::Value *load = Builder.CreateLoad(argAddr);
1328
1329 // Perform an atomic store. There are no memory ordering requirements.
1330 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001331 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001332 return;
1333 }
1334
1335 case PropertyImplStrategy::GetSetProperty:
1336 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001337
James Y Knight9871db02019-02-05 16:42:33 +00001338 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1339 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001340 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001341 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001342 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001343 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1344 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001345 if (!setOptimizedPropertyFn) {
1346 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1347 return;
1348 }
John McCall7f16c422011-09-10 09:17:20 +00001349 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001350 else {
1351 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1352 if (!setPropertyFn) {
1353 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1354 return;
1355 }
1356 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001357
John McCall7f16c422011-09-10 09:17:20 +00001358 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1359 // <is-atomic>, <is-copy>).
1360 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001361 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001362 llvm::Value *self =
1363 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1364 llvm::Value *ivarOffset =
1365 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001366 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1367 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1368 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001369
1370 CallArgList args;
1371 args.add(RValue::get(self), getContext().getObjCIdType());
1372 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001373 if (setOptimizedPropertyFn) {
1374 args.add(RValue::get(arg), getContext().getObjCIdType());
1375 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001376 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001377 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001378 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001379 } else {
1380 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1381 args.add(RValue::get(arg), getContext().getObjCIdType());
1382 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1383 getContext().BoolTy);
1384 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1385 getContext().BoolTy);
1386 // FIXME: We shouldn't need to get the function info here, the runtime
1387 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001388 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001389 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001390 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001391 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001392
John McCall7f16c422011-09-10 09:17:20 +00001393 return;
1394 }
1395
John McCallf4528ae2011-09-13 03:34:09 +00001396 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001397 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001398 return;
John McCallf4528ae2011-09-13 03:34:09 +00001399
1400 case PropertyImplStrategy::Expression:
1401 break;
John McCall7f16c422011-09-10 09:17:20 +00001402 }
1403
1404 // Otherwise, fake up some ASTs and emit a normal assignment.
1405 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001406 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001407 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001408 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1409 selfDecl->getType(), CK_LValueToRValue, &self,
1410 VK_RValue);
1411 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001412 SourceLocation(), SourceLocation(),
1413 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001414
1415 ParmVarDecl *argDecl = *setterMethod->param_begin();
1416 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001417 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1418 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001419 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1420 argType.getUnqualifiedType(), CK_LValueToRValue,
1421 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001422
John McCall7f16c422011-09-10 09:17:20 +00001423 // The property type can differ from the ivar type in some situations with
1424 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1425 // The following absurdity is just to ensure well-formed IR.
1426 CastKind argCK = CK_NoOp;
1427 if (ivarRef.getType()->isObjCObjectPointerType()) {
1428 if (argLoad.getType()->isObjCObjectPointerType())
1429 argCK = CK_BitCast;
1430 else if (argLoad.getType()->isBlockPointerType())
1431 argCK = CK_BlockPointerToObjCPointerCast;
1432 else
1433 argCK = CK_CPointerToObjCPointerCast;
1434 } else if (ivarRef.getType()->isBlockPointerType()) {
1435 if (argLoad.getType()->isBlockPointerType())
1436 argCK = CK_BitCast;
1437 else
1438 argCK = CK_AnyPointerToBlockPointerCast;
1439 } else if (ivarRef.getType()->isPointerType()) {
1440 argCK = CK_BitCast;
1441 }
1442 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1443 ivarRef.getType(), argCK, &argLoad,
1444 VK_RValue);
1445 Expr *finalArg = &argLoad;
1446 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1447 argLoad.getType()))
1448 finalArg = &argCast;
1449
1450
1451 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1452 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001453 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001454 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001455}
1456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001457/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001458///
1459/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001460/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001461void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1462 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001463 llvm::Constant *AtomicHelperFn =
1464 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001465 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1466 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1467 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001468 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001469
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001470 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001471
1472 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001473}
1474
John McCall6a4fa522011-03-22 07:05:39 +00001475namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001476 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001477 private:
1478 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001479 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001480 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001481 bool useEHCleanupForArray;
1482 public:
1483 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1484 CodeGenFunction::Destroyer *destroyer,
1485 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001486 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001487 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001488
Craig Topper4f12f102014-03-12 06:41:41 +00001489 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001490 LValue lvalue
1491 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1492 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001493 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001494 }
1495 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001496}
John McCall6a4fa522011-03-22 07:05:39 +00001497
John McCall4bd0fb12011-07-12 16:41:08 +00001498/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1499static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001500 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001501 QualType type) {
1502 llvm::Value *null = getNullForVariable(addr);
1503 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1504}
John McCall31168b02011-06-15 23:02:42 +00001505
John McCall6a4fa522011-03-22 07:05:39 +00001506static void emitCXXDestructMethod(CodeGenFunction &CGF,
1507 ObjCImplementationDecl *impl) {
1508 CodeGenFunction::RunCleanupsScope scope(CGF);
1509
1510 llvm::Value *self = CGF.LoadObjCSelf();
1511
Jordy Rosea91768e2011-07-22 02:08:32 +00001512 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1513 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001514 ivar; ivar = ivar->getNextIvar()) {
1515 QualType type = ivar->getType();
1516
John McCall6a4fa522011-03-22 07:05:39 +00001517 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001518 QualType::DestructionKind dtorKind = type.isDestructedType();
1519 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001520
Craig Topper8a13c412014-05-21 05:09:00 +00001521 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001522
John McCall4bd0fb12011-07-12 16:41:08 +00001523 // Use a call to objc_storeStrong to destroy strong ivars, for the
1524 // general benefit of the tools.
1525 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001526 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001527
John McCall4bd0fb12011-07-12 16:41:08 +00001528 // Otherwise use the default for the destruction kind.
1529 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001530 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001531 }
John McCall4bd0fb12011-07-12 16:41:08 +00001532
1533 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1534
1535 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1536 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001537 }
1538
1539 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1540}
1541
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001542void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1543 ObjCMethodDecl *MD,
1544 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001545 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001546 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001547
1548 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001549 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001550 // Suppress the final autorelease in ARC.
1551 AutoreleaseResult = false;
1552
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001553 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001554 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001555 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001556 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001557 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001558 EmitAggExpr(IvarInit->getInit(),
1559 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001560 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001561 AggValueSlot::IsNotAliased,
1562 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001563 }
1564 // constructor returns 'self'.
1565 CodeGenTypes &Types = CGM.getTypes();
1566 QualType IdTy(CGM.getContext().getObjCIdType());
1567 llvm::Value *SelfAsId =
1568 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1569 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001570
1571 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001572 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001573 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001574 }
1575 FinishFunction();
1576}
1577
Daniel Dunbara08dff12008-09-24 04:04:31 +00001578llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001579 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001580 DeclRefExpr DRE(getContext(), Self,
1581 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001582 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001583 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001584}
1585
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001586QualType CodeGenFunction::TypeOfSelfObject() {
1587 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1588 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001589 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1590 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001591 return PTy->getPointeeType();
1592}
1593
Chris Lattnerd4808922009-03-22 21:03:39 +00001594void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001595 llvm::FunctionCallee EnumerationMutationFnPtr =
1596 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001597 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001598 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1599 return;
1600 }
John McCallb92ab1a2016-10-26 23:46:34 +00001601 CGCallee EnumerationMutationFn =
1602 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001603
Devang Pateld2d66652011-01-19 01:36:36 +00001604 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001605 if (DI)
1606 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001607
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001608 RunCleanupsScope ForScope(*this);
1609
Kuba Mracek82c21752017-04-14 01:00:03 +00001610 // The local variable comes into scope immediately.
1611 AutoVarEmission variable = AutoVarEmission::invalid();
1612 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1613 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1614
John McCall1c926b72011-01-07 01:49:06 +00001615 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001616
Anders Carlsson75658592008-08-31 02:33:12 +00001617 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001618 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001619 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001620 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001621
Anders Carlsson75658592008-08-31 02:33:12 +00001622 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001623 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001624
John McCall1c926b72011-01-07 01:49:06 +00001625 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001626 IdentifierInfo *II[] = {
1627 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1628 &CGM.getContext().Idents.get("objects"),
1629 &CGM.getContext().Idents.get("count")
1630 };
1631 Selector FastEnumSel =
1632 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001633
1634 QualType ItemsTy =
1635 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001636 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001637 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001638 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001639
John McCall53848232011-07-27 01:07:15 +00001640 // Emit the collection pointer. In ARC, we do a retain.
1641 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001642 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001643 Collection = EmitARCRetainScalarExpr(S.getCollection());
1644
1645 // Enter a cleanup to do the release.
1646 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1647 } else {
1648 Collection = EmitScalarExpr(S.getCollection());
1649 }
Mike Stump11289f42009-09-09 15:08:12 +00001650
John McCall91e82dd2011-08-05 00:14:38 +00001651 // The 'continue' label needs to appear within the cleanup for the
1652 // collection object.
1653 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1654
John McCall1c926b72011-01-07 01:49:06 +00001655 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001656 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001657
1658 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001659 Args.add(RValue::get(StatePtr.getPointer()),
1660 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001661
John McCall1c926b72011-01-07 01:49:06 +00001662 // The second argument is a temporary array with space for NumItems
1663 // pointers. We'll actually be loading elements from the array
1664 // pointer written into the control state; this buffer is so that
1665 // collections that *aren't* backed by arrays can still queue up
1666 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001667 Args.add(RValue::get(ItemsPtr.getPointer()),
1668 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001669
John McCall1c926b72011-01-07 01:49:06 +00001670 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001671 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1672 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1673 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001674
John McCall1c926b72011-01-07 01:49:06 +00001675 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001676 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001677 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1678 getContext().getNSUIntegerType(),
1679 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001680
John McCall1c926b72011-01-07 01:49:06 +00001681 // The initial number of objects that were returned in the buffer.
1682 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001683
John McCall1c926b72011-01-07 01:49:06 +00001684 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1685 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001686
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001687 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001688
John McCall1c926b72011-01-07 01:49:06 +00001689 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001690 // empty; skip all this. Set the branch weight assuming this has the same
1691 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001692 uint64_t EntryCount = getCurrentProfileCount();
1693 Builder.CreateCondBr(
1694 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1695 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001696 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001697
John McCall1c926b72011-01-07 01:49:06 +00001698 // Otherwise, initialize the loop.
1699 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001700
John McCall1c926b72011-01-07 01:49:06 +00001701 // Save the initial mutations value. This is the value at an
1702 // address that was written into the state object by
1703 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001704 Address StateMutationsPtrPtr =
1705 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001706 llvm::Value *StateMutationsPtr
1707 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001708
John McCall1c926b72011-01-07 01:49:06 +00001709 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001710 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1711 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001712
John McCall1c926b72011-01-07 01:49:06 +00001713 // Start looping. This is the point we return to whenever we have a
1714 // fresh, non-empty batch of objects.
1715 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1716 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001717
John McCall1c926b72011-01-07 01:49:06 +00001718 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001719 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001720 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001721
John McCall1c926b72011-01-07 01:49:06 +00001722 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001723 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001724 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001725
Justin Bogner66242d62015-04-23 23:06:47 +00001726 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001727
John McCall1c926b72011-01-07 01:49:06 +00001728 // Check whether the mutations value has changed from where it was
1729 // at start. StateMutationsPtr should actually be invariant between
1730 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001731 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001732 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001733 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1734 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001735
John McCall1c926b72011-01-07 01:49:06 +00001736 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001737 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001738
John McCall1c926b72011-01-07 01:49:06 +00001739 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1740 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001741
John McCall1c926b72011-01-07 01:49:06 +00001742 // If so, call the enumeration-mutation function.
1743 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001744 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001745 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001746 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001747 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001748 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001749 // FIXME: We shouldn't need to get the function info here, the runtime already
1750 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001751 EmitCall(
1752 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001753 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001754
John McCall1c926b72011-01-07 01:49:06 +00001755 // Otherwise, or if the mutation function returns, just continue.
1756 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001757
John McCall1c926b72011-01-07 01:49:06 +00001758 // Initialize the element variable.
1759 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001760 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001761 LValue elementLValue;
1762 QualType elementType;
1763 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001764 // Initialize the variable, in case it's a __block variable or something.
1765 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001766
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001767 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1768 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1769 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001770 elementLValue = EmitLValue(&tempDRE);
1771 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001772 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001773
1774 if (D->isARCPseudoStrong())
1775 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001776 } else {
1777 elementLValue = LValue(); // suppress warning
1778 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001779 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001780 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001781 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001782
1783 // Fetch the buffer out of the enumeration state.
1784 // TODO: this pointer should actually be invariant between
1785 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001786 Address StateItemsPtr =
1787 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001788 llvm::Value *EnumStateItems =
1789 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001790
John McCall1c926b72011-01-07 01:49:06 +00001791 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001792 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001793 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001794 llvm::Value *CurrentItem =
1795 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001796
John McCall1c926b72011-01-07 01:49:06 +00001797 // Cast that value to the right type.
1798 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1799 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001800
John McCall1c926b72011-01-07 01:49:06 +00001801 // Make sure we have an l-value. Yes, this gets evaluated every
1802 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001803 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001804 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001805 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001806 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001807 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1808 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001809 }
Mike Stump11289f42009-09-09 15:08:12 +00001810
John McCall9e2e22f2011-02-22 07:16:58 +00001811 // If we do have an element variable, this assignment is the end of
1812 // its initialization.
1813 if (elementIsVariable)
1814 EmitAutoVarCleanups(variable);
1815
John McCall1c926b72011-01-07 01:49:06 +00001816 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001817 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001818 {
1819 RunCleanupsScope Scope(*this);
1820 EmitStmt(S.getBody());
1821 }
Anders Carlsson75658592008-08-31 02:33:12 +00001822 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001823
John McCall1c926b72011-01-07 01:49:06 +00001824 // Destroy the element variable now.
1825 elementVariableScope.ForceCleanup();
1826
1827 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001828 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001829
John McCall1c926b72011-01-07 01:49:06 +00001830 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001831
John McCall1c926b72011-01-07 01:49:06 +00001832 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001833 llvm::Value *indexPlusOne =
1834 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001835
John McCall1c926b72011-01-07 01:49:06 +00001836 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001837 // Set the branch weights based on the simplifying assumption that this is
1838 // like a while-loop, i.e., ignoring that the false branch fetches more
1839 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001840 Builder.CreateCondBr(
1841 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001842 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001843
1844 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1845 count->addIncoming(count, AfterBody.getBlock());
1846
1847 // Otherwise, we have to fetch more elements.
1848 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001849
1850 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001851 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1852 getContext().getNSUIntegerType(),
1853 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001854
John McCall1c926b72011-01-07 01:49:06 +00001855 // If we got a zero count, we're done.
1856 llvm::Value *refetchCount = CountRV.getScalarVal();
1857
1858 // (note that the message send might split FetchMoreBB)
1859 index->addIncoming(zero, Builder.GetInsertBlock());
1860 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1861
1862 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1863 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001864
Anders Carlsson75658592008-08-31 02:33:12 +00001865 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001866 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001867
John McCall9e2e22f2011-02-22 07:16:58 +00001868 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001869 // If the element was not a declaration, set it to be null.
1870
John McCall1c926b72011-01-07 01:49:06 +00001871 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1872 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001873 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001874 }
1875
Eric Christopher7cdf9482011-10-13 21:45:18 +00001876 if (DI)
1877 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001878
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001879 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001880 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001881}
1882
Mike Stump11289f42009-09-09 15:08:12 +00001883void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001884 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001885}
1886
Mike Stump11289f42009-09-09 15:08:12 +00001887void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001888 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1889}
1890
Chris Lattnere132e242008-11-15 21:26:17 +00001891void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001892 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001893 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001894}
1895
John McCall31168b02011-06-15 23:02:42 +00001896namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001897 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001898 CallObjCRelease(llvm::Value *object) : object(object) {}
1899 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001900
Craig Topper4f12f102014-03-12 06:41:41 +00001901 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001902 // Releases at the end of the full-expression are imprecise.
1903 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001904 }
1905 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001906}
John McCall31168b02011-06-15 23:02:42 +00001907
John McCall2d637d22011-09-10 06:18:15 +00001908/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001909/// release at the end of the full-expression.
1910llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1911 llvm::Value *object) {
1912 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001913 // conditional.
1914 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001915 return object;
1916}
1917
1918llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1919 llvm::Value *value) {
1920 return EmitARCRetainAutorelease(type, value);
1921}
1922
John McCalleff18842013-03-23 02:35:54 +00001923/// Given a number of pointers, inform the optimizer that they're
1924/// being intrinsically used up until this point in the program.
1925void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001926 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001927 if (!fn)
1928 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001929
1930 // This isn't really a "runtime" function, but as an intrinsic it
1931 // doesn't really matter as long as we align things up.
1932 EmitNounwindRuntimeCall(fn, values);
1933}
1934
James Y Knight9871db02019-02-05 16:42:33 +00001935static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001936 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001937 // If the target runtime doesn't naturally support ARC, emit weak
1938 // references to the runtime support library. We don't really
1939 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001940 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1941 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001942 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001943 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001944 }
John McCall31168b02011-06-15 23:02:42 +00001945}
1946
James Y Knight9871db02019-02-05 16:42:33 +00001947static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1948 llvm::FunctionCallee RTF) {
1949 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1950}
1951
John McCall31168b02011-06-15 23:02:42 +00001952/// Perform an operation having the signature
1953/// i8* (i8*)
1954/// where a null input causes a no-op and returns null.
James Y Knight9871db02019-02-05 16:42:33 +00001955static llvm::Value *
1956emitARCValueOperation(CodeGenFunction &CGF, llvm::Value *value,
1957 llvm::Type *returnType, llvm::Function *&fn,
1958 llvm::Intrinsic::ID IntID, bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001959 if (isa<llvm::ConstantPointerNull>(value))
1960 return value;
John McCall31168b02011-06-15 23:02:42 +00001961
1962 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001963 fn = CGF.CGM.getIntrinsic(IntID);
1964 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001965 }
1966
1967 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001968 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001969 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1970
1971 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001972 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001973 if (isTailCall)
1974 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001975
1976 // Cast the result back to the original type.
1977 return CGF.Builder.CreateBitCast(call, origType);
1978}
1979
1980/// Perform an operation having the following signature:
1981/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00001982static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
1983 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001984 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00001985 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001986 fn = CGF.CGM.getIntrinsic(IntID);
1987 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001988 }
1989
1990 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001991 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001992 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1993
1994 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001995 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001996
1997 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001998 if (origType != CGF.Int8PtrTy)
1999 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002000
2001 return result;
2002}
2003
2004/// Perform an operation having the following signature:
2005/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002006static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002007 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002008 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002009 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002010 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002011 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002012
2013 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002014 fn = CGF.CGM.getIntrinsic(IntID);
2015 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002016 }
2017
Chris Lattner2192fe52011-07-18 04:24:23 +00002018 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002019
John McCall882987f2013-02-28 19:01:20 +00002020 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002021 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002022 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2023 };
2024 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002025
Craig Topper8a13c412014-05-21 05:09:00 +00002026 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002027
2028 return CGF.Builder.CreateBitCast(result, origType);
2029}
2030
2031/// Perform an operation having the following signature:
2032/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002033static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2034 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002035 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002036 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002037
2038 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002039 fn = CGF.CGM.getIntrinsic(IntID);
2040 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002041 }
2042
John McCall882987f2013-02-28 19:01:20 +00002043 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002044 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2045 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002046 };
2047 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002048}
2049
Pete Cooper2cd35962018-12-18 20:33:00 +00002050/// Perform an operation having the signature
2051/// i8* (i8*)
2052/// where a null input causes a no-op and returns null.
2053static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2054 llvm::Value *value,
2055 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002056 llvm::FunctionCallee &fn,
2057 StringRef fnName, bool MayThrow) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002058 if (isa<llvm::ConstantPointerNull>(value))
2059 return value;
2060
2061 if (!fn) {
2062 llvm::FunctionType *fnType =
2063 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2064 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002065
2066 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002067 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002068 if (fnName == "objc_retain")
2069 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002070 }
2071
2072 // Cast the argument to 'id'.
2073 llvm::Type *origType = returnType ? returnType : value->getType();
2074 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2075
2076 // Call the function.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002077 llvm::CallBase *Inst = nullptr;
2078 if (MayThrow)
2079 Inst = CGF.EmitCallOrInvoke(fn, value);
2080 else
2081 Inst = CGF.EmitNounwindRuntimeCall(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002082
2083 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002084 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002085}
2086
John McCall31168b02011-06-15 23:02:42 +00002087/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002088/// call i8* \@objc_retain(i8* %value)
2089/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002090llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2091 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002092 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002093 else
2094 return EmitARCRetainNonBlock(value);
2095}
2096
2097/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002098/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002099llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002100 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002101 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002102 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002103}
2104
2105/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002106/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002107///
2108/// \param mandatory - If false, emit the call with metadata
2109/// indicating that it's okay for the optimizer to eliminate this call
2110/// if it can prove that the block never escapes except down the stack.
2111llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2112 bool mandatory) {
2113 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002114 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002115 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002116 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002117
2118 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2119 // tell the optimizer that it doesn't need to do this copy if the
2120 // block doesn't escape, where being passed as an argument doesn't
2121 // count as escaping.
2122 if (!mandatory && isa<llvm::Instruction>(result)) {
2123 llvm::CallInst *call
2124 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002125 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002126
John McCallff613032011-10-04 06:23:45 +00002127 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002128 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002129 }
2130
2131 return result;
John McCall31168b02011-06-15 23:02:42 +00002132}
2133
John McCalle399e5b2016-01-27 18:32:30 +00002134static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002135 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002136 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002137 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002138 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002139 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002140 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002141 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002142 .getARCRetainAutoreleasedReturnValueMarker();
2143
2144 // If we have an empty assembly string, there's nothing to do.
2145 if (assembly.empty()) {
2146
2147 // Otherwise, at -O0, build an inline asm that we're going to call
2148 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002149 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002150 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002151 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002152
John McCall31168b02011-06-15 23:02:42 +00002153 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2154
2155 // If we're at -O1 and above, we don't want to litter the code
2156 // with this marker yet, so leave a breadcrumb for the ARC
2157 // optimizer to pick up.
2158 } else {
2159 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002160 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002161 "clang.arc.retainAutoreleasedReturnValueMarker");
2162 assert(metadata->getNumOperands() <= 1);
2163 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002164 auto &ctx = CGF.getLLVMContext();
2165 metadata->addOperand(llvm::MDNode::get(ctx,
2166 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002167 }
2168 }
2169 }
2170
2171 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002172 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002173 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002174}
John McCall31168b02011-06-15 23:02:42 +00002175
John McCalle399e5b2016-01-27 18:32:30 +00002176/// Retain the given object which is the result of a function call.
2177/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2178///
2179/// Yes, this function name is one character away from a different
2180/// call with completely different semantics.
2181llvm::Value *
2182CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2183 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002184 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002185 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002186 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
John McCall31168b02011-06-15 23:02:42 +00002187}
2188
John McCalle399e5b2016-01-27 18:32:30 +00002189/// Claim a possibly-autoreleased return value at +0. This is only
2190/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002191/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002192/// the value is ignored, or when it is being assigned to an
2193/// __unsafe_unretained variable.
2194///
2195/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2196llvm::Value *
2197CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2198 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002199 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002200 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002201 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002202}
2203
John McCall31168b02011-06-15 23:02:42 +00002204/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002205/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002206void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2207 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002208 if (isa<llvm::ConstantPointerNull>(value)) return;
2209
James Y Knight9871db02019-02-05 16:42:33 +00002210 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002211 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002212 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2213 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002214 }
2215
2216 // Cast the argument to 'id'.
2217 value = Builder.CreateBitCast(value, Int8PtrTy);
2218
2219 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002220 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002221
John McCallcdda29c2013-03-13 03:10:54 +00002222 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002223 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002224 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002225 }
2226}
2227
John McCalle68b8f42012-10-17 02:28:37 +00002228/// Destroy a __strong variable.
2229///
2230/// At -O0, emit a call to store 'null' into the address;
2231/// instrumenting tools prefer this because the address is exposed,
2232/// but it's relatively cumbersome to optimize.
2233///
2234/// At -O1 and above, just load and call objc_release.
2235///
2236/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002237void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002238 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002239 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002240 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002241 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2242 return;
2243 }
2244
2245 llvm::Value *value = Builder.CreateLoad(addr);
2246 EmitARCRelease(value, precise);
2247}
2248
John McCall31168b02011-06-15 23:02:42 +00002249/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002250/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002251llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002252 llvm::Value *value,
2253 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002254 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002255
James Y Knight9871db02019-02-05 16:42:33 +00002256 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002257 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002258 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2259 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002260 }
2261
John McCall882987f2013-02-28 19:01:20 +00002262 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002263 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002264 Builder.CreateBitCast(value, Int8PtrTy)
2265 };
2266 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002267
Craig Topper8a13c412014-05-21 05:09:00 +00002268 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002269 return value;
2270}
2271
2272/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002273/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002274/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002275llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002276 llvm::Value *newValue,
2277 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002278 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002279 bool isBlock = type->isBlockPointerType();
2280
2281 // Use a store barrier at -O0 unless this is a block type or the
2282 // lvalue is inadequately aligned.
2283 if (shouldUseFusedARCCalls() &&
2284 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002285 (dst.getAlignment().isZero() ||
2286 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002287 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2288 }
2289
2290 // Otherwise, split it out.
2291
2292 // Retain the new value.
2293 newValue = EmitARCRetain(type, newValue);
2294
2295 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002296 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002297
2298 // Store. We do this before the release so that any deallocs won't
2299 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002300 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002301
2302 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002303 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002304
2305 return newValue;
2306}
2307
2308/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002309/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002310llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002311 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002312 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002313 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002314}
2315
2316/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002317/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002318llvm::Value *
2319CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002320 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002321 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002322 llvm::Intrinsic::objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002323 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002324}
2325
2326/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002327/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002328llvm::Value *
2329CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002330 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002331 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002332 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002333 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002334}
2335
2336/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002337/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002338/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002339/// %retain = call i8* \@objc_retainBlock(i8* %value)
2340/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002341llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2342 llvm::Value *value) {
2343 if (!type->isBlockPointerType())
2344 return EmitARCRetainAutoreleaseNonBlock(value);
2345
2346 if (isa<llvm::ConstantPointerNull>(value)) return value;
2347
Chris Lattner2192fe52011-07-18 04:24:23 +00002348 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002349 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002350 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002351 value = EmitARCAutorelease(value);
2352 return Builder.CreateBitCast(value, origType);
2353}
2354
2355/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002356/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002357llvm::Value *
2358CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002359 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002360 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002361 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002362}
2363
John McCallb04ecb72015-10-21 18:06:43 +00002364/// i8* \@objc_loadWeak(i8** %addr)
2365/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2366llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2367 return emitARCLoadOperation(*this, addr,
2368 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002369 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002370}
2371
James Dennett14c41ea2012-06-22 05:41:30 +00002372/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002373llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002374 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002375 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002376 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002377}
2378
James Dennett14c41ea2012-06-22 05:41:30 +00002379/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002380/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002381llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002382 llvm::Value *value,
2383 bool ignored) {
2384 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002385 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002386 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002387}
2388
James Dennett14c41ea2012-06-22 05:41:30 +00002389/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002390/// Returns %value. %addr is known to not have a current weak entry.
2391/// Essentially equivalent to:
2392/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002393void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002394 // If we're initializing to null, just write null to memory; no need
2395 // to get the runtime involved. But don't do this if optimization
2396 // is enabled, because accounting for this would make the optimizer
2397 // much more complicated.
2398 if (isa<llvm::ConstantPointerNull>(value) &&
2399 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2400 Builder.CreateStore(value, addr);
2401 return;
2402 }
2403
2404 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002405 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002406 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002407}
2408
James Dennett14c41ea2012-06-22 05:41:30 +00002409/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002410/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002411void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002412 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002413 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002414 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2415 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002416 }
2417
2418 // Cast the argument to 'id*'.
2419 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2420
John McCall7f416cc2015-09-08 08:05:57 +00002421 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002422}
2423
James Dennett14c41ea2012-06-22 05:41:30 +00002424/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002425/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2426/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002427void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002428 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002429 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002430 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002431}
2432
James Dennett14c41ea2012-06-22 05:41:30 +00002433/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002434/// Disregards the current value in %dest. Essentially
2435/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002436void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002437 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002438 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002439 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002440}
2441
Akira Hatanakad791e922018-03-19 17:38:40 +00002442void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2443 Address SrcAddr) {
2444 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2445 Object = EmitObjCConsumeObject(Ty, Object);
2446 EmitARCStoreWeak(DstAddr, Object, false);
2447}
2448
2449void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2450 Address SrcAddr) {
2451 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2452 Object = EmitObjCConsumeObject(Ty, Object);
2453 EmitARCStoreWeak(DstAddr, Object, false);
2454 EmitARCDestroyWeak(SrcAddr);
2455}
2456
John McCall31168b02011-06-15 23:02:42 +00002457/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002458/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002459llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002460 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002461 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002462 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2463 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002464 }
2465
John McCall882987f2013-02-28 19:01:20 +00002466 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002467}
2468
2469/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002470/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002471void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2472 assert(value->getType() == Int8PtrTy);
2473
Pete Cooper2cd35962018-12-18 20:33:00 +00002474 if (getInvokeDest()) {
2475 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002476 llvm::FunctionCallee &fn =
2477 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002478 if (!fn) {
2479 llvm::FunctionType *fnType =
2480 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2481 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2482 setARCRuntimeFunctionLinkage(CGM, fn);
2483 }
John McCall31168b02011-06-15 23:02:42 +00002484
Pete Cooper2cd35962018-12-18 20:33:00 +00002485 // objc_autoreleasePoolPop can throw.
2486 EmitRuntimeCallOrInvoke(fn, value);
2487 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002488 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002489 if (!fn) {
2490 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2491 setARCRuntimeFunctionLinkage(CGM, fn);
2492 }
2493
2494 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002495 }
John McCall31168b02011-06-15 23:02:42 +00002496}
2497
2498/// Produce the code to do an MRR version objc_autoreleasepool_push.
2499/// Which is: [[NSAutoreleasePool alloc] init];
2500/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2501/// init is declared as: - (id) init; in its NSObject super class.
2502///
2503llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2504 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002505 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002506 // [NSAutoreleasePool alloc]
2507 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2508 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2509 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002510 RValue AllocRV =
2511 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002512 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002513 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002514
2515 // [Receiver init]
2516 Receiver = AllocRV.getScalarVal();
2517 II = &CGM.getContext().Idents.get("init");
2518 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2519 RValue InitRV =
2520 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2521 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002522 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002523 return InitRV.getScalarVal();
2524}
2525
Pete Coopere3886802018-12-08 05:13:50 +00002526/// Allocate the given objc object.
2527/// call i8* \@objc_alloc(i8* %value)
2528llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2529 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002530 return emitObjCValueOperation(*this, value, resultType,
2531 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002532 "objc_alloc", /*MayThrow=*/true);
Pete Coopere3886802018-12-08 05:13:50 +00002533}
2534
2535/// Allocate the given objc object.
2536/// call i8* \@objc_allocWithZone(i8* %value)
2537llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2538 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002539 return emitObjCValueOperation(*this, value, resultType,
2540 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002541 "objc_allocWithZone", /*MayThrow=*/true);
Pete Coopere3886802018-12-08 05:13:50 +00002542}
2543
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002544llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2545 llvm::Type *resultType) {
2546 return emitObjCValueOperation(*this, value, resultType,
2547 CGM.getObjCEntrypoints().objc_alloc_init,
2548 "objc_alloc_init", /*MayThrow=*/true);
2549}
2550
John McCall31168b02011-06-15 23:02:42 +00002551/// Produce the code to do a primitive release.
2552/// [tmp drain];
2553void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2554 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2555 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2556 CallArgList Args;
2557 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002558 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002559}
2560
John McCall82fe67b2011-07-09 01:37:26 +00002561void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002562 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002563 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002564 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002565}
2566
2567void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002568 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002569 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002570 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002571}
2572
2573void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002574 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002575 QualType type) {
2576 CGF.EmitARCDestroyWeak(addr);
2577}
2578
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002579void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2580 QualType type) {
2581 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2582 CGF.EmitARCIntrinsicUse(value);
2583}
2584
Pete Coopere5b64ea2018-12-21 21:00:32 +00002585/// Autorelease the given object.
2586/// call i8* \@objc_autorelease(i8* %value)
2587llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2588 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002589 return emitObjCValueOperation(
2590 *this, value, returnType,
2591 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2592 "objc_autorelease", /*MayThrow=*/false);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002593}
2594
2595/// Retain the given object, with normal retain semantics.
2596/// call i8* \@objc_retain(i8* %value)
2597llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2598 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002599 return emitObjCValueOperation(
2600 *this, value, returnType,
2601 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain",
2602 /*MayThrow=*/false);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002603}
2604
2605/// Release the given object.
2606/// call void \@objc_release(i8* %value)
2607void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2608 ARCPreciseLifetime_t precise) {
2609 if (isa<llvm::ConstantPointerNull>(value)) return;
2610
James Y Knight9871db02019-02-05 16:42:33 +00002611 llvm::FunctionCallee &fn =
2612 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002613 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002614 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002615 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002616 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2617 setARCRuntimeFunctionLinkage(CGM, fn);
2618 // We have Native ARC, so set nonlazybind attribute for performance
2619 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2620 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002621 }
2622
2623 // Cast the argument to 'id'.
2624 value = Builder.CreateBitCast(value, Int8PtrTy);
2625
2626 // Call objc_release.
2627 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2628
2629 if (precise == ARCImpreciseLifetime) {
2630 call->setMetadata("clang.imprecise_release",
2631 llvm::MDNode::get(Builder.getContext(), None));
2632 }
2633}
2634
John McCall31168b02011-06-15 23:02:42 +00002635namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002636 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002637 llvm::Value *Token;
2638
2639 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2640
Craig Topper4f12f102014-03-12 06:41:41 +00002641 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002642 CGF.EmitObjCAutoreleasePoolPop(Token);
2643 }
2644 };
David Blaikie7e70d682015-08-18 22:40:54 +00002645 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002646 llvm::Value *Token;
2647
2648 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2649
Craig Topper4f12f102014-03-12 06:41:41 +00002650 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002651 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2652 }
2653 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002654}
John McCall31168b02011-06-15 23:02:42 +00002655
2656void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002657 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002658 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2659 else
2660 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2661}
2662
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002663static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2664 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002665 case Qualifiers::OCL_None:
2666 case Qualifiers::OCL_ExplicitNone:
2667 case Qualifiers::OCL_Strong:
2668 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002669 return true;
John McCall31168b02011-06-15 23:02:42 +00002670
2671 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002672 return false;
John McCall31168b02011-06-15 23:02:42 +00002673 }
2674
2675 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002676}
2677
2678static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002679 LValue lvalue,
2680 QualType type) {
2681 llvm::Value *result;
2682 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2683 if (shouldRetain) {
2684 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2685 } else {
2686 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2687 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2688 }
2689 return TryEmitResult(result, !shouldRetain);
2690}
2691
2692static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002693 const Expr *e) {
2694 e = e->IgnoreParens();
2695 QualType type = e->getType();
2696
Fangrui Song6907ce22018-07-30 19:24:48 +00002697 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002698 // an extra retain/release pair by zeroing out the source of this
2699 // "move" operation.
2700 if (e->isXValue() &&
2701 !type.isConstQualified() &&
2702 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2703 // Emit the lvalue.
2704 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002705
John McCall154a2fd2011-08-30 00:57:29 +00002706 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002707 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2708 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002709
John McCall154a2fd2011-08-30 00:57:29 +00002710 // Set the source pointer to NULL.
2711 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002712
John McCall154a2fd2011-08-30 00:57:29 +00002713 return TryEmitResult(result, true);
2714 }
2715
John McCall31168b02011-06-15 23:02:42 +00002716 // As a very special optimization, in ARC++, if the l-value is the
2717 // result of a non-volatile assignment, do a simple retain of the
2718 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002719 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002720 !type.isVolatileQualified() &&
2721 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2722 isa<BinaryOperator>(e) &&
2723 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2724 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2725
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002726 // Try to emit code for scalar constant instead of emitting LValue and
2727 // loading it because we are not guaranteed to have an l-value. One of such
2728 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2729 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2730 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2731 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2732 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2733 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2734 }
2735
John McCall31168b02011-06-15 23:02:42 +00002736 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2737}
2738
John McCalle399e5b2016-01-27 18:32:30 +00002739typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2740 llvm::Value *value)>
2741 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002742
John McCalle399e5b2016-01-27 18:32:30 +00002743/// Insert code immediately after a call.
2744static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2745 llvm::Value *value,
2746 ValueTransform doAfterCall,
2747 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002748 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2749 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2750
2751 // Place the retain immediately following the call.
2752 CGF.Builder.SetInsertPoint(call->getParent(),
2753 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002754 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002755
2756 CGF.Builder.restoreIP(ip);
2757 return value;
2758 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2759 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2760
2761 // Place the retain at the beginning of the normal destination block.
2762 llvm::BasicBlock *BB = invoke->getNormalDest();
2763 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002764 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002765
2766 CGF.Builder.restoreIP(ip);
2767 return value;
2768
2769 // Bitcasts can arise because of related-result returns. Rewrite
2770 // the operand.
2771 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2772 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002773 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002774 bitcast->setOperand(0, operand);
2775 return bitcast;
2776
2777 // Generic fall-back case.
2778 } else {
2779 // Retain using the non-block variant: we never need to do a copy
2780 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002781 return doFallback(CGF, value);
2782 }
2783}
2784
2785/// Given that the given expression is some sort of call (which does
2786/// not return retained), emit a retain following it.
2787static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2788 const Expr *e) {
2789 llvm::Value *value = CGF.EmitScalarExpr(e);
2790 return emitARCOperationAfterCall(CGF, value,
2791 [](CodeGenFunction &CGF, llvm::Value *value) {
2792 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2793 },
2794 [](CodeGenFunction &CGF, llvm::Value *value) {
2795 return CGF.EmitARCRetainNonBlock(value);
2796 });
2797}
2798
2799/// Given that the given expression is some sort of call (which does
2800/// not return retained), perform an unsafeClaim following it.
2801static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2802 const Expr *e) {
2803 llvm::Value *value = CGF.EmitScalarExpr(e);
2804 return emitARCOperationAfterCall(CGF, value,
2805 [](CodeGenFunction &CGF, llvm::Value *value) {
2806 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2807 },
2808 [](CodeGenFunction &CGF, llvm::Value *value) {
2809 return value;
2810 });
2811}
2812
2813llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2814 bool allowUnsafeClaim) {
2815 if (allowUnsafeClaim &&
2816 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2817 return emitARCUnsafeClaimCallResult(*this, E);
2818 } else {
2819 llvm::Value *value = emitARCRetainCallResult(*this, E);
2820 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002821 }
2822}
2823
John McCallcd78e802011-09-10 01:16:55 +00002824/// Determine whether it might be important to emit a separate
2825/// objc_retain_block on the result of the given expression, or
2826/// whether it's okay to just emit it in a +1 context.
2827static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2828 assert(e->getType()->isBlockPointerType());
2829 e = e->IgnoreParens();
2830
2831 // For future goodness, emit block expressions directly in +1
2832 // contexts if we can.
2833 if (isa<BlockExpr>(e))
2834 return false;
2835
2836 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2837 switch (cast->getCastKind()) {
2838 // Emitting these operations in +1 contexts is goodness.
2839 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002840 case CK_ARCReclaimReturnedObject:
2841 case CK_ARCConsumeObject:
2842 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002843 return false;
2844
2845 // These operations preserve a block type.
2846 case CK_NoOp:
2847 case CK_BitCast:
2848 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2849
2850 // These operations are known to be bad (or haven't been considered).
2851 case CK_AnyPointerToBlockPointerCast:
2852 default:
2853 return true;
2854 }
2855 }
2856
2857 return true;
2858}
2859
John McCalle399e5b2016-01-27 18:32:30 +00002860namespace {
2861/// A CRTP base class for emitting expressions of retainable object
2862/// pointer type in ARC.
2863template <typename Impl, typename Result> class ARCExprEmitter {
2864protected:
2865 CodeGenFunction &CGF;
2866 Impl &asImpl() { return *static_cast<Impl*>(this); }
2867
2868 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2869
2870public:
2871 Result visit(const Expr *e);
2872 Result visitCastExpr(const CastExpr *e);
2873 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002874 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002875 Result visitBinaryOperator(const BinaryOperator *e);
2876 Result visitBinAssign(const BinaryOperator *e);
2877 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2878 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2879 Result visitBinAssignWeak(const BinaryOperator *e);
2880 Result visitBinAssignStrong(const BinaryOperator *e);
2881
2882 // Minimal implementation:
2883 // Result visitLValueToRValue(const Expr *e)
2884 // Result visitConsumeObject(const Expr *e)
2885 // Result visitExtendBlockObject(const Expr *e)
2886 // Result visitReclaimReturnedObject(const Expr *e)
2887 // Result visitCall(const Expr *e)
2888 // Result visitExpr(const Expr *e)
2889 //
2890 // Result emitBitCast(Result result, llvm::Type *resultType)
2891 // llvm::Value *getValueOfResult(Result result)
2892};
2893}
2894
2895/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002896///
2897/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002898template <typename Impl, typename Result>
2899Result
2900ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002901 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002902
2903 // Find the result expression.
2904 const Expr *resultExpr = E->getResultExpr();
2905 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002906 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002907
2908 for (PseudoObjectExpr::const_semantics_iterator
2909 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2910 const Expr *semantic = *i;
2911
2912 // If this semantic expression is an opaque value, bind it
2913 // to the result of its source expression.
2914 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2915 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2916 OVMA opaqueData;
2917
2918 // If this semantic is the result of the pseudo-object
2919 // expression, try to evaluate the source as +1.
2920 if (ov == resultExpr) {
2921 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002922 result = asImpl().visit(ov->getSourceExpr());
2923 opaqueData = OVMA::bind(CGF, ov,
2924 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002925
2926 // Otherwise, just bind it.
2927 } else {
2928 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2929 }
2930 opaques.push_back(opaqueData);
2931
2932 // Otherwise, if the expression is the result, evaluate it
2933 // and remember the result.
2934 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002935 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002936
2937 // Otherwise, evaluate the expression in an ignored context.
2938 } else {
2939 CGF.EmitIgnoredExpr(semantic);
2940 }
2941 }
2942
2943 // Unbind all the opaques now.
2944 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2945 opaques[i].unbind(CGF);
2946
2947 return result;
2948}
2949
John McCalle399e5b2016-01-27 18:32:30 +00002950template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002951Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2952 // The default implementation just forwards the expression to visitExpr.
2953 return asImpl().visitExpr(e);
2954}
2955
2956template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00002957Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2958 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002959
John McCalle399e5b2016-01-27 18:32:30 +00002960 // No-op casts don't change the type, so we just ignore them.
2961 case CK_NoOp:
2962 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002963
John McCalle399e5b2016-01-27 18:32:30 +00002964 // These casts can change the type.
2965 case CK_CPointerToObjCPointerCast:
2966 case CK_BlockPointerToObjCPointerCast:
2967 case CK_AnyPointerToBlockPointerCast:
2968 case CK_BitCast: {
2969 llvm::Type *resultType = CGF.ConvertType(e->getType());
2970 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2971 Result result = asImpl().visit(e->getSubExpr());
2972 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002973 }
2974
John McCalle399e5b2016-01-27 18:32:30 +00002975 // Handle some casts specially.
2976 case CK_LValueToRValue:
2977 return asImpl().visitLValueToRValue(e->getSubExpr());
2978 case CK_ARCConsumeObject:
2979 return asImpl().visitConsumeObject(e->getSubExpr());
2980 case CK_ARCExtendBlockObject:
2981 return asImpl().visitExtendBlockObject(e->getSubExpr());
2982 case CK_ARCReclaimReturnedObject:
2983 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2984
2985 // Otherwise, use the default logic.
2986 default:
2987 return asImpl().visitExpr(e);
2988 }
2989}
2990
2991template <typename Impl, typename Result>
2992Result
2993ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2994 switch (e->getOpcode()) {
2995 case BO_Comma:
2996 CGF.EmitIgnoredExpr(e->getLHS());
2997 CGF.EnsureInsertPoint();
2998 return asImpl().visit(e->getRHS());
2999
3000 case BO_Assign:
3001 return asImpl().visitBinAssign(e);
3002
3003 default:
3004 return asImpl().visitExpr(e);
3005 }
3006}
3007
3008template <typename Impl, typename Result>
3009Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3010 switch (e->getLHS()->getType().getObjCLifetime()) {
3011 case Qualifiers::OCL_ExplicitNone:
3012 return asImpl().visitBinAssignUnsafeUnretained(e);
3013
3014 case Qualifiers::OCL_Weak:
3015 return asImpl().visitBinAssignWeak(e);
3016
3017 case Qualifiers::OCL_Autoreleasing:
3018 return asImpl().visitBinAssignAutoreleasing(e);
3019
3020 case Qualifiers::OCL_Strong:
3021 return asImpl().visitBinAssignStrong(e);
3022
3023 case Qualifiers::OCL_None:
3024 return asImpl().visitExpr(e);
3025 }
3026 llvm_unreachable("bad ObjC ownership qualifier");
3027}
3028
3029/// The default rule for __unsafe_unretained emits the RHS recursively,
3030/// stores into the unsafe variable, and propagates the result outward.
3031template <typename Impl, typename Result>
3032Result ARCExprEmitter<Impl,Result>::
3033 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3034 // Recursively emit the RHS.
3035 // For __block safety, do this before emitting the LHS.
3036 Result result = asImpl().visit(e->getRHS());
3037
3038 // Perform the store.
3039 LValue lvalue =
3040 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3041 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3042 lvalue);
3043
3044 return result;
3045}
3046
3047template <typename Impl, typename Result>
3048Result
3049ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3050 return asImpl().visitExpr(e);
3051}
3052
3053template <typename Impl, typename Result>
3054Result
3055ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3056 return asImpl().visitExpr(e);
3057}
3058
3059template <typename Impl, typename Result>
3060Result
3061ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3062 return asImpl().visitExpr(e);
3063}
3064
3065/// The general expression-emission logic.
3066template <typename Impl, typename Result>
3067Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3068 // We should *never* see a nested full-expression here, because if
3069 // we fail to emit at +1, our caller must not retain after we close
3070 // out the full-expression. This isn't as important in the unsafe
3071 // emitter.
3072 assert(!isa<ExprWithCleanups>(e));
3073
3074 // Look through parens, __extension__, generic selection, etc.
3075 e = e->IgnoreParens();
3076
3077 // Handle certain kinds of casts.
3078 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3079 return asImpl().visitCastExpr(ce);
3080
3081 // Handle the comma operator.
3082 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3083 return asImpl().visitBinaryOperator(op);
3084
3085 // TODO: handle conditional operators here
3086
3087 // For calls and message sends, use the retained-call logic.
3088 // Delegate inits are a special case in that they're the only
3089 // returns-retained expression that *isn't* surrounded by
3090 // a consume.
3091 } else if (isa<CallExpr>(e) ||
3092 (isa<ObjCMessageExpr>(e) &&
3093 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3094 return asImpl().visitCall(e);
3095
3096 // Look through pseudo-object expressions.
3097 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3098 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003099 } else if (auto *be = dyn_cast<BlockExpr>(e))
3100 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003101
3102 return asImpl().visitExpr(e);
3103}
3104
3105namespace {
3106
3107/// An emitter for +1 results.
3108struct ARCRetainExprEmitter :
3109 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3110
3111 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3112
3113 llvm::Value *getValueOfResult(TryEmitResult result) {
3114 return result.getPointer();
3115 }
3116
3117 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3118 llvm::Value *value = result.getPointer();
3119 value = CGF.Builder.CreateBitCast(value, resultType);
3120 result.setPointer(value);
3121 return result;
3122 }
3123
3124 TryEmitResult visitLValueToRValue(const Expr *e) {
3125 return tryEmitARCRetainLoadOfScalar(CGF, e);
3126 }
3127
3128 /// For consumptions, just emit the subexpression and thus elide
3129 /// the retain/release pair.
3130 TryEmitResult visitConsumeObject(const Expr *e) {
3131 llvm::Value *result = CGF.EmitScalarExpr(e);
3132 return TryEmitResult(result, true);
3133 }
3134
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003135 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3136 TryEmitResult result = visitExpr(e);
3137 // Avoid the block-retain if this is a block literal that doesn't need to be
3138 // copied to the heap.
3139 if (e->getBlockDecl()->canAvoidCopyToHeap())
3140 result.setInt(true);
3141 return result;
3142 }
3143
John McCalle399e5b2016-01-27 18:32:30 +00003144 /// Block extends are net +0. Naively, we could just recurse on
3145 /// the subexpression, but actually we need to ensure that the
3146 /// value is copied as a block, so there's a little filter here.
3147 TryEmitResult visitExtendBlockObject(const Expr *e) {
3148 llvm::Value *result; // will be a +0 value
3149
3150 // If we can't safely assume the sub-expression will produce a
3151 // block-copied value, emit the sub-expression at +0.
3152 if (shouldEmitSeparateBlockRetain(e)) {
3153 result = CGF.EmitScalarExpr(e);
3154
3155 // Otherwise, try to emit the sub-expression at +1 recursively.
3156 } else {
3157 TryEmitResult subresult = asImpl().visit(e);
3158
3159 // If that produced a retained value, just use that.
3160 if (subresult.getInt()) {
3161 return subresult;
3162 }
3163
3164 // Otherwise it's +0.
3165 result = subresult.getPointer();
3166 }
3167
3168 // Retain the object as a block.
3169 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3170 return TryEmitResult(result, true);
3171 }
3172
3173 /// For reclaims, emit the subexpression as a retained call and
3174 /// skip the consumption.
3175 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3176 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3177 return TryEmitResult(result, true);
3178 }
3179
3180 /// When we have an undecorated call, retroactively do a claim.
3181 TryEmitResult visitCall(const Expr *e) {
3182 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3183 return TryEmitResult(result, true);
3184 }
3185
3186 // TODO: maybe special-case visitBinAssignWeak?
3187
3188 TryEmitResult visitExpr(const Expr *e) {
3189 // We didn't find an obvious production, so emit what we've got and
3190 // tell the caller that we didn't manage to retain.
3191 llvm::Value *result = CGF.EmitScalarExpr(e);
3192 return TryEmitResult(result, false);
3193 }
3194};
3195}
3196
3197static TryEmitResult
3198tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3199 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003200}
3201
3202static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3203 LValue lvalue,
3204 QualType type) {
3205 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3206 llvm::Value *value = result.getPointer();
3207 if (!result.getInt())
3208 value = CGF.EmitARCRetain(type, value);
3209 return value;
3210}
3211
3212/// EmitARCRetainScalarExpr - Semantically equivalent to
3213/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3214/// best-effort attempt to peephole expressions that naturally produce
3215/// retained objects.
3216llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003217 // The retain needs to happen within the full-expression.
3218 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3219 enterFullExpression(cleanups);
3220 RunCleanupsScope scope(*this);
3221 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3222 }
3223
John McCall31168b02011-06-15 23:02:42 +00003224 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3225 llvm::Value *value = result.getPointer();
3226 if (!result.getInt())
3227 value = EmitARCRetain(e->getType(), value);
3228 return value;
3229}
3230
3231llvm::Value *
3232CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003233 // The retain needs to happen within the full-expression.
3234 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3235 enterFullExpression(cleanups);
3236 RunCleanupsScope scope(*this);
3237 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3238 }
3239
John McCall31168b02011-06-15 23:02:42 +00003240 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3241 llvm::Value *value = result.getPointer();
3242 if (result.getInt())
3243 value = EmitARCAutorelease(value);
3244 else
3245 value = EmitARCRetainAutorelease(e->getType(), value);
3246 return value;
3247}
3248
John McCallff613032011-10-04 06:23:45 +00003249llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3250 llvm::Value *result;
3251 bool doRetain;
3252
3253 if (shouldEmitSeparateBlockRetain(e)) {
3254 result = EmitScalarExpr(e);
3255 doRetain = true;
3256 } else {
3257 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3258 result = subresult.getPointer();
3259 doRetain = !subresult.getInt();
3260 }
3261
3262 if (doRetain)
3263 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3264 return EmitObjCConsumeObject(e->getType(), result);
3265}
3266
John McCall248512a2011-10-01 10:32:24 +00003267llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3268 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003269 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003270 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003271 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003272 return EmitARCRetainAutoreleaseScalarExpr(expr);
3273 }
3274
3275 // Otherwise, use the normal scalar-expression emission. The
3276 // exception machinery doesn't do anything special with the
3277 // exception like retaining it, so there's no safety associated with
3278 // only running cleanups after the throw has started, and when it
3279 // matters it tends to be substantially inferior code.
3280 return EmitScalarExpr(expr);
3281}
3282
John McCalle399e5b2016-01-27 18:32:30 +00003283namespace {
3284
3285/// An emitter for assigning into an __unsafe_unretained context.
3286struct ARCUnsafeUnretainedExprEmitter :
3287 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3288
3289 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3290
3291 llvm::Value *getValueOfResult(llvm::Value *value) {
3292 return value;
3293 }
3294
3295 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3296 return CGF.Builder.CreateBitCast(value, resultType);
3297 }
3298
3299 llvm::Value *visitLValueToRValue(const Expr *e) {
3300 return CGF.EmitScalarExpr(e);
3301 }
3302
3303 /// For consumptions, just emit the subexpression and perform the
3304 /// consumption like normal.
3305 llvm::Value *visitConsumeObject(const Expr *e) {
3306 llvm::Value *value = CGF.EmitScalarExpr(e);
3307 return CGF.EmitObjCConsumeObject(e->getType(), value);
3308 }
3309
3310 /// No special logic for block extensions. (This probably can't
3311 /// actually happen in this emitter, though.)
3312 llvm::Value *visitExtendBlockObject(const Expr *e) {
3313 return CGF.EmitARCExtendBlockObject(e);
3314 }
3315
3316 /// For reclaims, perform an unsafeClaim if that's enabled.
3317 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3318 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3319 }
3320
3321 /// When we have an undecorated call, just emit it without adding
3322 /// the unsafeClaim.
3323 llvm::Value *visitCall(const Expr *e) {
3324 return CGF.EmitScalarExpr(e);
3325 }
3326
3327 /// Just do normal scalar emission in the default case.
3328 llvm::Value *visitExpr(const Expr *e) {
3329 return CGF.EmitScalarExpr(e);
3330 }
3331};
3332}
3333
3334static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3335 const Expr *e) {
3336 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3337}
3338
3339/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3340/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3341/// avoiding any spurious retains, including by performing reclaims
3342/// with objc_unsafeClaimAutoreleasedReturnValue.
3343llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3344 // Look through full-expressions.
3345 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3346 enterFullExpression(cleanups);
3347 RunCleanupsScope scope(*this);
3348 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3349 }
3350
3351 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3352}
3353
3354std::pair<LValue,llvm::Value*>
3355CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3356 bool ignored) {
3357 // Evaluate the RHS first. If we're ignoring the result, assume
3358 // that we can emit at an unsafe +0.
3359 llvm::Value *value;
3360 if (ignored) {
3361 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3362 } else {
3363 value = EmitScalarExpr(e->getRHS());
3364 }
3365
3366 // Emit the LHS and perform the store.
3367 LValue lvalue = EmitLValue(e->getLHS());
3368 EmitStoreOfScalar(value, lvalue);
3369
3370 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3371}
3372
John McCall31168b02011-06-15 23:02:42 +00003373std::pair<LValue,llvm::Value*>
3374CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3375 bool ignored) {
3376 // Evaluate the RHS first.
3377 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3378 llvm::Value *value = result.getPointer();
3379
John McCallb726a552011-07-28 07:23:35 +00003380 bool hasImmediateRetain = result.getInt();
3381
3382 // If we didn't emit a retained object, and the l-value is of block
3383 // type, then we need to emit the block-retain immediately in case
3384 // it invalidates the l-value.
3385 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003386 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003387 hasImmediateRetain = true;
3388 }
3389
John McCall31168b02011-06-15 23:02:42 +00003390 LValue lvalue = EmitLValue(e->getLHS());
3391
3392 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003393 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003394 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003395 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003396 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003397 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003398 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003399 }
3400
3401 return std::pair<LValue,llvm::Value*>(lvalue, value);
3402}
3403
3404std::pair<LValue,llvm::Value*>
3405CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3406 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3407 LValue lvalue = EmitLValue(e->getLHS());
3408
Eli Friedmana0544d62011-12-03 04:14:32 +00003409 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003410
3411 return std::pair<LValue,llvm::Value*>(lvalue, value);
3412}
3413
3414void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003415 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003416 const Stmt *subStmt = ARPS.getSubStmt();
3417 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3418
3419 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003420 if (DI)
3421 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003422
3423 // Keep track of the current cleanup stack depth.
3424 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003425 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003426 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3427 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3428 } else {
3429 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3430 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3431 }
3432
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003433 for (const auto *I : S.body())
3434 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003435
Eric Christopher7cdf9482011-10-13 21:45:18 +00003436 if (DI)
3437 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003438}
John McCall1bd25562011-06-24 23:21:27 +00003439
3440/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3441/// make sure it survives garbage collection until this point.
3442void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3443 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003444 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003445 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003446 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3447 /* assembly */ "",
3448 /* constraints */ "r",
3449 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003450
3451 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003452 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003453}
3454
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003455/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003456/// non-trivial copy assignment function, produce following helper function.
3457/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3458///
3459llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003460CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3461 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003462 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003463 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003464 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003465 QualType Ty = PID->getPropertyIvarDecl()->getType();
3466 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003467 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003468 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003469 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003470 return nullptr;
3471 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003472 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003473 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003474 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3475 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3476 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003477
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003478 ASTContext &C = getContext();
3479 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003480 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003481
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003482 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003483 QualType DestTy = C.getPointerType(Ty);
3484 QualType SrcTy = Ty;
3485 SrcTy.addConst();
3486 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003487
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003488 SmallVector<QualType, 2> ArgTys;
3489 ArgTys.push_back(DestTy);
3490 ArgTys.push_back(SrcTy);
3491 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3492
3493 FunctionDecl *FD = FunctionDecl::Create(
3494 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3495 FunctionTy, nullptr, SC_Static, false, false);
3496
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003497 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003498 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3499 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003500 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003501 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3502 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003503 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003504
John McCallc56a8b32016-03-11 04:30:31 +00003505 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003506 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003507
John McCalla729c622012-02-17 03:33:10 +00003508 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003509
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003510 llvm::Function *Fn =
3511 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003512 "__assign_helper_atomic_property_",
3513 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003514
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003515 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003516
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003517 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003518
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003519 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3520 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003521 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003522 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003523
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003524 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3525 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003526 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003527 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003528
John McCall113bee02012-03-10 09:33:50 +00003529 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003530 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003531 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3532 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3533 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003534
Bruno Riccic5885cf2018-12-21 15:20:32 +00003535 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003536
3537 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003538 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003539 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003540 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003541}
3542
3543llvm::Constant *
3544CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3545 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003546 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003547 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003548 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003549 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3550 QualType Ty = PD->getType();
3551 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003552 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003553 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003554 return nullptr;
3555 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003556 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003557 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003558 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3559 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3560 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003561
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003562 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003563 IdentifierInfo *II =
3564 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003565
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003566 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003567 QualType DestTy = C.getPointerType(Ty);
3568 QualType SrcTy = Ty;
3569 SrcTy.addConst();
3570 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003571
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003572 SmallVector<QualType, 2> ArgTys;
3573 ArgTys.push_back(DestTy);
3574 ArgTys.push_back(SrcTy);
3575 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3576
3577 FunctionDecl *FD = FunctionDecl::Create(
3578 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3579 FunctionTy, nullptr, SC_Static, false, false);
3580
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003581 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003582 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3583 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003584 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003585 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3586 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003587 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003588
John McCallc56a8b32016-03-11 04:30:31 +00003589 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003590 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003591
John McCalla729c622012-02-17 03:33:10 +00003592 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003593
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003594 llvm::Function *Fn = llvm::Function::Create(
3595 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3596 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003597
3598 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003599
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003600 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003601
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003602 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3603 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003604
John McCall113bee02012-03-10 09:33:50 +00003605 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003606 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003607
3608 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003609 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003610
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003611 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003612 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003613 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3614 CXXConstExpr->arg_end());
3615
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003616 CXXConstructExpr *TheCXXConstructExpr =
3617 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3618 CXXConstExpr->getConstructor(),
3619 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003620 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003621 CXXConstExpr->hadMultipleCandidates(),
3622 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003623 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003624 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003625 CXXConstExpr->getConstructionKind(),
3626 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003627
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003628 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3629 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003630
John McCall113bee02012-03-10 09:33:50 +00003631 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003632 CharUnits Alignment
3633 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003634 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003635 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3636 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003637 AggValueSlot::IsDestructed,
3638 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003639 AggValueSlot::IsNotAliased,
3640 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003641
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003642 FinishFunction();
3643 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3644 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3645 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003646}
3647
Eli Friedmanec75fec2012-02-28 01:08:45 +00003648llvm::Value *
3649CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3650 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003651 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3652 Selector CopySelector =
3653 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003654 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3655 Selector AutoreleaseSelector =
3656 getContext().Selectors.getNullarySelector(AutoreleaseID);
3657
3658 // Emit calls to retain/autorelease.
3659 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3660 llvm::Value *Val = Block;
3661 RValue Result;
3662 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003663 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003664 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003665 Val = Result.getScalarVal();
3666 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3667 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003668 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003669 Val = Result.getScalarVal();
3670 return Val;
3671}
3672
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003673llvm::Value *
3674CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3675 assert(Args.size() == 3 && "Expected 3 argument here!");
3676
3677 if (!CGM.IsOSVersionAtLeastFn) {
3678 llvm::FunctionType *FTy =
3679 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3680 CGM.IsOSVersionAtLeastFn =
3681 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3682 }
3683
3684 llvm::Value *CallRes =
3685 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3686
3687 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3688}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003689
Alex Lorenza8fbef42017-03-23 11:14:27 +00003690void CodeGenModule::emitAtAvailableLinkGuard() {
3691 if (!IsOSVersionAtLeastFn)
3692 return;
3693 // @available requires CoreFoundation only on Darwin.
3694 if (!Target.getTriple().isOSDarwin())
3695 return;
3696 // Add -framework CoreFoundation to the linker commands. We still want to
3697 // emit the core foundation reference down below because otherwise if
3698 // CoreFoundation is not used in the code, the linker won't link the
3699 // framework.
3700 auto &Context = getLLVMContext();
3701 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3702 llvm::MDString::get(Context, "CoreFoundation")};
3703 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3704 // Emit a reference to a symbol from CoreFoundation to ensure that
3705 // CoreFoundation is linked into the final binary.
3706 llvm::FunctionType *FTy =
3707 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003708 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003709 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3710
3711 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003712 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3713 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
3714 llvm::AttributeList(), /*IsLocal=*/true);
3715 llvm::Function *CFLinkCheckFunc =
3716 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3717 if (CFLinkCheckFunc->empty()) {
3718 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3719 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3720 CodeGenFunction CGF(*this);
3721 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3722 CGF.EmitNounwindRuntimeCall(CFFunc,
3723 llvm::Constant::getNullValue(VoidPtrTy));
3724 CGF.Builder.CreateUnreachable();
3725 addCompilerUsedGlobal(CFLinkCheckFunc);
3726 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003727}
3728
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003729CGObjCRuntime::~CGObjCRuntime() {}