blob: c52aa6bb54963ddf55650be8afb6ae6af1ff9f08 [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"
Akira Hatanaka1488ee42019-03-08 04:45:37 +000017#include "ConstantEmitter.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080020#include "clang/AST/Attr.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000021#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000022#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000023#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000024#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000025#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
Fangrui Song6907ce22018-07-30 19:24:48 +000048 llvm::Constant *C =
John McCall7f416cc2015-09-08 08:05:57 +000049 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Patrick Beard0caa3942012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
Alex Denisovfde64952015-06-26 05:28:36 +000056/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57/// or [NSValue valueWithBytes:objCType:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000058///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000059llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisovfde64952015-06-26 05:28:36 +000064 const Expr *SubExpr = E->getSubExpr();
Akira Hatanaka1488ee42019-03-08 04:45:37 +000065
66 if (E->isExpressibleAsConstantInitializer()) {
67 ConstantEmitter ConstEmitter(CGM);
68 return ConstEmitter.tryEmitAbstract(E, E->getType());
69 }
70
Patrick Beard0caa3942012-04-19 00:25:12 +000071 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
72 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000073
Ted Kremeneke65b0862012-03-06 20:05:56 +000074 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000075 // Assumes that the method was introduced in the class that should be
76 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000077 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000078 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000079 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000080
Ted Kremeneke65b0862012-03-06 20:05:56 +000081 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000082 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
83 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000084
85 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000086 // via [NSValue valueWithBytes:objCType:]
87 const QualType ValueType(SubExpr->getType().getCanonicalType());
88 if (ValueType->isObjCBoxableRecordType()) {
89 // Emit CodeGen for first parameter
90 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000091 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000092 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000093 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
94 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000095
96 // Create char array to store type encoding
97 std::string Str;
98 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000099 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +0000100
Alex Denisovfde64952015-06-26 05:28:36 +0000101 // Cast type encoding to correct type
102 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
103 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
104 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
105
106 Args.add(RValue::get(Cast), EncodingQT);
107 } else {
108 Args.add(EmitAnyExpr(SubExpr), ArgQT);
109 }
Alp Toker314cc812014-01-25 16:55:45 +0000110
111 RValue result = Runtime.GenerateMessageSend(
112 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
113 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000114 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 ConvertType(E->getType()));
116}
117
118llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000119 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000120 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000121 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000122 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
123 if (!ALE)
124 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000125
126 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000127 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000128 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000129 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
130 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
131 QualType IdTy(CGM.getContext().getObjCIdType());
132 llvm::Constant *Constant =
133 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000134 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000135 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000136 cast<llvm::LoadInst>(Ptr)->setMetadata(
137 CGM.getModule().getMDKindID("invariant.load"),
138 llvm::MDNode::get(getLLVMContext(), None));
139 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000140 }
141
142 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000143 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
144 NumElements);
145 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000146 QualType ElementArrayType
Richard Smith772e2662019-10-04 01:25:59 +0000147 = Context.getConstantArrayType(ElementType, APNumElements, nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 ArrayType::Normal, /*IndexTypeQuals=*/0);
149
150 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000151 Address Objects = CreateMemTemp(ElementArrayType, "objects");
152 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000153 if (DLE)
154 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000155
John McCall770a4c12013-04-04 00:20:38 +0000156 // In ARC, we may need to do extra work to keep all the keys and
157 // values alive until after the call.
158 SmallVector<llvm::Value *, 16> NeededObjects;
159 bool TrackNeededObjects =
160 (getLangOpts().ObjCAutoRefCount &&
161 CGM.getCodeGenOpts().OptimizationLevel != 0);
162
Ted Kremeneke65b0862012-03-06 20:05:56 +0000163 // Perform the actual initialialization of the array(s).
164 for (uint64_t i = 0; i < NumElements; i++) {
165 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000166 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000167 const Expr *Rhs = ALE->getElement(i);
James Y Knight751fe282019-02-09 22:22:28 +0000168 LValue LV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
169 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000170
171 llvm::Value *value = EmitScalarExpr(Rhs);
172 EmitStoreThroughLValue(RValue::get(value), LV, true);
173 if (TrackNeededObjects) {
174 NeededObjects.push_back(value);
175 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000176 } else {
John McCall770a4c12013-04-04 00:20:38 +0000177 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000178 const Expr *Key = DLE->getKeyValueElement(i).Key;
James Y Knight751fe282019-02-09 22:22:28 +0000179 LValue KeyLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Keys, i),
180 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000181 llvm::Value *keyValue = EmitScalarExpr(Key);
182 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000183
John McCall770a4c12013-04-04 00:20:38 +0000184 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000185 const Expr *Value = DLE->getKeyValueElement(i).Value;
James Y Knight751fe282019-02-09 22:22:28 +0000186 LValue ValueLV = MakeAddrLValue(Builder.CreateConstArrayGEP(Objects, i),
187 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000188 llvm::Value *valueValue = EmitScalarExpr(Value);
189 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
190 if (TrackNeededObjects) {
191 NeededObjects.push_back(keyValue);
192 NeededObjects.push_back(valueValue);
193 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000194 }
195 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000196
Ted Kremeneke65b0862012-03-06 20:05:56 +0000197 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000198 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000199 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
200 const ParmVarDecl *argDecl = *PI++;
201 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000202 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000203 if (DLE) {
204 argDecl = *PI++;
205 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000206 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000207 }
208 argDecl = *PI;
209 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000210 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000211 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
212 Args.add(RValue::get(Count), ArgQT);
213
214 // Generate a reference to the class pointer, which will be the receiver.
215 Selector Sel = MethodWithObjects->getSelector();
216 QualType ResultType = E->getType();
217 const ObjCObjectPointerType *InterfacePointerType
218 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000219 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000220 = InterfacePointerType->getObjectType()->getInterface();
221 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000222 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000223
224 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000225 RValue result = Runtime.GenerateMessageSend(
226 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
227 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000228
229 // The above message send needs these objects, but in ARC they are
230 // passed in a buffer that is essentially __unsafe_unretained.
231 // Therefore we must prevent the optimizer from releasing them until
232 // after the call.
233 if (TrackNeededObjects) {
234 EmitARCIntrinsicUse(NeededObjects);
235 }
236
Fangrui Song6907ce22018-07-30 19:24:48 +0000237 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000238 ConvertType(E->getType()));
239}
240
241llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000242 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000243}
244
245llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
246 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000247 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248}
249
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000250/// Emit a selector.
251llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
252 // Untyped selector.
253 // Note that this implementation allows for non-constant strings to be passed
254 // as arguments to @selector(). Currently, the only thing preventing this
255 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000256 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000257}
258
Daniel Dunbar66912a12008-08-20 00:28:19 +0000259llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
260 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000261 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000262}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000263
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000264/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000265/// to type erasure at various points, e.g., related result types or the use
266/// of parameterized classes.
267static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
268 RValue Result) {
269 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000270 return Result;
John McCall31168b02011-06-15 23:02:42 +0000271
Douglas Gregore83b9562015-07-07 03:57:53 +0000272 // If the converted types are the same, we're done.
273 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
274 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000275 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000276
277 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000278 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000279 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000280}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000281
John McCallcf166702011-07-22 08:53:00 +0000282/// Decide whether to extend the lifetime of the receiver of a
283/// returns-inner-pointer message.
284static bool
285shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
286 switch (message->getReceiverKind()) {
287
288 // For a normal instance message, we should extend unless the
289 // receiver is loaded from a variable with precise lifetime.
290 case ObjCMessageExpr::Instance: {
291 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000292
293 // Look through OVEs.
294 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
295 if (opaque->getSourceExpr())
296 receiver = opaque->getSourceExpr()->IgnoreParens();
297 }
298
John McCallcf166702011-07-22 08:53:00 +0000299 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
300 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
301 receiver = ice->getSubExpr()->IgnoreParens();
302
John McCall6380a282015-09-09 23:37:17 +0000303 // Look through OVEs.
304 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
305 if (opaque->getSourceExpr())
306 receiver = opaque->getSourceExpr()->IgnoreParens();
307 }
308
John McCallcf166702011-07-22 08:53:00 +0000309 // Only __strong variables.
310 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
311 return true;
312
313 // All ivars and fields have precise lifetime.
314 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
315 return false;
316
317 // Otherwise, check for variables.
318 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
319 if (!declRef) return true;
320 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
321 if (!var) return true;
322
323 // All variables have precise lifetime except local variables with
324 // automatic storage duration that aren't specially marked.
325 return (var->hasLocalStorage() &&
326 !var->hasAttr<ObjCPreciseLifetimeAttr>());
327 }
328
329 case ObjCMessageExpr::Class:
330 case ObjCMessageExpr::SuperClass:
331 // It's never necessary for class objects.
332 return false;
333
334 case ObjCMessageExpr::SuperInstance:
335 // We generally assume that 'self' lives throughout a method call.
336 return false;
337 }
338
339 llvm_unreachable("invalid receiver kind");
340}
341
John McCall460ce582015-10-22 18:38:17 +0000342/// Given an expression of ObjC pointer type, check whether it was
343/// immediately loaded from an ARC __weak l-value.
344static const Expr *findWeakLValue(const Expr *E) {
345 assert(E->getType()->isObjCRetainableType());
346 E = E->IgnoreParens();
347 if (auto CE = dyn_cast<CastExpr>(E)) {
348 if (CE->getCastKind() == CK_LValueToRValue) {
349 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
350 return CE->getSubExpr();
351 }
352 }
353
354 return nullptr;
355}
356
Pete Coopere3886802018-12-08 05:13:50 +0000357/// The ObjC runtime may provide entrypoints that are likely to be faster
358/// than an ordinary message send of the appropriate selector.
359///
360/// The entrypoints are guaranteed to be equivalent to just sending the
361/// corresponding message. If the entrypoint is implemented naively as just a
362/// message send, using it is a trade-off: it sacrifices a few cycles of
363/// overhead to save a small amount of code. However, it's possible for
364/// runtimes to detect and special-case classes that use "standard"
365/// behavior; if that's dynamically a large proportion of all objects, using
366/// the entrypoint will also be faster than using a message send.
367///
368/// If the runtime does support a required entrypoint, then this method will
369/// generate a call and return the resulting value. Otherwise it will return
370/// None and the caller can generate a msgSend instead.
371static Optional<llvm::Value *>
372tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
373 llvm::Value *Receiver,
374 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000375 const ObjCMethodDecl *method,
376 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000377 auto &CGM = CGF.CGM;
378 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
379 return None;
380
381 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
382 switch (Sel.getMethodFamily()) {
383 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000384 if (isClassMessage &&
385 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000386 ResultType->isObjCObjectPointerType()) {
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000387 // [Foo alloc] -> objc_alloc(Foo) or
388 // [self alloc] -> objc_alloc(self)
Pete Coopere3886802018-12-08 05:13:50 +0000389 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
390 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000391 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo) or
392 // [self allocWithZone:nil] -> objc_allocWithZone(self)
Pete Coopere3886802018-12-08 05:13:50 +0000393 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
394 Args.size() == 1 && Args.front().getType()->isPointerType() &&
395 Sel.getNameForSlot(0) == "allocWithZone") {
396 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
397 if (isa<llvm::ConstantPointerNull>(arg))
398 return CGF.EmitObjCAllocWithZone(Receiver,
399 CGF.ConvertType(ResultType));
400 return None;
401 }
402 }
403 break;
404
Pete Coopere5b64ea2018-12-21 21:00:32 +0000405 case OMF_autorelease:
406 if (ResultType->isObjCObjectPointerType() &&
407 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
408 Runtime.shouldUseARCFunctionsForRetainRelease())
409 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
410 break;
411
412 case OMF_retain:
413 if (ResultType->isObjCObjectPointerType() &&
414 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
415 Runtime.shouldUseARCFunctionsForRetainRelease())
416 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
417 break;
418
419 case OMF_release:
420 if (ResultType->isVoidType() &&
421 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
422 Runtime.shouldUseARCFunctionsForRetainRelease()) {
423 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
424 return nullptr;
425 }
426 break;
427
Pete Coopere3886802018-12-08 05:13:50 +0000428 default:
429 break;
430 }
431 return None;
432}
433
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800434CodeGen::RValue CGObjCRuntime::GeneratePossiblySpecializedMessageSend(
435 CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
436 Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
437 const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
438 bool isClassMessage) {
439 if (Optional<llvm::Value *> SpecializedResult =
440 tryGenerateSpecializedMessageSend(CGF, ResultType, Receiver, Args,
441 Sel, Method, isClassMessage)) {
442 return RValue::get(SpecializedResult.getValue());
443 }
444 return GenerateMessageSend(CGF, Return, ResultType, Sel, Receiver, Args, OID,
445 Method);
446}
447
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000448/// Instead of '[[MyClass alloc] init]', try to generate
449/// 'objc_alloc_init(MyClass)'. This provides a code size improvement on the
450/// caller side, as well as the optimized objc_alloc.
451static Optional<llvm::Value *>
452tryEmitSpecializedAllocInit(CodeGenFunction &CGF, const ObjCMessageExpr *OME) {
453 auto &Runtime = CGF.getLangOpts().ObjCRuntime;
454 if (!Runtime.shouldUseRuntimeFunctionForCombinedAllocInit())
455 return None;
456
457 // Match the exact pattern '[[MyClass alloc] init]'.
458 Selector Sel = OME->getSelector();
Erik Pilkington55e703a2019-02-25 21:35:14 +0000459 if (OME->getReceiverKind() != ObjCMessageExpr::Instance ||
460 !OME->getType()->isObjCObjectPointerType() || !Sel.isUnarySelector() ||
461 Sel.getNameForSlot(0) != "init")
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000462 return None;
463
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000464 // Okay, this is '[receiver init]', check if 'receiver' is '[cls alloc]' or
465 // we are in an ObjC class method and 'receiver' is '[self alloc]'.
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000466 auto *SubOME =
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000467 dyn_cast<ObjCMessageExpr>(OME->getInstanceReceiver()->IgnoreParenCasts());
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000468 if (!SubOME)
469 return None;
470 Selector SubSel = SubOME->getSelector();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000471
472 // Check if we are in an ObjC class method and the receiver expression is
473 // 'self'.
474 const Expr *SelfInClassMethod = nullptr;
475 if (const auto *CurMD = dyn_cast_or_null<ObjCMethodDecl>(CGF.CurFuncDecl))
476 if (CurMD->isClassMethod())
477 if ((SelfInClassMethod = SubOME->getInstanceReceiver()))
478 if (!SelfInClassMethod->isObjCSelfExpr())
479 SelfInClassMethod = nullptr;
480
481 if ((SubOME->getReceiverKind() != ObjCMessageExpr::Class &&
482 !SelfInClassMethod) || !SubOME->getType()->isObjCObjectPointerType() ||
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000483 !SubSel.isUnarySelector() || SubSel.getNameForSlot(0) != "alloc")
484 return None;
485
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000486 llvm::Value *Receiver;
487 if (SelfInClassMethod) {
488 Receiver = CGF.EmitScalarExpr(SelfInClassMethod);
489 } else {
490 QualType ReceiverType = SubOME->getClassReceiver();
Simon Pilgrim25dc5c72020-01-14 13:28:46 +0000491 const ObjCObjectType *ObjTy = ReceiverType->castAs<ObjCObjectType>();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000492 const ObjCInterfaceDecl *ID = ObjTy->getInterface();
493 assert(ID && "null interface should be impossible here");
494 Receiver = CGF.CGM.getObjCRuntime().GetClass(CGF, ID);
495 }
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000496 return CGF.EmitObjCAllocInit(Receiver, CGF.ConvertType(OME->getType()));
497}
498
John McCall78a15112010-05-22 01:48:05 +0000499RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
500 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000501 // Only the lookup mechanism and first two arguments of the method
502 // implementation vary between runtimes. We can get the receiver and
503 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000504
John McCall31168b02011-06-15 23:02:42 +0000505 bool isDelegateInit = E->isDelegateInitCall();
506
John McCallcf166702011-07-22 08:53:00 +0000507 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000508
John McCall460ce582015-10-22 18:38:17 +0000509 // If the method is -retain, and the receiver's being loaded from
510 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
511 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
512 method->getMethodFamily() == OMF_retain) {
513 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
514 LValue lvalue = EmitLValue(lvalueExpr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800515 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +0000516 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
517 }
518 }
519
Erik Pilkingtonec389b02019-02-14 19:58:37 +0000520 if (Optional<llvm::Value *> Val = tryEmitSpecializedAllocInit(*this, E))
521 return AdjustObjCObjectType(*this, E->getType(), RValue::get(*Val));
522
John McCall31168b02011-06-15 23:02:42 +0000523 // We don't retain the receiver in delegate init calls, and this is
524 // safe because the receiver value is always loaded from 'self',
525 // which we zero out. We don't want to Block_copy block receivers,
526 // though.
527 bool retainSelf =
528 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000529 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000530 method &&
531 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000532
Daniel Dunbar8d480592008-08-11 18:12:00 +0000533 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000534 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000535 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000536 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000537 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000538 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000539 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000540 switch (E->getReceiverKind()) {
541 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000542 ReceiverType = E->getInstanceReceiver()->getType();
Akira Hatanaka48566aa2019-06-04 16:29:58 +0000543 if (auto *OMD = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl))
544 if (OMD->isClassMethod())
545 if (E->getInstanceReceiver()->isObjCSelfExpr())
546 isClassMessage = true;
John McCall31168b02011-06-15 23:02:42 +0000547 if (retainSelf) {
548 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
549 E->getInstanceReceiver());
550 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000551 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000552 } else
553 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000554 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000555
Douglas Gregor9a129192010-04-21 00:45:42 +0000556 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000557 ReceiverType = E->getClassReceiver();
Simon Pilgrim25dc5c72020-01-14 13:28:46 +0000558 OID = ReceiverType->castAs<ObjCObjectType>()->getInterface();
John McCall3e294922010-05-17 20:12:43 +0000559 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000560 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000561 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000562 break;
563 }
564
565 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000566 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000567 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000568 isSuperMessage = true;
569 break;
570
571 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000572 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000573 Receiver = LoadObjCSelf();
574 isSuperMessage = true;
575 isClassMessage = true;
576 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000577 }
578
John McCallcf166702011-07-22 08:53:00 +0000579 if (retainSelf)
580 Receiver = EmitARCRetainNonBlock(Receiver);
581
582 // In ARC, we sometimes want to "extend the lifetime"
583 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
584 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000585 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000586 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
587 shouldExtendReceiverForInnerPointerMessage(E))
588 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
589
Alp Toker314cc812014-01-25 16:55:45 +0000590 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000591
Daniel Dunbarc722b852008-08-30 03:02:31 +0000592 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000593 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000594
John McCall31168b02011-06-15 23:02:42 +0000595 // For delegate init calls in ARC, do an unsafe store of null into
596 // self. This represents the call taking direct ownership of that
597 // value. We have to do this after emitting the other call
598 // arguments because they might also reference self, but we don't
599 // have to worry about any of them modifying self because that would
600 // be an undefined read and write of an object in unordered
601 // expressions.
602 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000603 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000604 "delegate init calls should only be marked in ARC");
605
606 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000607 Address selfAddr =
608 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000609 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
610 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000611
Douglas Gregor33823722011-06-11 01:09:30 +0000612 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000613 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000614 // super is only valid in an Objective-C method
615 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000616 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000617 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
618 E->getSelector(),
619 OMD->getClassInterface(),
620 isCategoryImpl,
621 Receiver,
622 isClassMessage,
623 Args,
John McCallcf166702011-07-22 08:53:00 +0000624 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000625 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000626 // Call runtime methods directly if we can.
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800627 result = Runtime.GeneratePossiblySpecializedMessageSend(
628 *this, Return, ResultType, E->getSelector(), Receiver, Args, OID,
629 method, isClassMessage);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000630 }
John McCall31168b02011-06-15 23:02:42 +0000631
632 // For delegate init calls in ARC, implicitly store the result of
633 // the call back into self. This takes ownership of the value.
634 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000635 Address selfAddr =
636 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000637 llvm::Value *newSelf = result.getScalarVal();
638
639 // The delegate return type isn't necessarily a matching type; in
640 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000641 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000642 newSelf = Builder.CreateBitCast(newSelf, selfTy);
643
644 Builder.CreateStore(newSelf, selfAddr);
645 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000646
Douglas Gregore83b9562015-07-07 03:57:53 +0000647 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000648}
649
John McCall31168b02011-06-15 23:02:42 +0000650namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000651struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000652 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000653 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000654
655 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000656 const ObjCInterfaceDecl *iface = impl->getClassInterface();
657 if (!iface->getSuperClass()) return;
658
John McCalldffafde2011-07-13 18:26:47 +0000659 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
660
John McCall31168b02011-06-15 23:02:42 +0000661 // Call [super dealloc] if we have a superclass.
662 llvm::Value *self = CGF.LoadObjCSelf();
663
664 CallArgList args;
665 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
666 CGF.getContext().VoidTy,
667 method->getSelector(),
668 iface,
John McCalldffafde2011-07-13 18:26:47 +0000669 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000670 self,
671 /*is class msg*/ false,
672 args,
673 method);
674 }
675};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000676}
John McCall31168b02011-06-15 23:02:42 +0000677
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000678/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
679/// the LLVM function and sets the other context used by
680/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000681void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000682 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000683 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000684 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000685 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000686 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000687 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000688
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000689 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000690
John McCalla729c622012-02-17 03:33:10 +0000691 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800692 if (OMD->isDirectMethod()) {
693 Fn->setVisibility(llvm::Function::HiddenVisibility);
694 CGM.SetLLVMFunctionAttributes(OMD, FI, Fn);
695 CGM.SetLLVMFunctionAttributesForDefinition(OMD, Fn);
696 } else {
697 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
698 }
Chris Lattner5696e7b2008-06-17 18:05:57 +0000699
John McCalla738c252011-03-09 04:27:21 +0000700 args.push_back(OMD->getSelfDecl());
701 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000702
Benjamin Kramerf9890422015-02-17 16:48:30 +0000703 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000704
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000705 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000706 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000707
Adrian Prantl42d71b92014-04-10 23:21:53 +0000708 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
709 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000710
Pierre Habouzitd4e1ba32019-11-07 23:14:58 -0800711 if (OMD->isDirectMethod()) {
712 // This function is a direct call, it has to implement a nil check
713 // on entry.
714 //
715 // TODO: possibly have several entry points to elide the check
716 CGM.getObjCRuntime().GenerateDirectMethodPrologue(*this, Fn, OMD, CD);
717 }
718
John McCall31168b02011-06-15 23:02:42 +0000719 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000720 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000721 OMD->isInstanceMethod() &&
722 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000723 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000724 OMD->getSelector().getIdentifierInfoForSlot(0);
725 if (ident->isStr("dealloc"))
726 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
727 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000728}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000729
John McCall31168b02011-06-15 23:02:42 +0000730static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
731 LValue lvalue, QualType type);
732
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000733/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000734/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000735void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000736 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000737 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000738 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000739 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000740 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000741 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000742}
743
John McCallb923ece2011-09-12 23:06:44 +0000744/// emitStructGetterCall - Call the runtime function to load a property
745/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000746static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000747 bool isAtomic, bool hasStrong) {
748 ASTContext &Context = CGF.getContext();
749
John McCall7f416cc2015-09-08 08:05:57 +0000750 Address src =
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800751 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
752 .getAddress(CGF);
John McCallb923ece2011-09-12 23:06:44 +0000753
Fangrui Song6907ce22018-07-30 19:24:48 +0000754 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000755 // sizeof (Type of Ivar), isAtomic, false);
756 CallArgList args;
757
John McCall7f416cc2015-09-08 08:05:57 +0000758 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
759 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000760
761 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000762 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000763
764 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
765 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
766 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
767 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
768
James Y Knight9871db02019-02-05 16:42:33 +0000769 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000770 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000771 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000772 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000773}
774
John McCallf4528ae2011-09-13 03:34:09 +0000775/// Determine whether the given architecture supports unaligned atomic
776/// accesses. They don't have to be fast, just faster than a function
777/// call and a mutex.
778static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000779 // FIXME: Allow unaligned atomic load/store on x86. (It is not
780 // currently supported by the backend.)
781 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000782}
783
784/// Return the maximum size that permits atomic accesses for the given
785/// architecture.
786static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
787 llvm::Triple::ArchType arch) {
788 // ARM has 8-byte atomic accesses, but it's not clear whether we
789 // want to rely on them here.
790
791 // In the default case, just assume that any size up to a pointer is
792 // fine given adequate alignment.
793 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
794}
795
796namespace {
797 class PropertyImplStrategy {
798 public:
799 enum StrategyKind {
800 /// The 'native' strategy is to use the architecture's provided
801 /// reads and writes.
802 Native,
803
804 /// Use objc_setProperty and objc_getProperty.
805 GetSetProperty,
806
807 /// Use objc_setProperty for the setter, but use expression
808 /// evaluation for the getter.
809 SetPropertyAndExpressionGet,
810
811 /// Use objc_copyStruct.
812 CopyStruct,
813
814 /// The 'expression' strategy is to emit normal assignment or
815 /// lvalue-to-rvalue expressions.
816 Expression
817 };
818
819 StrategyKind getKind() const { return StrategyKind(Kind); }
820
821 bool hasStrongMember() const { return HasStrong; }
822 bool isAtomic() const { return IsAtomic; }
823 bool isCopy() const { return IsCopy; }
824
825 CharUnits getIvarSize() const { return IvarSize; }
826 CharUnits getIvarAlignment() const { return IvarAlignment; }
827
828 PropertyImplStrategy(CodeGenModule &CGM,
829 const ObjCPropertyImplDecl *propImpl);
830
831 private:
832 unsigned Kind : 8;
833 unsigned IsAtomic : 1;
834 unsigned IsCopy : 1;
835 unsigned HasStrong : 1;
836
837 CharUnits IvarSize;
838 CharUnits IvarAlignment;
839 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000840}
John McCallf4528ae2011-09-13 03:34:09 +0000841
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000842/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000843PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
844 const ObjCPropertyImplDecl *propImpl) {
845 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000846 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000847
John McCall43192862011-09-13 18:31:23 +0000848 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
849 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000850 HasStrong = false; // doesn't matter here.
851
852 // Evaluate the ivar's size and alignment.
853 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
854 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000855 std::tie(IvarSize, IvarAlignment) =
856 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000857
858 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000859 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000860 if (IsCopy) {
861 Kind = GetSetProperty;
862 return;
863 }
864
John McCall43192862011-09-13 18:31:23 +0000865 // Handle retain.
866 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000867 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000868 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000869 // fallthrough
870
871 // In ARC, if the property is non-atomic, use expression emission,
872 // which translates to objc_storeStrong. This isn't required, but
873 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000874 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000875 // Using standard expression emission for the setter is only
876 // acceptable if the ivar is __strong, which won't be true if
877 // the property is annotated with __attribute__((NSObject)).
878 // TODO: falling all the way back to objc_setProperty here is
879 // just laziness, though; we could still use objc_storeStrong
880 // if we hacked it right.
881 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
882 Kind = Expression;
883 else
884 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000885 return;
886
887 // Otherwise, we need to at least use setProperty. However, if
888 // the property isn't atomic, we can use normal expression
889 // emission for the getter.
890 } else if (!IsAtomic) {
891 Kind = SetPropertyAndExpressionGet;
892 return;
893
894 // Otherwise, we have to use both setProperty and getProperty.
895 } else {
896 Kind = GetSetProperty;
897 return;
898 }
899 }
900
901 // If we're not atomic, just use expression accesses.
902 if (!IsAtomic) {
903 Kind = Expression;
904 return;
905 }
906
John McCall0e5c0862011-09-13 05:36:29 +0000907 // Properties on bitfield ivars need to be emitted using expression
908 // accesses even if they're nominally atomic.
909 if (ivar->isBitField()) {
910 Kind = Expression;
911 return;
912 }
913
John McCallf4528ae2011-09-13 03:34:09 +0000914 // GC-qualified or ARC-qualified ivars need to be emitted as
915 // expressions. This actually works out to being atomic anyway,
916 // except for ARC __strong, but that should trigger the above code.
917 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000918 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000919 CGM.getContext().getObjCGCAttrKind(ivarType))) {
920 Kind = Expression;
921 return;
922 }
923
924 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000925 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000926 if (const RecordType *recordType = ivarType->getAs<RecordType>())
927 HasStrong = recordType->getDecl()->hasObjectMember();
928
929 // We can never access structs with object members with a native
930 // access, because we need to use write barriers. This is what
931 // objc_copyStruct is for.
932 if (HasStrong) {
933 Kind = CopyStruct;
934 return;
935 }
936
937 // Otherwise, this is target-dependent and based on the size and
938 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000939
940 // If the size of the ivar is not a power of two, give up. We don't
941 // want to get into the business of doing compare-and-swaps.
942 if (!IvarSize.isPowerOfTwo()) {
943 Kind = CopyStruct;
944 return;
945 }
946
John McCallf4528ae2011-09-13 03:34:09 +0000947 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000948 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000949
950 // Most architectures require memory to fit within a single cache
951 // line, so the alignment has to be at least the size of the access.
952 // Otherwise we have to grab a lock.
953 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
954 Kind = CopyStruct;
955 return;
956 }
957
958 // If the ivar's size exceeds the architecture's maximum atomic
959 // access size, we have to use CopyStruct.
960 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
961 Kind = CopyStruct;
962 return;
963 }
964
965 // Otherwise, we can use native loads and stores.
966 Kind = Native;
967}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000969/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000970///
971/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000972/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000973void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
974 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000975 llvm::Constant *AtomicHelperFn =
976 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -0800977 ObjCMethodDecl *OMD = PID->getGetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000978 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000979 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000980
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000981 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000982
Adrian Prantlce7d3592019-12-05 12:26:16 -0800983 FinishFunction(OMD->getEndLoc());
John McCallf4528ae2011-09-13 03:34:09 +0000984}
985
John McCallbdd81852011-09-13 06:00:03 +0000986static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
987 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000988 if (!getter) return true;
989
990 // Sema only makes only of these when the ivar has a C++ class type,
991 // so the form is pretty constrained.
992
John McCallbdd81852011-09-13 06:00:03 +0000993 // If the property has a reference type, we might just be binding a
994 // reference, in which case the result will be a gl-value. We should
995 // treat this as a non-trivial operation.
996 if (getter->isGLValue())
997 return false;
998
John McCallf4528ae2011-09-13 03:34:09 +0000999 // If we selected a trivial copy-constructor, we're okay.
1000 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
1001 return (construct->getConstructor()->isTrivial());
1002
1003 // The constructor might require cleanups (in which case it's never
1004 // trivial).
1005 assert(isa<ExprWithCleanups>(getter));
1006 return false;
1007}
1008
Fangrui Song6907ce22018-07-30 19:24:48 +00001009/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001010/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +00001011static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001012 llvm::Value *returnAddr,
1013 ObjCIvarDecl *ivar,
1014 llvm::Constant *AtomicHelperFn) {
1015 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
1016 // AtomicHelperFn);
1017 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001018
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001019 // The 1st argument is the return Slot.
1020 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001021
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001022 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001023 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001024 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1025 .getPointer(CGF);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001026 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1027 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001028
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001029 // Third argument is the helper function.
1030 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001031
James Y Knight9871db02019-02-05 16:42:33 +00001032 llvm::FunctionCallee copyCppAtomicObjectFn =
1033 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001034 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +00001035 CGF.EmitCall(
1036 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001037 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001038}
1039
John McCallf4528ae2011-09-13 03:34:09 +00001040void
1041CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001042 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +00001043 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001044 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +00001045 // If there's a non-trivial 'get' expression, we just have to emit that.
1046 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001047 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +00001048 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
1049 propImpl->getGetterCXXConstructor(),
1050 /* NRVOCandidate=*/nullptr);
1051 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001052 }
1053 else {
1054 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001055 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001056 ivar, AtomicHelperFn);
1057 }
John McCallf4528ae2011-09-13 03:34:09 +00001058 return;
1059 }
1060
1061 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1062 QualType propType = prop->getType();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001063 ObjCMethodDecl *getterMethod = propImpl->getGetterMethodDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001064
Fangrui Song6907ce22018-07-30 19:24:48 +00001065 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +00001066
1067 // Pick an implementation strategy.
1068 PropertyImplStrategy strategy(CGM, propImpl);
1069 switch (strategy.getKind()) {
1070 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001071 // We don't need to do anything for a zero-size struct.
1072 if (strategy.getIvarSize().isZero())
1073 return;
1074
John McCallf4528ae2011-09-13 03:34:09 +00001075 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1076
1077 // Currently, all atomic accesses have to be through integer
1078 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001079 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1080 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001081 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1082
1083 // Perform an atomic load. This does not impose ordering constraints.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001084 Address ivarAddr = LV.getAddress(*this);
John McCallf4528ae2011-09-13 03:34:09 +00001085 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1086 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001087 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001088
1089 // Store that value into the return address. Doing this with a
1090 // bitcast is likely to produce some pretty ugly IR, but it's not
1091 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001092 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1093 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1094 llvm::Value *ivarVal = load;
1095 if (ivarSize > retTySize) {
1096 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1097 ivarVal = Builder.CreateTrunc(load, newTy);
1098 bitcastType = newTy->getPointerTo();
1099 }
1100 Builder.CreateStore(ivarVal,
1101 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001102
1103 // Make sure we don't do an autorelease.
1104 AutoreleaseResult = false;
1105 return;
1106 }
1107
1108 case PropertyImplStrategy::GetSetProperty: {
James Y Knight9871db02019-02-05 16:42:33 +00001109 llvm::FunctionCallee getPropertyFn =
1110 CGM.getObjCRuntime().GetPropertyGetFunction();
John McCallf4528ae2011-09-13 03:34:09 +00001111 if (!getPropertyFn) {
1112 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001113 return;
1114 }
John McCallb92ab1a2016-10-26 23:46:34 +00001115 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001116
1117 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1118 // FIXME: Can't this be simpler? This might even be worse than the
1119 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001120 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001121 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001122 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1123 llvm::Value *ivarOffset =
1124 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1125
1126 CallArgList args;
1127 args.add(RValue::get(self), getContext().getObjCIdType());
1128 args.add(RValue::get(cmd), getContext().getObjCSelType());
1129 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001130 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1131 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001132
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001133 // FIXME: We shouldn't need to get the function info here, the
1134 // runtime already should have computed it to build the function.
James Y Knight3933add2019-01-30 02:54:28 +00001135 llvm::CallBase *CallInstruction;
James Y Knightb92d2902019-02-05 16:05:50 +00001136 RValue RV = EmitCall(getTypes().arrangeBuiltinFunctionCall(
1137 getContext().getObjCIdType(), args),
1138 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001139 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1140 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001141
Daniel Dunbara08dff12008-09-24 04:04:31 +00001142 // We need to fix the type here. Ivars with copy & retain are
1143 // always objects so we don't need to worry about complex or
1144 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001145 RV = RValue::get(Builder.CreateBitCast(
1146 RV.getScalarVal(),
1147 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001148
1149 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001150
1151 // objc_getProperty does an autorelease, so we should suppress ours.
1152 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001153
John McCallf4528ae2011-09-13 03:34:09 +00001154 return;
1155 }
1156
1157 case PropertyImplStrategy::CopyStruct:
1158 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1159 strategy.hasStrongMember());
1160 return;
1161
1162 case PropertyImplStrategy::Expression:
1163 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1164 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1165
1166 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001167 switch (getEvaluationKind(ivarType)) {
1168 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001169 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001170 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001171 /*init*/ true);
1172 return;
1173 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001174 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001175 // The return value slot is guaranteed to not be aliased, but
1176 // that's not necessarily the same as "on the stack", so
1177 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001178 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smith8cca3a52019-06-20 20:56:20 +00001179 /* Src= */ LV, ivarType, getOverlapForReturnValue());
Richard Smithe78fac52018-04-05 20:52:58 +00001180 return;
1181 }
John McCall47fb9502013-03-07 21:37:08 +00001182 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001183 llvm::Value *value;
1184 if (propType->isReferenceType()) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001185 value = LV.getAddress(*this).getPointer();
John McCall24fada12011-07-22 05:23:13 +00001186 } else {
1187 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1188 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001189 if (getLangOpts().ObjCAutoRefCount) {
1190 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1191 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001192 value = EmitARCLoadWeak(LV.getAddress(*this));
John McCall460ce582015-10-22 18:38:17 +00001193 }
John McCall24fada12011-07-22 05:23:13 +00001194
1195 // Otherwise we want to do a simple load, suppressing the
1196 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001197 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001198 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001199 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001200 }
John McCall31168b02011-06-15 23:02:42 +00001201
Alp Toker314cc812014-01-25 16:55:45 +00001202 value = Builder.CreateBitCast(
1203 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001204 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001205
John McCall24fada12011-07-22 05:23:13 +00001206 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001207 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001208 }
John McCall47fb9502013-03-07 21:37:08 +00001209 }
1210 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001211 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001212
John McCallf4528ae2011-09-13 03:34:09 +00001213 }
1214 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001215}
1216
John McCallb923ece2011-09-12 23:06:44 +00001217/// emitStructSetterCall - Call the runtime function to store the value
1218/// from the first formal parameter into the given ivar.
1219static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1220 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001221 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001222 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001223 CallArgList args;
1224
1225 // The first argument is the address of the ivar.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001226 llvm::Value *ivarAddr =
1227 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1228 .getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001229 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1230 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001231
1232 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001233 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001234 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1235 argVar->getType().getNonReferenceType(), VK_LValue,
1236 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001237 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
John McCallb923ece2011-09-12 23:06:44 +00001238 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1239 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001240
1241 // The third argument is the sizeof the type.
1242 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001243 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1244 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001245
John McCallb923ece2011-09-12 23:06:44 +00001246 // The fourth argument is the 'isAtomic' flag.
1247 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001248
John McCallb923ece2011-09-12 23:06:44 +00001249 // The fifth argument is the 'hasStrong' flag.
1250 // FIXME: should this really always be false?
1251 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1252
James Y Knight9871db02019-02-05 16:42:33 +00001253 llvm::FunctionCallee fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001254 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001255 CGF.EmitCall(
1256 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001257 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001258}
1259
Fangrui Song6907ce22018-07-30 19:24:48 +00001260/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1261/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001262/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001263static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001264 ObjCMethodDecl *OMD,
1265 ObjCIvarDecl *ivar,
1266 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001267 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001268 // AtomicHelperFn);
1269 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001270
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001271 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001272 llvm::Value *ivarAddr =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001273 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
1274 .getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001275 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1276 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001277
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001278 // The second argument is the address of the parameter variable.
1279 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001280 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1281 argVar->getType().getNonReferenceType(), VK_LValue,
1282 SourceLocation());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001283 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer(CGF);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001284 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1285 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001286
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001287 // Third argument is the helper function.
1288 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001289
James Y Knight9871db02019-02-05 16:42:33 +00001290 llvm::FunctionCallee fn =
1291 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001292 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001293 CGF.EmitCall(
1294 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001295 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001296}
1297
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001298
John McCallf4528ae2011-09-13 03:34:09 +00001299static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1300 Expr *setter = PID->getSetterCXXAssignment();
1301 if (!setter) return true;
1302
1303 // Sema only makes only of these when the ivar has a C++ class type,
1304 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001305
1306 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001307 // This also implies that there's nothing non-trivial going on with
1308 // the arguments, because operator= can only be trivial if it's a
1309 // synthesized assignment operator and therefore both parameters are
1310 // references.
1311 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001312 if (const FunctionDecl *callee
1313 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1314 if (callee->isTrivial())
1315 return true;
1316 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001317 }
John McCall7f16c422011-09-10 09:17:20 +00001318
John McCallf4528ae2011-09-13 03:34:09 +00001319 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001320 return false;
1321}
1322
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001323static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001324 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001325 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001326 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001327}
1328
John McCall7f16c422011-09-10 09:17:20 +00001329void
1330CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001331 const ObjCPropertyImplDecl *propImpl,
1332 llvm::Constant *AtomicHelperFn) {
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001333 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Adrian Prantl2073dd22019-11-04 14:28:14 -08001334 ObjCMethodDecl *setterMethod = propImpl->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001335
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001336 // Just use the setter expression if Sema gave us one and it's
1337 // non-trivial.
1338 if (!hasTrivialSetExpr(propImpl)) {
1339 if (!AtomicHelperFn)
1340 // If non-atomic, assignment is called directly.
1341 EmitStmt(propImpl->getSetterCXXAssignment());
1342 else
1343 // If atomic, assignment is called via a locking api.
1344 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1345 AtomicHelperFn);
1346 return;
1347 }
John McCall7f16c422011-09-10 09:17:20 +00001348
John McCallf4528ae2011-09-13 03:34:09 +00001349 PropertyImplStrategy strategy(CGM, propImpl);
1350 switch (strategy.getKind()) {
1351 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001352 // We don't need to do anything for a zero-size struct.
1353 if (strategy.getIvarSize().isZero())
1354 return;
1355
John McCall7f416cc2015-09-08 08:05:57 +00001356 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001357
John McCallf4528ae2011-09-13 03:34:09 +00001358 LValue ivarLValue =
1359 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001360 Address ivarAddr = ivarLValue.getAddress(*this);
John McCall7f16c422011-09-10 09:17:20 +00001361
John McCallf4528ae2011-09-13 03:34:09 +00001362 // Currently, all atomic accesses have to be through integer
1363 // types, so there's no point in trying to pick a prettier type.
1364 llvm::Type *bitcastType =
1365 llvm::Type::getIntNTy(getLLVMContext(),
1366 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001367
1368 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001369 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1370 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001371
1372 // This bitcast load is likely to cause some nasty IR.
1373 llvm::Value *load = Builder.CreateLoad(argAddr);
1374
1375 // Perform an atomic store. There are no memory ordering requirements.
1376 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001377 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001378 return;
1379 }
1380
1381 case PropertyImplStrategy::GetSetProperty:
1382 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001383
James Y Knight9871db02019-02-05 16:42:33 +00001384 llvm::FunctionCallee setOptimizedPropertyFn = nullptr;
1385 llvm::FunctionCallee setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001386 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001387 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001388 setOptimizedPropertyFn =
James Y Knight9871db02019-02-05 16:42:33 +00001389 CGM.getObjCRuntime().GetOptimizedPropertySetFunction(
1390 strategy.isAtomic(), strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001391 if (!setOptimizedPropertyFn) {
1392 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1393 return;
1394 }
John McCall7f16c422011-09-10 09:17:20 +00001395 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001396 else {
1397 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1398 if (!setPropertyFn) {
1399 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1400 return;
1401 }
1402 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001403
John McCall7f16c422011-09-10 09:17:20 +00001404 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1405 // <is-atomic>, <is-copy>).
1406 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001407 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001408 llvm::Value *self =
1409 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1410 llvm::Value *ivarOffset =
1411 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001412 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1413 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1414 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001415
1416 CallArgList args;
1417 args.add(RValue::get(self), getContext().getObjCIdType());
1418 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001419 if (setOptimizedPropertyFn) {
1420 args.add(RValue::get(arg), getContext().getObjCIdType());
1421 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001422 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001423 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001424 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001425 } else {
1426 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1427 args.add(RValue::get(arg), getContext().getObjCIdType());
1428 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1429 getContext().BoolTy);
1430 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1431 getContext().BoolTy);
1432 // FIXME: We shouldn't need to get the function info here, the runtime
1433 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001434 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001435 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001436 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001437 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001438
John McCall7f16c422011-09-10 09:17:20 +00001439 return;
1440 }
1441
John McCallf4528ae2011-09-13 03:34:09 +00001442 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001443 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001444 return;
John McCallf4528ae2011-09-13 03:34:09 +00001445
1446 case PropertyImplStrategy::Expression:
1447 break;
John McCall7f16c422011-09-10 09:17:20 +00001448 }
1449
1450 // Otherwise, fake up some ASTs and emit a normal assignment.
1451 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001452 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001453 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001454 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1455 selfDecl->getType(), CK_LValueToRValue, &self,
1456 VK_RValue);
1457 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001458 SourceLocation(), SourceLocation(),
1459 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001460
1461 ParmVarDecl *argDecl = *setterMethod->param_begin();
1462 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001463 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1464 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001465 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1466 argType.getUnqualifiedType(), CK_LValueToRValue,
1467 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001468
John McCall7f16c422011-09-10 09:17:20 +00001469 // The property type can differ from the ivar type in some situations with
1470 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1471 // The following absurdity is just to ensure well-formed IR.
1472 CastKind argCK = CK_NoOp;
1473 if (ivarRef.getType()->isObjCObjectPointerType()) {
1474 if (argLoad.getType()->isObjCObjectPointerType())
1475 argCK = CK_BitCast;
1476 else if (argLoad.getType()->isBlockPointerType())
1477 argCK = CK_BlockPointerToObjCPointerCast;
1478 else
1479 argCK = CK_CPointerToObjCPointerCast;
1480 } else if (ivarRef.getType()->isBlockPointerType()) {
1481 if (argLoad.getType()->isBlockPointerType())
1482 argCK = CK_BitCast;
1483 else
1484 argCK = CK_AnyPointerToBlockPointerCast;
1485 } else if (ivarRef.getType()->isPointerType()) {
1486 argCK = CK_BitCast;
1487 }
1488 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1489 ivarRef.getType(), argCK, &argLoad,
1490 VK_RValue);
1491 Expr *finalArg = &argLoad;
1492 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1493 argLoad.getType()))
1494 finalArg = &argCast;
1495
1496
1497 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1498 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001499 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001500 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001501}
1502
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001503/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001504///
1505/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001506/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001507void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1508 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001509 llvm::Constant *AtomicHelperFn =
1510 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Adrian Prantl2073dd22019-11-04 14:28:14 -08001511 ObjCMethodDecl *OMD = PID->getSetterMethodDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001512 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001513 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001514
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001515 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001516
Adrian Prantlce7d3592019-12-05 12:26:16 -08001517 FinishFunction(OMD->getEndLoc());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001518}
1519
John McCall6a4fa522011-03-22 07:05:39 +00001520namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001521 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001522 private:
1523 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001524 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001525 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001526 bool useEHCleanupForArray;
1527 public:
1528 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1529 CodeGenFunction::Destroyer *destroyer,
1530 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001531 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001532 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001533
Craig Topper4f12f102014-03-12 06:41:41 +00001534 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001535 LValue lvalue
1536 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001537 CGF.emitDestroy(lvalue.getAddress(CGF), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001538 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001539 }
1540 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001541}
John McCall6a4fa522011-03-22 07:05:39 +00001542
John McCall4bd0fb12011-07-12 16:41:08 +00001543/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1544static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001545 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001546 QualType type) {
1547 llvm::Value *null = getNullForVariable(addr);
1548 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1549}
John McCall31168b02011-06-15 23:02:42 +00001550
John McCall6a4fa522011-03-22 07:05:39 +00001551static void emitCXXDestructMethod(CodeGenFunction &CGF,
1552 ObjCImplementationDecl *impl) {
1553 CodeGenFunction::RunCleanupsScope scope(CGF);
1554
1555 llvm::Value *self = CGF.LoadObjCSelf();
1556
Jordy Rosea91768e2011-07-22 02:08:32 +00001557 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1558 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001559 ivar; ivar = ivar->getNextIvar()) {
1560 QualType type = ivar->getType();
1561
John McCall6a4fa522011-03-22 07:05:39 +00001562 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001563 QualType::DestructionKind dtorKind = type.isDestructedType();
1564 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001565
Craig Topper8a13c412014-05-21 05:09:00 +00001566 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001567
John McCall4bd0fb12011-07-12 16:41:08 +00001568 // Use a call to objc_storeStrong to destroy strong ivars, for the
1569 // general benefit of the tools.
1570 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001571 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001572
John McCall4bd0fb12011-07-12 16:41:08 +00001573 // Otherwise use the default for the destruction kind.
1574 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001575 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001576 }
John McCall4bd0fb12011-07-12 16:41:08 +00001577
1578 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1579
1580 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1581 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001582 }
1583
1584 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1585}
1586
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001587void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1588 ObjCMethodDecl *MD,
1589 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001590 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001591 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001592
1593 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001594 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001595 // Suppress the final autorelease in ARC.
1596 AutoreleaseResult = false;
1597
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001598 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001599 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001600 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001601 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001602 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001603 EmitAggExpr(IvarInit->getInit(),
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001604 AggValueSlot::forLValue(LV, *this, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001605 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001606 AggValueSlot::IsNotAliased,
1607 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001608 }
1609 // constructor returns 'self'.
1610 CodeGenTypes &Types = CGM.getTypes();
1611 QualType IdTy(CGM.getContext().getObjCIdType());
1612 llvm::Value *SelfAsId =
1613 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1614 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001615
1616 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001617 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001618 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001619 }
1620 FinishFunction();
1621}
1622
Daniel Dunbara08dff12008-09-24 04:04:31 +00001623llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001624 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001625 DeclRefExpr DRE(getContext(), Self,
1626 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001627 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001628 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001629}
1630
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001631QualType CodeGenFunction::TypeOfSelfObject() {
1632 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1633 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001634 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1635 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001636 return PTy->getPointeeType();
1637}
1638
Chris Lattnerd4808922009-03-22 21:03:39 +00001639void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
James Y Knight9871db02019-02-05 16:42:33 +00001640 llvm::FunctionCallee EnumerationMutationFnPtr =
1641 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001642 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001643 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1644 return;
1645 }
John McCallb92ab1a2016-10-26 23:46:34 +00001646 CGCallee EnumerationMutationFn =
1647 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001648
Devang Pateld2d66652011-01-19 01:36:36 +00001649 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001650 if (DI)
1651 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001652
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001653 RunCleanupsScope ForScope(*this);
1654
Kuba Mracek82c21752017-04-14 01:00:03 +00001655 // The local variable comes into scope immediately.
1656 AutoVarEmission variable = AutoVarEmission::invalid();
1657 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1658 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1659
John McCall1c926b72011-01-07 01:49:06 +00001660 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001661
Anders Carlsson75658592008-08-31 02:33:12 +00001662 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001663 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001664 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001665 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001666
Anders Carlsson75658592008-08-31 02:33:12 +00001667 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001668 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001669
John McCall1c926b72011-01-07 01:49:06 +00001670 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001671 IdentifierInfo *II[] = {
1672 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1673 &CGM.getContext().Idents.get("objects"),
1674 &CGM.getContext().Idents.get("count")
1675 };
1676 Selector FastEnumSel =
1677 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001678
1679 QualType ItemsTy =
1680 getContext().getConstantArrayType(getContext().getObjCIdType(),
Richard Smith772e2662019-10-04 01:25:59 +00001681 llvm::APInt(32, NumItems), nullptr,
Anders Carlsson75658592008-08-31 02:33:12 +00001682 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001683 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001684
John McCall53848232011-07-27 01:07:15 +00001685 // Emit the collection pointer. In ARC, we do a retain.
1686 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001687 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001688 Collection = EmitARCRetainScalarExpr(S.getCollection());
1689
1690 // Enter a cleanup to do the release.
1691 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1692 } else {
1693 Collection = EmitScalarExpr(S.getCollection());
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCall91e82dd2011-08-05 00:14:38 +00001696 // The 'continue' label needs to appear within the cleanup for the
1697 // collection object.
1698 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1699
John McCall1c926b72011-01-07 01:49:06 +00001700 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001701 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001702
1703 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001704 Args.add(RValue::get(StatePtr.getPointer()),
1705 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall1c926b72011-01-07 01:49:06 +00001707 // The second argument is a temporary array with space for NumItems
1708 // pointers. We'll actually be loading elements from the array
1709 // pointer written into the control state; this buffer is so that
1710 // collections that *aren't* backed by arrays can still queue up
1711 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001712 Args.add(RValue::get(ItemsPtr.getPointer()),
1713 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001714
John McCall1c926b72011-01-07 01:49:06 +00001715 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001716 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1717 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1718 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001719
John McCall1c926b72011-01-07 01:49:06 +00001720 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001721 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001722 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1723 getContext().getNSUIntegerType(),
1724 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001725
John McCall1c926b72011-01-07 01:49:06 +00001726 // The initial number of objects that were returned in the buffer.
1727 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001728
John McCall1c926b72011-01-07 01:49:06 +00001729 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1730 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001731
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001732 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001733
John McCall1c926b72011-01-07 01:49:06 +00001734 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001735 // empty; skip all this. Set the branch weight assuming this has the same
1736 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001737 uint64_t EntryCount = getCurrentProfileCount();
1738 Builder.CreateCondBr(
1739 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1740 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001741 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001742
John McCall1c926b72011-01-07 01:49:06 +00001743 // Otherwise, initialize the loop.
1744 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001745
John McCall1c926b72011-01-07 01:49:06 +00001746 // Save the initial mutations value. This is the value at an
1747 // address that was written into the state object by
1748 // countByEnumeratingWithState:objects:count:.
James Y Knight751fe282019-02-09 22:22:28 +00001749 Address StateMutationsPtrPtr =
1750 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001751 llvm::Value *StateMutationsPtr
1752 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001753
John McCall1c926b72011-01-07 01:49:06 +00001754 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001755 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1756 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001757
John McCall1c926b72011-01-07 01:49:06 +00001758 // Start looping. This is the point we return to whenever we have a
1759 // fresh, non-empty batch of objects.
1760 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1761 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001762
John McCall1c926b72011-01-07 01:49:06 +00001763 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001764 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001765 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001766
John McCall1c926b72011-01-07 01:49:06 +00001767 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001768 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001769 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001770
Justin Bogner66242d62015-04-23 23:06:47 +00001771 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001772
John McCall1c926b72011-01-07 01:49:06 +00001773 // Check whether the mutations value has changed from where it was
1774 // at start. StateMutationsPtr should actually be invariant between
1775 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001776 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001777 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001778 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1779 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001780
John McCall1c926b72011-01-07 01:49:06 +00001781 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001782 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001783
John McCall1c926b72011-01-07 01:49:06 +00001784 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1785 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001786
John McCall1c926b72011-01-07 01:49:06 +00001787 // If so, call the enumeration-mutation function.
1788 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001789 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001790 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001791 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001792 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001793 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001794 // FIXME: We shouldn't need to get the function info here, the runtime already
1795 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001796 EmitCall(
1797 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001798 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001799
John McCall1c926b72011-01-07 01:49:06 +00001800 // Otherwise, or if the mutation function returns, just continue.
1801 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001802
John McCall1c926b72011-01-07 01:49:06 +00001803 // Initialize the element variable.
1804 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001805 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001806 LValue elementLValue;
1807 QualType elementType;
1808 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001809 // Initialize the variable, in case it's a __block variable or something.
1810 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001811
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001812 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1813 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1814 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001815 elementLValue = EmitLValue(&tempDRE);
1816 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001817 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001818
1819 if (D->isARCPseudoStrong())
1820 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001821 } else {
1822 elementLValue = LValue(); // suppress warning
1823 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001824 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001825 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001826 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001827
1828 // Fetch the buffer out of the enumeration state.
1829 // TODO: this pointer should actually be invariant between
1830 // refreshes, which would help us do certain loop optimizations.
James Y Knight751fe282019-02-09 22:22:28 +00001831 Address StateItemsPtr =
1832 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001833 llvm::Value *EnumStateItems =
1834 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001835
John McCall1c926b72011-01-07 01:49:06 +00001836 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001837 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001838 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001839 llvm::Value *CurrentItem =
1840 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001841
John McCall1c926b72011-01-07 01:49:06 +00001842 // Cast that value to the right type.
1843 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1844 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001845
John McCall1c926b72011-01-07 01:49:06 +00001846 // Make sure we have an l-value. Yes, this gets evaluated every
1847 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001848 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001849 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001850 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001851 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001852 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1853 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
John McCall9e2e22f2011-02-22 07:16:58 +00001856 // If we do have an element variable, this assignment is the end of
1857 // its initialization.
1858 if (elementIsVariable)
1859 EmitAutoVarCleanups(variable);
1860
John McCall1c926b72011-01-07 01:49:06 +00001861 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001862 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001863 {
1864 RunCleanupsScope Scope(*this);
1865 EmitStmt(S.getBody());
1866 }
Anders Carlsson75658592008-08-31 02:33:12 +00001867 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001868
John McCall1c926b72011-01-07 01:49:06 +00001869 // Destroy the element variable now.
1870 elementVariableScope.ForceCleanup();
1871
1872 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001873 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001874
John McCall1c926b72011-01-07 01:49:06 +00001875 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001876
John McCall1c926b72011-01-07 01:49:06 +00001877 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001878 llvm::Value *indexPlusOne =
1879 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001880
John McCall1c926b72011-01-07 01:49:06 +00001881 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001882 // Set the branch weights based on the simplifying assumption that this is
1883 // like a while-loop, i.e., ignoring that the false branch fetches more
1884 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001885 Builder.CreateCondBr(
1886 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001887 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001888
1889 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1890 count->addIncoming(count, AfterBody.getBlock());
1891
1892 // Otherwise, we have to fetch more elements.
1893 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001894
1895 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001896 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1897 getContext().getNSUIntegerType(),
1898 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCall1c926b72011-01-07 01:49:06 +00001900 // If we got a zero count, we're done.
1901 llvm::Value *refetchCount = CountRV.getScalarVal();
1902
1903 // (note that the message send might split FetchMoreBB)
1904 index->addIncoming(zero, Builder.GetInsertBlock());
1905 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1906
1907 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1908 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001909
Anders Carlsson75658592008-08-31 02:33:12 +00001910 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001911 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001912
John McCall9e2e22f2011-02-22 07:16:58 +00001913 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001914 // If the element was not a declaration, set it to be null.
1915
John McCall1c926b72011-01-07 01:49:06 +00001916 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1917 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001918 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001919 }
1920
Eric Christopher7cdf9482011-10-13 21:45:18 +00001921 if (DI)
1922 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001923
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001924 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001925 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001926}
1927
Mike Stump11289f42009-09-09 15:08:12 +00001928void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001929 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001930}
1931
Mike Stump11289f42009-09-09 15:08:12 +00001932void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001933 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1934}
1935
Chris Lattnere132e242008-11-15 21:26:17 +00001936void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001937 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001938 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001939}
1940
John McCall31168b02011-06-15 23:02:42 +00001941namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001942 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001943 CallObjCRelease(llvm::Value *object) : object(object) {}
1944 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001945
Craig Topper4f12f102014-03-12 06:41:41 +00001946 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001947 // Releases at the end of the full-expression are imprecise.
1948 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001949 }
1950 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001951}
John McCall31168b02011-06-15 23:02:42 +00001952
John McCall2d637d22011-09-10 06:18:15 +00001953/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001954/// release at the end of the full-expression.
1955llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1956 llvm::Value *object) {
1957 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001958 // conditional.
1959 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001960 return object;
1961}
1962
1963llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1964 llvm::Value *value) {
1965 return EmitARCRetainAutorelease(type, value);
1966}
1967
John McCalleff18842013-03-23 02:35:54 +00001968/// Given a number of pointers, inform the optimizer that they're
1969/// being intrinsically used up until this point in the program.
1970void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
James Y Knight9871db02019-02-05 16:42:33 +00001971 llvm::Function *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001972 if (!fn)
1973 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001974
1975 // This isn't really a "runtime" function, but as an intrinsic it
1976 // doesn't really matter as long as we align things up.
1977 EmitNounwindRuntimeCall(fn, values);
1978}
1979
James Y Knight9871db02019-02-05 16:42:33 +00001980static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM, llvm::Value *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001981 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001982 // If the target runtime doesn't naturally support ARC, emit weak
1983 // references to the runtime support library. We don't really
1984 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001985 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1986 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001987 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001988 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001989 }
John McCall31168b02011-06-15 23:02:42 +00001990}
1991
James Y Knight9871db02019-02-05 16:42:33 +00001992static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1993 llvm::FunctionCallee RTF) {
1994 setARCRuntimeFunctionLinkage(CGM, RTF.getCallee());
1995}
1996
John McCall31168b02011-06-15 23:02:42 +00001997/// Perform an operation having the signature
1998/// i8* (i8*)
1999/// where a null input causes a no-op and returns null.
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002000static llvm::Value *emitARCValueOperation(
2001 CodeGenFunction &CGF, llvm::Value *value, llvm::Type *returnType,
2002 llvm::Function *&fn, llvm::Intrinsic::ID IntID,
2003 llvm::CallInst::TailCallKind tailKind = llvm::CallInst::TCK_None) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00002004 if (isa<llvm::ConstantPointerNull>(value))
2005 return value;
John McCall31168b02011-06-15 23:02:42 +00002006
2007 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002008 fn = CGF.CGM.getIntrinsic(IntID);
2009 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002010 }
2011
2012 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00002013 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00002014 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2015
2016 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00002017 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002018 call->setTailCallKind(tailKind);
John McCall31168b02011-06-15 23:02:42 +00002019
2020 // Cast the result back to the original type.
2021 return CGF.Builder.CreateBitCast(call, origType);
2022}
2023
2024/// Perform an operation having the following signature:
2025/// i8* (i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002026static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF, Address addr,
2027 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002028 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00002029 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002030 fn = CGF.CGM.getIntrinsic(IntID);
2031 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002032 }
2033
2034 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00002035 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00002036 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
2037
2038 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00002039 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002040
2041 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00002042 if (origType != CGF.Int8PtrTy)
2043 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00002044
2045 return result;
2046}
2047
2048/// Perform an operation having the following signature:
2049/// i8* (i8**, i8*)
James Y Knight9871db02019-02-05 16:42:33 +00002050static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF, Address addr,
John McCall31168b02011-06-15 23:02:42 +00002051 llvm::Value *value,
James Y Knight9871db02019-02-05 16:42:33 +00002052 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002053 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00002054 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002055 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002056
2057 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002058 fn = CGF.CGM.getIntrinsic(IntID);
2059 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002060 }
2061
Chris Lattner2192fe52011-07-18 04:24:23 +00002062 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002063
John McCall882987f2013-02-28 19:01:20 +00002064 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002065 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002066 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
2067 };
2068 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002069
Craig Topper8a13c412014-05-21 05:09:00 +00002070 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002071
2072 return CGF.Builder.CreateBitCast(result, origType);
2073}
2074
2075/// Perform an operation having the following signature:
2076/// void (i8**, i8**)
James Y Knight9871db02019-02-05 16:42:33 +00002077static void emitARCCopyOperation(CodeGenFunction &CGF, Address dst, Address src,
2078 llvm::Function *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002079 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002080 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002081
2082 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002083 fn = CGF.CGM.getIntrinsic(IntID);
2084 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002085 }
2086
John McCall882987f2013-02-28 19:01:20 +00002087 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002088 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2089 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002090 };
2091 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002092}
2093
Pete Cooper2cd35962018-12-18 20:33:00 +00002094/// Perform an operation having the signature
2095/// i8* (i8*)
2096/// where a null input causes a no-op and returns null.
2097static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2098 llvm::Value *value,
2099 llvm::Type *returnType,
James Y Knight9871db02019-02-05 16:42:33 +00002100 llvm::FunctionCallee &fn,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002101 StringRef fnName) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002102 if (isa<llvm::ConstantPointerNull>(value))
2103 return value;
2104
2105 if (!fn) {
2106 llvm::FunctionType *fnType =
2107 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2108 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002109
2110 // We have Native ARC, so set nonlazybind attribute for performance
James Y Knight9871db02019-02-05 16:42:33 +00002111 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
Pete Coopere5b64ea2018-12-21 21:00:32 +00002112 if (fnName == "objc_retain")
2113 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002114 }
2115
2116 // Cast the argument to 'id'.
2117 llvm::Type *origType = returnType ? returnType : value->getType();
2118 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2119
2120 // Call the function.
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002121 llvm::CallBase *Inst = CGF.EmitCallOrInvoke(fn, value);
Pete Cooper2cd35962018-12-18 20:33:00 +00002122
2123 // Cast the result back to the original type.
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002124 return CGF.Builder.CreateBitCast(Inst, origType);
Pete Cooper2cd35962018-12-18 20:33:00 +00002125}
2126
John McCall31168b02011-06-15 23:02:42 +00002127/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002128/// call i8* \@objc_retain(i8* %value)
2129/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002130llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2131 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002132 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002133 else
2134 return EmitARCRetainNonBlock(value);
2135}
2136
2137/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002138/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002139llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002140 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002141 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002142 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002143}
2144
2145/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002146/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002147///
2148/// \param mandatory - If false, emit the call with metadata
2149/// indicating that it's okay for the optimizer to eliminate this call
2150/// if it can prove that the block never escapes except down the stack.
2151llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2152 bool mandatory) {
2153 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002154 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002155 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002156 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002157
2158 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2159 // tell the optimizer that it doesn't need to do this copy if the
2160 // block doesn't escape, where being passed as an argument doesn't
2161 // count as escaping.
2162 if (!mandatory && isa<llvm::Instruction>(result)) {
2163 llvm::CallInst *call
2164 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002165 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002166
John McCallff613032011-10-04 06:23:45 +00002167 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002168 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002169 }
2170
2171 return result;
John McCall31168b02011-06-15 23:02:42 +00002172}
2173
John McCalle399e5b2016-01-27 18:32:30 +00002174static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002175 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002176 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002177 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002178 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002179 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002180 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002181 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002182 .getARCRetainAutoreleasedReturnValueMarker();
2183
2184 // If we have an empty assembly string, there's nothing to do.
2185 if (assembly.empty()) {
2186
2187 // Otherwise, at -O0, build an inline asm that we're going to call
2188 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002189 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002190 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002191 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002192
John McCall31168b02011-06-15 23:02:42 +00002193 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2194
2195 // If we're at -O1 and above, we don't want to litter the code
2196 // with this marker yet, so leave a breadcrumb for the ARC
2197 // optimizer to pick up.
2198 } else {
Akira Hatanaka60c3a3b2019-04-10 06:20:23 +00002199 const char *markerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
2200 if (!CGF.CGM.getModule().getModuleFlag(markerKey)) {
2201 auto *str = llvm::MDString::get(CGF.getLLVMContext(), assembly);
2202 CGF.CGM.getModule().addModuleFlag(llvm::Module::Error, markerKey, str);
John McCall31168b02011-06-15 23:02:42 +00002203 }
2204 }
2205 }
2206
2207 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002208 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002209 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002210}
John McCall31168b02011-06-15 23:02:42 +00002211
John McCalle399e5b2016-01-27 18:32:30 +00002212/// Retain the given object which is the result of a function call.
2213/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2214///
2215/// Yes, this function name is one character away from a different
2216/// call with completely different semantics.
2217llvm::Value *
2218CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2219 emitAutoreleasedReturnValueMarker(*this);
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002220 llvm::CallInst::TailCallKind tailKind =
2221 CGM.getTargetCodeGenInfo()
2222 .shouldSuppressTailCallsOfRetainAutoreleasedReturnValue()
2223 ? llvm::CallInst::TCK_NoTail
2224 : llvm::CallInst::TCK_None;
2225 return emitARCValueOperation(
2226 *this, value, nullptr,
2227 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
2228 llvm::Intrinsic::objc_retainAutoreleasedReturnValue, tailKind);
John McCall31168b02011-06-15 23:02:42 +00002229}
2230
John McCalle399e5b2016-01-27 18:32:30 +00002231/// Claim a possibly-autoreleased return value at +0. This is only
2232/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002233/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002234/// the value is ignored, or when it is being assigned to an
2235/// __unsafe_unretained variable.
2236///
2237/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2238llvm::Value *
2239CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2240 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002241 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002242 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002243 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002244}
2245
John McCall31168b02011-06-15 23:02:42 +00002246/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002247/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002248void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2249 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002250 if (isa<llvm::ConstantPointerNull>(value)) return;
2251
James Y Knight9871db02019-02-05 16:42:33 +00002252 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002253 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002254 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2255 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002256 }
2257
2258 // Cast the argument to 'id'.
2259 value = Builder.CreateBitCast(value, Int8PtrTy);
2260
2261 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002262 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002263
John McCallcdda29c2013-03-13 03:10:54 +00002264 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002265 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002266 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002267 }
2268}
2269
John McCalle68b8f42012-10-17 02:28:37 +00002270/// Destroy a __strong variable.
2271///
2272/// At -O0, emit a call to store 'null' into the address;
2273/// instrumenting tools prefer this because the address is exposed,
2274/// but it's relatively cumbersome to optimize.
2275///
2276/// At -O1 and above, just load and call objc_release.
2277///
2278/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002279void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002280 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002281 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002282 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002283 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2284 return;
2285 }
2286
2287 llvm::Value *value = Builder.CreateLoad(addr);
2288 EmitARCRelease(value, precise);
2289}
2290
John McCall31168b02011-06-15 23:02:42 +00002291/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002292/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002293llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002294 llvm::Value *value,
2295 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002296 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002297
James Y Knight9871db02019-02-05 16:42:33 +00002298 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002299 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002300 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2301 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002302 }
2303
John McCall882987f2013-02-28 19:01:20 +00002304 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002305 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002306 Builder.CreateBitCast(value, Int8PtrTy)
2307 };
2308 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002309
Craig Topper8a13c412014-05-21 05:09:00 +00002310 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002311 return value;
2312}
2313
2314/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002315/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002316/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002317llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002318 llvm::Value *newValue,
2319 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002320 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002321 bool isBlock = type->isBlockPointerType();
2322
2323 // Use a store barrier at -O0 unless this is a block type or the
2324 // lvalue is inadequately aligned.
2325 if (shouldUseFusedARCCalls() &&
2326 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002327 (dst.getAlignment().isZero() ||
2328 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002329 return EmitARCStoreStrongCall(dst.getAddress(*this), newValue, ignored);
John McCall31168b02011-06-15 23:02:42 +00002330 }
2331
2332 // Otherwise, split it out.
2333
2334 // Retain the new value.
2335 newValue = EmitARCRetain(type, newValue);
2336
2337 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002338 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002339
2340 // Store. We do this before the release so that any deallocs won't
2341 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002342 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002343
2344 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002345 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002346
2347 return newValue;
2348}
2349
2350/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002351/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002352llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002353 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002354 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002355 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002356}
2357
2358/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002359/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002360llvm::Value *
2361CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002362 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002363 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002364 llvm::Intrinsic::objc_autoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002365 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002366}
2367
2368/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002369/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002370llvm::Value *
2371CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002372 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002373 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002374 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Akira Hatanaka65bb3f92019-03-21 19:59:49 +00002375 llvm::CallInst::TCK_Tail);
John McCall31168b02011-06-15 23:02:42 +00002376}
2377
2378/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002379/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002380/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002381/// %retain = call i8* \@objc_retainBlock(i8* %value)
2382/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002383llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2384 llvm::Value *value) {
2385 if (!type->isBlockPointerType())
2386 return EmitARCRetainAutoreleaseNonBlock(value);
2387
2388 if (isa<llvm::ConstantPointerNull>(value)) return value;
2389
Chris Lattner2192fe52011-07-18 04:24:23 +00002390 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002391 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002392 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002393 value = EmitARCAutorelease(value);
2394 return Builder.CreateBitCast(value, origType);
2395}
2396
2397/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002398/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002399llvm::Value *
2400CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002401 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002402 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002403 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002404}
2405
John McCallb04ecb72015-10-21 18:06:43 +00002406/// i8* \@objc_loadWeak(i8** %addr)
2407/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2408llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2409 return emitARCLoadOperation(*this, addr,
2410 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002411 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002412}
2413
James Dennett14c41ea2012-06-22 05:41:30 +00002414/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002415llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002416 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002417 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002418 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002419}
2420
James Dennett14c41ea2012-06-22 05:41:30 +00002421/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002422/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002423llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002424 llvm::Value *value,
2425 bool ignored) {
2426 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002427 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002428 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002429}
2430
James Dennett14c41ea2012-06-22 05:41:30 +00002431/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002432/// Returns %value. %addr is known to not have a current weak entry.
2433/// Essentially equivalent to:
2434/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002435void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002436 // If we're initializing to null, just write null to memory; no need
2437 // to get the runtime involved. But don't do this if optimization
2438 // is enabled, because accounting for this would make the optimizer
2439 // much more complicated.
2440 if (isa<llvm::ConstantPointerNull>(value) &&
2441 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2442 Builder.CreateStore(value, addr);
2443 return;
2444 }
2445
2446 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002447 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002448 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002449}
2450
James Dennett14c41ea2012-06-22 05:41:30 +00002451/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002452/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002453void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
James Y Knight9871db02019-02-05 16:42:33 +00002454 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002455 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002456 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2457 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002458 }
2459
2460 // Cast the argument to 'id*'.
2461 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2462
John McCall7f416cc2015-09-08 08:05:57 +00002463 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002464}
2465
James Dennett14c41ea2012-06-22 05:41:30 +00002466/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002467/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2468/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002469void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002470 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002471 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002472 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002473}
2474
James Dennett14c41ea2012-06-22 05:41:30 +00002475/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002476/// Disregards the current value in %dest. Essentially
2477/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002478void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002479 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002480 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002481 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002482}
2483
Akira Hatanakad791e922018-03-19 17:38:40 +00002484void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2485 Address SrcAddr) {
2486 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2487 Object = EmitObjCConsumeObject(Ty, Object);
2488 EmitARCStoreWeak(DstAddr, Object, false);
2489}
2490
2491void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2492 Address SrcAddr) {
2493 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2494 Object = EmitObjCConsumeObject(Ty, Object);
2495 EmitARCStoreWeak(DstAddr, Object, false);
2496 EmitARCDestroyWeak(SrcAddr);
2497}
2498
John McCall31168b02011-06-15 23:02:42 +00002499/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002500/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002501llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
James Y Knight9871db02019-02-05 16:42:33 +00002502 llvm::Function *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002503 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002504 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2505 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002506 }
2507
John McCall882987f2013-02-28 19:01:20 +00002508 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002509}
2510
2511/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002512/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002513void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2514 assert(value->getType() == Int8PtrTy);
2515
Pete Cooper2cd35962018-12-18 20:33:00 +00002516 if (getInvokeDest()) {
2517 // Call the runtime method not the intrinsic if we are handling exceptions
James Y Knight9871db02019-02-05 16:42:33 +00002518 llvm::FunctionCallee &fn =
2519 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
Pete Cooper2cd35962018-12-18 20:33:00 +00002520 if (!fn) {
2521 llvm::FunctionType *fnType =
2522 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2523 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2524 setARCRuntimeFunctionLinkage(CGM, fn);
2525 }
John McCall31168b02011-06-15 23:02:42 +00002526
Pete Cooper2cd35962018-12-18 20:33:00 +00002527 // objc_autoreleasePoolPop can throw.
2528 EmitRuntimeCallOrInvoke(fn, value);
2529 } else {
James Y Knight9871db02019-02-05 16:42:33 +00002530 llvm::FunctionCallee &fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
Pete Cooper2cd35962018-12-18 20:33:00 +00002531 if (!fn) {
2532 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2533 setARCRuntimeFunctionLinkage(CGM, fn);
2534 }
2535
2536 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002537 }
John McCall31168b02011-06-15 23:02:42 +00002538}
2539
2540/// Produce the code to do an MRR version objc_autoreleasepool_push.
2541/// Which is: [[NSAutoreleasePool alloc] init];
2542/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2543/// init is declared as: - (id) init; in its NSObject super class.
2544///
2545llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2546 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002547 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002548 // [NSAutoreleasePool alloc]
2549 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2550 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2551 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002552 RValue AllocRV =
2553 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002554 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002555 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002556
2557 // [Receiver init]
2558 Receiver = AllocRV.getScalarVal();
2559 II = &CGM.getContext().Idents.get("init");
2560 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2561 RValue InitRV =
2562 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2563 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002564 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002565 return InitRV.getScalarVal();
2566}
2567
Pete Coopere3886802018-12-08 05:13:50 +00002568/// Allocate the given objc object.
2569/// call i8* \@objc_alloc(i8* %value)
2570llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2571 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002572 return emitObjCValueOperation(*this, value, resultType,
2573 CGM.getObjCEntrypoints().objc_alloc,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002574 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002575}
2576
2577/// Allocate the given objc object.
2578/// call i8* \@objc_allocWithZone(i8* %value)
2579llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2580 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002581 return emitObjCValueOperation(*this, value, resultType,
2582 CGM.getObjCEntrypoints().objc_allocWithZone,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002583 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002584}
2585
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002586llvm::Value *CodeGenFunction::EmitObjCAllocInit(llvm::Value *value,
2587 llvm::Type *resultType) {
2588 return emitObjCValueOperation(*this, value, resultType,
2589 CGM.getObjCEntrypoints().objc_alloc_init,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002590 "objc_alloc_init");
Erik Pilkingtonec389b02019-02-14 19:58:37 +00002591}
2592
John McCall31168b02011-06-15 23:02:42 +00002593/// Produce the code to do a primitive release.
2594/// [tmp drain];
2595void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2596 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2597 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2598 CallArgList Args;
2599 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002600 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002601}
2602
John McCall82fe67b2011-07-09 01:37:26 +00002603void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002604 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002605 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002606 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002607}
2608
2609void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002610 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002611 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002612 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002613}
2614
2615void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002616 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002617 QualType type) {
2618 CGF.EmitARCDestroyWeak(addr);
2619}
2620
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002621void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2622 QualType type) {
2623 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2624 CGF.EmitARCIntrinsicUse(value);
2625}
2626
Pete Coopere5b64ea2018-12-21 21:00:32 +00002627/// Autorelease the given object.
2628/// call i8* \@objc_autorelease(i8* %value)
2629llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2630 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002631 return emitObjCValueOperation(
2632 *this, value, returnType,
2633 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002634 "objc_autorelease");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002635}
2636
2637/// Retain the given object, with normal retain semantics.
2638/// call i8* \@objc_retain(i8* %value)
2639llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2640 llvm::Type *returnType) {
Erik Pilkington1f7eda52019-01-30 23:17:38 +00002641 return emitObjCValueOperation(
2642 *this, value, returnType,
Erik Pilkingtonf6c645f2019-05-15 20:15:01 +00002643 CGM.getObjCEntrypoints().objc_retainRuntimeFunction, "objc_retain");
Pete Coopere5b64ea2018-12-21 21:00:32 +00002644}
2645
2646/// Release the given object.
2647/// call void \@objc_release(i8* %value)
2648void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2649 ARCPreciseLifetime_t precise) {
2650 if (isa<llvm::ConstantPointerNull>(value)) return;
2651
James Y Knight9871db02019-02-05 16:42:33 +00002652 llvm::FunctionCallee &fn =
2653 CGM.getObjCEntrypoints().objc_releaseRuntimeFunction;
Pete Coopere5b64ea2018-12-21 21:00:32 +00002654 if (!fn) {
James Y Knight9871db02019-02-05 16:42:33 +00002655 llvm::FunctionType *fnType =
Pete Coopere5b64ea2018-12-21 21:00:32 +00002656 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
James Y Knight9871db02019-02-05 16:42:33 +00002657 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2658 setARCRuntimeFunctionLinkage(CGM, fn);
2659 // We have Native ARC, so set nonlazybind attribute for performance
2660 if (llvm::Function *f = dyn_cast<llvm::Function>(fn.getCallee()))
2661 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002662 }
2663
2664 // Cast the argument to 'id'.
2665 value = Builder.CreateBitCast(value, Int8PtrTy);
2666
2667 // Call objc_release.
Akira Hatanaka34d28cf2019-05-10 21:54:16 +00002668 llvm::CallBase *call = EmitCallOrInvoke(fn, value);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002669
2670 if (precise == ARCImpreciseLifetime) {
2671 call->setMetadata("clang.imprecise_release",
2672 llvm::MDNode::get(Builder.getContext(), None));
2673 }
2674}
2675
John McCall31168b02011-06-15 23:02:42 +00002676namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002677 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002678 llvm::Value *Token;
2679
2680 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2681
Craig Topper4f12f102014-03-12 06:41:41 +00002682 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002683 CGF.EmitObjCAutoreleasePoolPop(Token);
2684 }
2685 };
David Blaikie7e70d682015-08-18 22:40:54 +00002686 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002687 llvm::Value *Token;
2688
2689 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2690
Craig Topper4f12f102014-03-12 06:41:41 +00002691 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002692 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2693 }
2694 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002695}
John McCall31168b02011-06-15 23:02:42 +00002696
2697void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002698 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002699 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2700 else
2701 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2702}
2703
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002704static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2705 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002706 case Qualifiers::OCL_None:
2707 case Qualifiers::OCL_ExplicitNone:
2708 case Qualifiers::OCL_Strong:
2709 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002710 return true;
John McCall31168b02011-06-15 23:02:42 +00002711
2712 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002713 return false;
John McCall31168b02011-06-15 23:02:42 +00002714 }
2715
2716 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002717}
2718
2719static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002720 LValue lvalue,
2721 QualType type) {
2722 llvm::Value *result;
2723 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2724 if (shouldRetain) {
2725 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2726 } else {
2727 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002728 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress(CGF));
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002729 }
2730 return TryEmitResult(result, !shouldRetain);
2731}
2732
2733static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002734 const Expr *e) {
2735 e = e->IgnoreParens();
2736 QualType type = e->getType();
2737
Fangrui Song6907ce22018-07-30 19:24:48 +00002738 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002739 // an extra retain/release pair by zeroing out the source of this
2740 // "move" operation.
2741 if (e->isXValue() &&
2742 !type.isConstQualified() &&
2743 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2744 // Emit the lvalue.
2745 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002746
John McCall154a2fd2011-08-30 00:57:29 +00002747 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002748 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2749 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002750
John McCall154a2fd2011-08-30 00:57:29 +00002751 // Set the source pointer to NULL.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002752 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress(CGF)), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002753
John McCall154a2fd2011-08-30 00:57:29 +00002754 return TryEmitResult(result, true);
2755 }
2756
John McCall31168b02011-06-15 23:02:42 +00002757 // As a very special optimization, in ARC++, if the l-value is the
2758 // result of a non-volatile assignment, do a simple retain of the
2759 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002760 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002761 !type.isVolatileQualified() &&
2762 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2763 isa<BinaryOperator>(e) &&
2764 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2765 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2766
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002767 // Try to emit code for scalar constant instead of emitting LValue and
2768 // loading it because we are not guaranteed to have an l-value. One of such
2769 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2770 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2771 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2772 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2773 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2774 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2775 }
2776
John McCall31168b02011-06-15 23:02:42 +00002777 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2778}
2779
John McCalle399e5b2016-01-27 18:32:30 +00002780typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2781 llvm::Value *value)>
2782 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002783
John McCalle399e5b2016-01-27 18:32:30 +00002784/// Insert code immediately after a call.
2785static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2786 llvm::Value *value,
2787 ValueTransform doAfterCall,
2788 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002789 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2790 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2791
2792 // Place the retain immediately following the call.
2793 CGF.Builder.SetInsertPoint(call->getParent(),
2794 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002795 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002796
2797 CGF.Builder.restoreIP(ip);
2798 return value;
2799 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2800 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2801
2802 // Place the retain at the beginning of the normal destination block.
2803 llvm::BasicBlock *BB = invoke->getNormalDest();
2804 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002805 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002806
2807 CGF.Builder.restoreIP(ip);
2808 return value;
2809
2810 // Bitcasts can arise because of related-result returns. Rewrite
2811 // the operand.
2812 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2813 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002814 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002815 bitcast->setOperand(0, operand);
2816 return bitcast;
2817
2818 // Generic fall-back case.
2819 } else {
2820 // Retain using the non-block variant: we never need to do a copy
2821 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002822 return doFallback(CGF, value);
2823 }
2824}
2825
2826/// Given that the given expression is some sort of call (which does
2827/// not return retained), emit a retain following it.
2828static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2829 const Expr *e) {
2830 llvm::Value *value = CGF.EmitScalarExpr(e);
2831 return emitARCOperationAfterCall(CGF, value,
2832 [](CodeGenFunction &CGF, llvm::Value *value) {
2833 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2834 },
2835 [](CodeGenFunction &CGF, llvm::Value *value) {
2836 return CGF.EmitARCRetainNonBlock(value);
2837 });
2838}
2839
2840/// Given that the given expression is some sort of call (which does
2841/// not return retained), perform an unsafeClaim following it.
2842static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2843 const Expr *e) {
2844 llvm::Value *value = CGF.EmitScalarExpr(e);
2845 return emitARCOperationAfterCall(CGF, value,
2846 [](CodeGenFunction &CGF, llvm::Value *value) {
2847 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2848 },
2849 [](CodeGenFunction &CGF, llvm::Value *value) {
2850 return value;
2851 });
2852}
2853
2854llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2855 bool allowUnsafeClaim) {
2856 if (allowUnsafeClaim &&
2857 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2858 return emitARCUnsafeClaimCallResult(*this, E);
2859 } else {
2860 llvm::Value *value = emitARCRetainCallResult(*this, E);
2861 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002862 }
2863}
2864
John McCallcd78e802011-09-10 01:16:55 +00002865/// Determine whether it might be important to emit a separate
2866/// objc_retain_block on the result of the given expression, or
2867/// whether it's okay to just emit it in a +1 context.
2868static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2869 assert(e->getType()->isBlockPointerType());
2870 e = e->IgnoreParens();
2871
2872 // For future goodness, emit block expressions directly in +1
2873 // contexts if we can.
2874 if (isa<BlockExpr>(e))
2875 return false;
2876
2877 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2878 switch (cast->getCastKind()) {
2879 // Emitting these operations in +1 contexts is goodness.
2880 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002881 case CK_ARCReclaimReturnedObject:
2882 case CK_ARCConsumeObject:
2883 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002884 return false;
2885
2886 // These operations preserve a block type.
2887 case CK_NoOp:
2888 case CK_BitCast:
2889 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2890
2891 // These operations are known to be bad (or haven't been considered).
2892 case CK_AnyPointerToBlockPointerCast:
2893 default:
2894 return true;
2895 }
2896 }
2897
2898 return true;
2899}
2900
John McCalle399e5b2016-01-27 18:32:30 +00002901namespace {
2902/// A CRTP base class for emitting expressions of retainable object
2903/// pointer type in ARC.
2904template <typename Impl, typename Result> class ARCExprEmitter {
2905protected:
2906 CodeGenFunction &CGF;
2907 Impl &asImpl() { return *static_cast<Impl*>(this); }
2908
2909 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2910
2911public:
2912 Result visit(const Expr *e);
2913 Result visitCastExpr(const CastExpr *e);
2914 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002915 Result visitBlockExpr(const BlockExpr *e);
John McCalle399e5b2016-01-27 18:32:30 +00002916 Result visitBinaryOperator(const BinaryOperator *e);
2917 Result visitBinAssign(const BinaryOperator *e);
2918 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2919 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2920 Result visitBinAssignWeak(const BinaryOperator *e);
2921 Result visitBinAssignStrong(const BinaryOperator *e);
2922
2923 // Minimal implementation:
2924 // Result visitLValueToRValue(const Expr *e)
2925 // Result visitConsumeObject(const Expr *e)
2926 // Result visitExtendBlockObject(const Expr *e)
2927 // Result visitReclaimReturnedObject(const Expr *e)
2928 // Result visitCall(const Expr *e)
2929 // Result visitExpr(const Expr *e)
2930 //
2931 // Result emitBitCast(Result result, llvm::Type *resultType)
2932 // llvm::Value *getValueOfResult(Result result)
2933};
2934}
2935
2936/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002937///
2938/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002939template <typename Impl, typename Result>
2940Result
2941ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002942 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002943
2944 // Find the result expression.
2945 const Expr *resultExpr = E->getResultExpr();
2946 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002947 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002948
2949 for (PseudoObjectExpr::const_semantics_iterator
2950 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2951 const Expr *semantic = *i;
2952
2953 // If this semantic expression is an opaque value, bind it
2954 // to the result of its source expression.
2955 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2956 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2957 OVMA opaqueData;
2958
2959 // If this semantic is the result of the pseudo-object
2960 // expression, try to evaluate the source as +1.
2961 if (ov == resultExpr) {
2962 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002963 result = asImpl().visit(ov->getSourceExpr());
2964 opaqueData = OVMA::bind(CGF, ov,
2965 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002966
2967 // Otherwise, just bind it.
2968 } else {
2969 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2970 }
2971 opaques.push_back(opaqueData);
2972
2973 // Otherwise, if the expression is the result, evaluate it
2974 // and remember the result.
2975 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002976 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002977
2978 // Otherwise, evaluate the expression in an ignored context.
2979 } else {
2980 CGF.EmitIgnoredExpr(semantic);
2981 }
2982 }
2983
2984 // Unbind all the opaques now.
2985 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2986 opaques[i].unbind(CGF);
2987
2988 return result;
2989}
2990
John McCalle399e5b2016-01-27 18:32:30 +00002991template <typename Impl, typename Result>
Akira Hatanakac5792aa2019-02-27 18:17:16 +00002992Result ARCExprEmitter<Impl, Result>::visitBlockExpr(const BlockExpr *e) {
2993 // The default implementation just forwards the expression to visitExpr.
2994 return asImpl().visitExpr(e);
2995}
2996
2997template <typename Impl, typename Result>
John McCalle399e5b2016-01-27 18:32:30 +00002998Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2999 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00003000
John McCalle399e5b2016-01-27 18:32:30 +00003001 // No-op casts don't change the type, so we just ignore them.
3002 case CK_NoOp:
3003 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00003004
John McCalle399e5b2016-01-27 18:32:30 +00003005 // These casts can change the type.
3006 case CK_CPointerToObjCPointerCast:
3007 case CK_BlockPointerToObjCPointerCast:
3008 case CK_AnyPointerToBlockPointerCast:
3009 case CK_BitCast: {
3010 llvm::Type *resultType = CGF.ConvertType(e->getType());
3011 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
3012 Result result = asImpl().visit(e->getSubExpr());
3013 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00003014 }
3015
John McCalle399e5b2016-01-27 18:32:30 +00003016 // Handle some casts specially.
3017 case CK_LValueToRValue:
3018 return asImpl().visitLValueToRValue(e->getSubExpr());
3019 case CK_ARCConsumeObject:
3020 return asImpl().visitConsumeObject(e->getSubExpr());
3021 case CK_ARCExtendBlockObject:
3022 return asImpl().visitExtendBlockObject(e->getSubExpr());
3023 case CK_ARCReclaimReturnedObject:
3024 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
3025
3026 // Otherwise, use the default logic.
3027 default:
3028 return asImpl().visitExpr(e);
3029 }
3030}
3031
3032template <typename Impl, typename Result>
3033Result
3034ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
3035 switch (e->getOpcode()) {
3036 case BO_Comma:
3037 CGF.EmitIgnoredExpr(e->getLHS());
3038 CGF.EnsureInsertPoint();
3039 return asImpl().visit(e->getRHS());
3040
3041 case BO_Assign:
3042 return asImpl().visitBinAssign(e);
3043
3044 default:
3045 return asImpl().visitExpr(e);
3046 }
3047}
3048
3049template <typename Impl, typename Result>
3050Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
3051 switch (e->getLHS()->getType().getObjCLifetime()) {
3052 case Qualifiers::OCL_ExplicitNone:
3053 return asImpl().visitBinAssignUnsafeUnretained(e);
3054
3055 case Qualifiers::OCL_Weak:
3056 return asImpl().visitBinAssignWeak(e);
3057
3058 case Qualifiers::OCL_Autoreleasing:
3059 return asImpl().visitBinAssignAutoreleasing(e);
3060
3061 case Qualifiers::OCL_Strong:
3062 return asImpl().visitBinAssignStrong(e);
3063
3064 case Qualifiers::OCL_None:
3065 return asImpl().visitExpr(e);
3066 }
3067 llvm_unreachable("bad ObjC ownership qualifier");
3068}
3069
3070/// The default rule for __unsafe_unretained emits the RHS recursively,
3071/// stores into the unsafe variable, and propagates the result outward.
3072template <typename Impl, typename Result>
3073Result ARCExprEmitter<Impl,Result>::
3074 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
3075 // Recursively emit the RHS.
3076 // For __block safety, do this before emitting the LHS.
3077 Result result = asImpl().visit(e->getRHS());
3078
3079 // Perform the store.
3080 LValue lvalue =
3081 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
3082 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
3083 lvalue);
3084
3085 return result;
3086}
3087
3088template <typename Impl, typename Result>
3089Result
3090ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3091 return asImpl().visitExpr(e);
3092}
3093
3094template <typename Impl, typename Result>
3095Result
3096ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3097 return asImpl().visitExpr(e);
3098}
3099
3100template <typename Impl, typename Result>
3101Result
3102ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3103 return asImpl().visitExpr(e);
3104}
3105
3106/// The general expression-emission logic.
3107template <typename Impl, typename Result>
3108Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3109 // We should *never* see a nested full-expression here, because if
3110 // we fail to emit at +1, our caller must not retain after we close
3111 // out the full-expression. This isn't as important in the unsafe
3112 // emitter.
3113 assert(!isa<ExprWithCleanups>(e));
3114
3115 // Look through parens, __extension__, generic selection, etc.
3116 e = e->IgnoreParens();
3117
3118 // Handle certain kinds of casts.
3119 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3120 return asImpl().visitCastExpr(ce);
3121
3122 // Handle the comma operator.
3123 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3124 return asImpl().visitBinaryOperator(op);
3125
3126 // TODO: handle conditional operators here
3127
3128 // For calls and message sends, use the retained-call logic.
3129 // Delegate inits are a special case in that they're the only
3130 // returns-retained expression that *isn't* surrounded by
3131 // a consume.
3132 } else if (isa<CallExpr>(e) ||
3133 (isa<ObjCMessageExpr>(e) &&
3134 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3135 return asImpl().visitCall(e);
3136
3137 // Look through pseudo-object expressions.
3138 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3139 return asImpl().visitPseudoObjectExpr(pseudo);
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003140 } else if (auto *be = dyn_cast<BlockExpr>(e))
3141 return asImpl().visitBlockExpr(be);
John McCalle399e5b2016-01-27 18:32:30 +00003142
3143 return asImpl().visitExpr(e);
3144}
3145
3146namespace {
3147
3148/// An emitter for +1 results.
3149struct ARCRetainExprEmitter :
3150 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3151
3152 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3153
3154 llvm::Value *getValueOfResult(TryEmitResult result) {
3155 return result.getPointer();
3156 }
3157
3158 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3159 llvm::Value *value = result.getPointer();
3160 value = CGF.Builder.CreateBitCast(value, resultType);
3161 result.setPointer(value);
3162 return result;
3163 }
3164
3165 TryEmitResult visitLValueToRValue(const Expr *e) {
3166 return tryEmitARCRetainLoadOfScalar(CGF, e);
3167 }
3168
3169 /// For consumptions, just emit the subexpression and thus elide
3170 /// the retain/release pair.
3171 TryEmitResult visitConsumeObject(const Expr *e) {
3172 llvm::Value *result = CGF.EmitScalarExpr(e);
3173 return TryEmitResult(result, true);
3174 }
3175
Akira Hatanakac5792aa2019-02-27 18:17:16 +00003176 TryEmitResult visitBlockExpr(const BlockExpr *e) {
3177 TryEmitResult result = visitExpr(e);
3178 // Avoid the block-retain if this is a block literal that doesn't need to be
3179 // copied to the heap.
3180 if (e->getBlockDecl()->canAvoidCopyToHeap())
3181 result.setInt(true);
3182 return result;
3183 }
3184
John McCalle399e5b2016-01-27 18:32:30 +00003185 /// Block extends are net +0. Naively, we could just recurse on
3186 /// the subexpression, but actually we need to ensure that the
3187 /// value is copied as a block, so there's a little filter here.
3188 TryEmitResult visitExtendBlockObject(const Expr *e) {
3189 llvm::Value *result; // will be a +0 value
3190
3191 // If we can't safely assume the sub-expression will produce a
3192 // block-copied value, emit the sub-expression at +0.
3193 if (shouldEmitSeparateBlockRetain(e)) {
3194 result = CGF.EmitScalarExpr(e);
3195
3196 // Otherwise, try to emit the sub-expression at +1 recursively.
3197 } else {
3198 TryEmitResult subresult = asImpl().visit(e);
3199
3200 // If that produced a retained value, just use that.
3201 if (subresult.getInt()) {
3202 return subresult;
3203 }
3204
3205 // Otherwise it's +0.
3206 result = subresult.getPointer();
3207 }
3208
3209 // Retain the object as a block.
3210 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3211 return TryEmitResult(result, true);
3212 }
3213
3214 /// For reclaims, emit the subexpression as a retained call and
3215 /// skip the consumption.
3216 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3217 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3218 return TryEmitResult(result, true);
3219 }
3220
3221 /// When we have an undecorated call, retroactively do a claim.
3222 TryEmitResult visitCall(const Expr *e) {
3223 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3224 return TryEmitResult(result, true);
3225 }
3226
3227 // TODO: maybe special-case visitBinAssignWeak?
3228
3229 TryEmitResult visitExpr(const Expr *e) {
3230 // We didn't find an obvious production, so emit what we've got and
3231 // tell the caller that we didn't manage to retain.
3232 llvm::Value *result = CGF.EmitScalarExpr(e);
3233 return TryEmitResult(result, false);
3234 }
3235};
3236}
3237
3238static TryEmitResult
3239tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3240 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003241}
3242
3243static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3244 LValue lvalue,
3245 QualType type) {
3246 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3247 llvm::Value *value = result.getPointer();
3248 if (!result.getInt())
3249 value = CGF.EmitARCRetain(type, value);
3250 return value;
3251}
3252
3253/// EmitARCRetainScalarExpr - Semantically equivalent to
3254/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3255/// best-effort attempt to peephole expressions that naturally produce
3256/// retained objects.
3257llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003258 // The retain needs to happen within the full-expression.
3259 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3260 enterFullExpression(cleanups);
3261 RunCleanupsScope scope(*this);
3262 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3263 }
3264
John McCall31168b02011-06-15 23:02:42 +00003265 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3266 llvm::Value *value = result.getPointer();
3267 if (!result.getInt())
3268 value = EmitARCRetain(e->getType(), value);
3269 return value;
3270}
3271
3272llvm::Value *
3273CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003274 // The retain needs to happen within the full-expression.
3275 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3276 enterFullExpression(cleanups);
3277 RunCleanupsScope scope(*this);
3278 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3279 }
3280
John McCall31168b02011-06-15 23:02:42 +00003281 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3282 llvm::Value *value = result.getPointer();
3283 if (result.getInt())
3284 value = EmitARCAutorelease(value);
3285 else
3286 value = EmitARCRetainAutorelease(e->getType(), value);
3287 return value;
3288}
3289
John McCallff613032011-10-04 06:23:45 +00003290llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3291 llvm::Value *result;
3292 bool doRetain;
3293
3294 if (shouldEmitSeparateBlockRetain(e)) {
3295 result = EmitScalarExpr(e);
3296 doRetain = true;
3297 } else {
3298 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3299 result = subresult.getPointer();
3300 doRetain = !subresult.getInt();
3301 }
3302
3303 if (doRetain)
3304 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3305 return EmitObjCConsumeObject(e->getType(), result);
3306}
3307
John McCall248512a2011-10-01 10:32:24 +00003308llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3309 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003310 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003311 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003312 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003313 return EmitARCRetainAutoreleaseScalarExpr(expr);
3314 }
3315
3316 // Otherwise, use the normal scalar-expression emission. The
3317 // exception machinery doesn't do anything special with the
3318 // exception like retaining it, so there's no safety associated with
3319 // only running cleanups after the throw has started, and when it
3320 // matters it tends to be substantially inferior code.
3321 return EmitScalarExpr(expr);
3322}
3323
John McCalle399e5b2016-01-27 18:32:30 +00003324namespace {
3325
3326/// An emitter for assigning into an __unsafe_unretained context.
3327struct ARCUnsafeUnretainedExprEmitter :
3328 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3329
3330 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3331
3332 llvm::Value *getValueOfResult(llvm::Value *value) {
3333 return value;
3334 }
3335
3336 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3337 return CGF.Builder.CreateBitCast(value, resultType);
3338 }
3339
3340 llvm::Value *visitLValueToRValue(const Expr *e) {
3341 return CGF.EmitScalarExpr(e);
3342 }
3343
3344 /// For consumptions, just emit the subexpression and perform the
3345 /// consumption like normal.
3346 llvm::Value *visitConsumeObject(const Expr *e) {
3347 llvm::Value *value = CGF.EmitScalarExpr(e);
3348 return CGF.EmitObjCConsumeObject(e->getType(), value);
3349 }
3350
3351 /// No special logic for block extensions. (This probably can't
3352 /// actually happen in this emitter, though.)
3353 llvm::Value *visitExtendBlockObject(const Expr *e) {
3354 return CGF.EmitARCExtendBlockObject(e);
3355 }
3356
3357 /// For reclaims, perform an unsafeClaim if that's enabled.
3358 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3359 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3360 }
3361
3362 /// When we have an undecorated call, just emit it without adding
3363 /// the unsafeClaim.
3364 llvm::Value *visitCall(const Expr *e) {
3365 return CGF.EmitScalarExpr(e);
3366 }
3367
3368 /// Just do normal scalar emission in the default case.
3369 llvm::Value *visitExpr(const Expr *e) {
3370 return CGF.EmitScalarExpr(e);
3371 }
3372};
3373}
3374
3375static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3376 const Expr *e) {
3377 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3378}
3379
3380/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3381/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3382/// avoiding any spurious retains, including by performing reclaims
3383/// with objc_unsafeClaimAutoreleasedReturnValue.
3384llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3385 // Look through full-expressions.
3386 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3387 enterFullExpression(cleanups);
3388 RunCleanupsScope scope(*this);
3389 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3390 }
3391
3392 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3393}
3394
3395std::pair<LValue,llvm::Value*>
3396CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3397 bool ignored) {
3398 // Evaluate the RHS first. If we're ignoring the result, assume
3399 // that we can emit at an unsafe +0.
3400 llvm::Value *value;
3401 if (ignored) {
3402 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3403 } else {
3404 value = EmitScalarExpr(e->getRHS());
3405 }
3406
3407 // Emit the LHS and perform the store.
3408 LValue lvalue = EmitLValue(e->getLHS());
3409 EmitStoreOfScalar(value, lvalue);
3410
3411 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3412}
3413
John McCall31168b02011-06-15 23:02:42 +00003414std::pair<LValue,llvm::Value*>
3415CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3416 bool ignored) {
3417 // Evaluate the RHS first.
3418 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3419 llvm::Value *value = result.getPointer();
3420
John McCallb726a552011-07-28 07:23:35 +00003421 bool hasImmediateRetain = result.getInt();
3422
3423 // If we didn't emit a retained object, and the l-value is of block
3424 // type, then we need to emit the block-retain immediately in case
3425 // it invalidates the l-value.
3426 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003427 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003428 hasImmediateRetain = true;
3429 }
3430
John McCall31168b02011-06-15 23:02:42 +00003431 LValue lvalue = EmitLValue(e->getLHS());
3432
3433 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003434 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003435 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003436 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003437 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003438 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003439 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003440 }
3441
3442 return std::pair<LValue,llvm::Value*>(lvalue, value);
3443}
3444
3445std::pair<LValue,llvm::Value*>
3446CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3447 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3448 LValue lvalue = EmitLValue(e->getLHS());
3449
Eli Friedmana0544d62011-12-03 04:14:32 +00003450 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003451
3452 return std::pair<LValue,llvm::Value*>(lvalue, value);
3453}
3454
3455void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003456 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003457 const Stmt *subStmt = ARPS.getSubStmt();
3458 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3459
3460 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003461 if (DI)
3462 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003463
3464 // Keep track of the current cleanup stack depth.
3465 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003466 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003467 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3468 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3469 } else {
3470 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3471 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3472 }
3473
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003474 for (const auto *I : S.body())
3475 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003476
Eric Christopher7cdf9482011-10-13 21:45:18 +00003477 if (DI)
3478 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003479}
John McCall1bd25562011-06-24 23:21:27 +00003480
3481/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3482/// make sure it survives garbage collection until this point.
3483void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3484 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003485 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003486 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
James Y Knight9871db02019-02-05 16:42:33 +00003487 llvm::InlineAsm *extender = llvm::InlineAsm::get(extenderType,
3488 /* assembly */ "",
3489 /* constraints */ "r",
3490 /* side effects */ true);
John McCall1bd25562011-06-24 23:21:27 +00003491
3492 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003493 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003494}
3495
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003496/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003497/// non-trivial copy assignment function, produce following helper function.
3498/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3499///
3500llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003501CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3502 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003503 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003504 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003505 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003506 QualType Ty = PID->getPropertyIvarDecl()->getType();
3507 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003508 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003509 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003510 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003511 return nullptr;
3512 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003513 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003514 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003515 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3516 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3517 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003518
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003519 ASTContext &C = getContext();
3520 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003521 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003522
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003523 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003524 QualType DestTy = C.getPointerType(Ty);
3525 QualType SrcTy = Ty;
3526 SrcTy.addConst();
3527 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003528
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003529 SmallVector<QualType, 2> ArgTys;
3530 ArgTys.push_back(DestTy);
3531 ArgTys.push_back(SrcTy);
3532 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3533
3534 FunctionDecl *FD = FunctionDecl::Create(
3535 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3536 FunctionTy, nullptr, SC_Static, false, false);
3537
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003538 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003539 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3540 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003541 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003542 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3543 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003544 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003545
John McCallc56a8b32016-03-11 04:30:31 +00003546 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003547 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003548
John McCalla729c622012-02-17 03:33:10 +00003549 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003550
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003551 llvm::Function *Fn =
3552 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003553 "__assign_helper_atomic_property_",
3554 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003555
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003556 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003557
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003558 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003559
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003560 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3561 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003562 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003563 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003564
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003565 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3566 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003567 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003568 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003569
John McCall113bee02012-03-10 09:33:50 +00003570 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003571 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003572 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3573 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3574 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003575
Bruno Riccic5885cf2018-12-21 15:20:32 +00003576 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003577
3578 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003579 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003580 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003581 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003582}
3583
3584llvm::Constant *
3585CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3586 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003587 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003588 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003589 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003590 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3591 QualType Ty = PD->getType();
3592 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003593 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003594 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003595 return nullptr;
3596 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003597 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003598 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003599 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3600 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3601 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003602
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003603 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003604 IdentifierInfo *II =
3605 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003606
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003607 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003608 QualType DestTy = C.getPointerType(Ty);
3609 QualType SrcTy = Ty;
3610 SrcTy.addConst();
3611 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003612
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003613 SmallVector<QualType, 2> ArgTys;
3614 ArgTys.push_back(DestTy);
3615 ArgTys.push_back(SrcTy);
3616 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3617
3618 FunctionDecl *FD = FunctionDecl::Create(
3619 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3620 FunctionTy, nullptr, SC_Static, false, false);
3621
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003622 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003623 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3624 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003625 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003626 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3627 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003628 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003629
John McCallc56a8b32016-03-11 04:30:31 +00003630 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003631 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003632
John McCalla729c622012-02-17 03:33:10 +00003633 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003634
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003635 llvm::Function *Fn = llvm::Function::Create(
3636 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3637 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003638
3639 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003640
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003641 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003642
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003643 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3644 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003645
John McCall113bee02012-03-10 09:33:50 +00003646 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003647 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003648
3649 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003650 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003651
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003652 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003653 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003654 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3655 CXXConstExpr->arg_end());
3656
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003657 CXXConstructExpr *TheCXXConstructExpr =
3658 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3659 CXXConstExpr->getConstructor(),
3660 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003661 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003662 CXXConstExpr->hadMultipleCandidates(),
3663 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003664 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003665 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003666 CXXConstExpr->getConstructionKind(),
3667 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003668
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003669 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3670 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003671
John McCall113bee02012-03-10 09:33:50 +00003672 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003673 CharUnits Alignment
3674 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003675 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003676 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3677 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003678 AggValueSlot::IsDestructed,
3679 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003680 AggValueSlot::IsNotAliased,
3681 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003682
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003683 FinishFunction();
3684 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3685 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3686 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003687}
3688
Eli Friedmanec75fec2012-02-28 01:08:45 +00003689llvm::Value *
3690CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3691 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003692 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3693 Selector CopySelector =
3694 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003695 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3696 Selector AutoreleaseSelector =
3697 getContext().Selectors.getNullarySelector(AutoreleaseID);
3698
3699 // Emit calls to retain/autorelease.
3700 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3701 llvm::Value *Val = Block;
3702 RValue Result;
3703 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003704 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003705 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003706 Val = Result.getScalarVal();
3707 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3708 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003709 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003710 Val = Result.getScalarVal();
3711 return Val;
3712}
3713
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003714llvm::Value *
3715CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3716 assert(Args.size() == 3 && "Expected 3 argument here!");
3717
3718 if (!CGM.IsOSVersionAtLeastFn) {
3719 llvm::FunctionType *FTy =
3720 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3721 CGM.IsOSVersionAtLeastFn =
3722 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3723 }
3724
3725 llvm::Value *CallRes =
3726 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3727
3728 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3729}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003730
Alex Lorenza8fbef42017-03-23 11:14:27 +00003731void CodeGenModule::emitAtAvailableLinkGuard() {
3732 if (!IsOSVersionAtLeastFn)
3733 return;
3734 // @available requires CoreFoundation only on Darwin.
3735 if (!Target.getTriple().isOSDarwin())
3736 return;
3737 // Add -framework CoreFoundation to the linker commands. We still want to
3738 // emit the core foundation reference down below because otherwise if
3739 // CoreFoundation is not used in the code, the linker won't link the
3740 // framework.
3741 auto &Context = getLLVMContext();
3742 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3743 llvm::MDString::get(Context, "CoreFoundation")};
3744 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3745 // Emit a reference to a symbol from CoreFoundation to ensure that
3746 // CoreFoundation is linked into the final binary.
3747 llvm::FunctionType *FTy =
3748 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003749 llvm::FunctionCallee CFFunc =
Alex Lorenza8fbef42017-03-23 11:14:27 +00003750 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3751
3752 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
James Y Knight9871db02019-02-05 16:42:33 +00003753 llvm::FunctionCallee CFLinkCheckFuncRef = CreateRuntimeFunction(
3754 CheckFTy, "__clang_at_available_requires_core_foundation_framework",
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003755 llvm::AttributeList(), /*Local=*/true);
James Y Knight9871db02019-02-05 16:42:33 +00003756 llvm::Function *CFLinkCheckFunc =
3757 cast<llvm::Function>(CFLinkCheckFuncRef.getCallee()->stripPointerCasts());
3758 if (CFLinkCheckFunc->empty()) {
3759 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3760 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3761 CodeGenFunction CGF(*this);
3762 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3763 CGF.EmitNounwindRuntimeCall(CFFunc,
3764 llvm::Constant::getNullValue(VoidPtrTy));
3765 CGF.Builder.CreateUnreachable();
3766 addCompilerUsedGlobal(CFLinkCheckFunc);
3767 }
Alex Lorenza8fbef42017-03-23 11:14:27 +00003768}
3769
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003770CGObjCRuntime::~CGObjCRuntime() {}