blob: 9c66ff0e8fb2add5e55c8bde6023cbb2a2492a30 [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//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregore83b9562015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
John McCall7f416cc2015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
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();
Patrick Beard0caa3942012-04-19 00:25:12 +000065 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +000068
Ted Kremeneke65b0862012-03-06 20:05:56 +000069 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000070 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CallArgList Args;
Alex Denisovfde64952015-06-26 05:28:36 +000077 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +000079
80 // ObjCBoxedExpr supports boxing of structs and unions
Alex Denisovfde64952015-06-26 05:28:36 +000081 // via [NSValue valueWithBytes:objCType:]
82 const QualType ValueType(SubExpr->getType().getCanonicalType());
83 if (ValueType->isObjCBoxableRecordType()) {
84 // Emit CodeGen for first parameter
85 // and cast value to correct type
John McCall7f416cc2015-09-08 08:05:57 +000086 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisovfde64952015-06-26 05:28:36 +000087 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCall7f416cc2015-09-08 08:05:57 +000088 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisovfde64952015-06-26 05:28:36 +000090
91 // Create char array to store type encoding
92 std::string Str;
93 getContext().getObjCEncodingForType(ValueType, Str);
John McCall7f416cc2015-09-08 08:05:57 +000094 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Fangrui Song6907ce22018-07-30 19:24:48 +000095
Alex Denisovfde64952015-06-26 05:28:36 +000096 // Cast type encoding to correct type
97 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
100
101 Args.add(RValue::get(Cast), EncodingQT);
102 } else {
103 Args.add(EmitAnyExpr(SubExpr), ArgQT);
104 }
Alp Toker314cc812014-01-25 16:55:45 +0000105
106 RValue result = Runtime.GenerateMessageSend(
107 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108 Args, ClassDecl, BoxingMethod);
Fangrui Song6907ce22018-07-30 19:24:48 +0000109 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000110 ConvertType(E->getType()));
111}
112
113llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000114 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +0000116 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000117 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
118 if (!ALE)
119 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000120
121 // Optimize empty collections by referencing constants, when available.
Fangrui Song6907ce22018-07-30 19:24:48 +0000122 uint64_t NumElements =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000123 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000124 if (NumElements == 0 && CGM.getLangOpts().ObjCRuntime.hasEmptyCollections()) {
125 StringRef ConstantName = ALE ? "__NSArray0__" : "__NSDictionary0__";
126 QualType IdTy(CGM.getContext().getObjCIdType());
127 llvm::Constant *Constant =
128 CGM.CreateRuntimeVariable(ConvertType(IdTy), ConstantName);
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000129 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000130 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getBeginLoc());
Akira Hatanakab5d1ea42017-04-17 15:21:55 +0000131 cast<llvm::LoadInst>(Ptr)->setMetadata(
132 CGM.getModule().getMDKindID("invariant.load"),
133 llvm::MDNode::get(getLLVMContext(), None));
134 return Builder.CreateBitCast(Ptr, ConvertType(E->getType()));
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +0000135 }
136
137 // Compute the type of the array we're initializing.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000138 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
139 NumElements);
140 QualType ElementType = Context.getObjCIdType().withConst();
Fangrui Song6907ce22018-07-30 19:24:48 +0000141 QualType ElementArrayType
142 = Context.getConstantArrayType(ElementType, APNumElements,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000143 ArrayType::Normal, /*IndexTypeQuals=*/0);
144
145 // Allocate the temporary array(s).
John McCall7f416cc2015-09-08 08:05:57 +0000146 Address Objects = CreateMemTemp(ElementArrayType, "objects");
147 Address Keys = Address::invalid();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000148 if (DLE)
149 Keys = CreateMemTemp(ElementArrayType, "keys");
Fangrui Song6907ce22018-07-30 19:24:48 +0000150
John McCall770a4c12013-04-04 00:20:38 +0000151 // In ARC, we may need to do extra work to keep all the keys and
152 // values alive until after the call.
153 SmallVector<llvm::Value *, 16> NeededObjects;
154 bool TrackNeededObjects =
155 (getLangOpts().ObjCAutoRefCount &&
156 CGM.getCodeGenOpts().OptimizationLevel != 0);
157
Ted Kremeneke65b0862012-03-06 20:05:56 +0000158 // Perform the actual initialialization of the array(s).
159 for (uint64_t i = 0; i < NumElements; i++) {
160 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000161 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000162 const Expr *Rhs = ALE->getElement(i);
John McCall7f416cc2015-09-08 08:05:57 +0000163 LValue LV = MakeAddrLValue(
164 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000165 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000166
167 llvm::Value *value = EmitScalarExpr(Rhs);
168 EmitStoreThroughLValue(RValue::get(value), LV, true);
169 if (TrackNeededObjects) {
170 NeededObjects.push_back(value);
171 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000172 } else {
John McCall770a4c12013-04-04 00:20:38 +0000173 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000174 const Expr *Key = DLE->getKeyValueElement(i).Key;
John McCall7f416cc2015-09-08 08:05:57 +0000175 LValue KeyLV = MakeAddrLValue(
176 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000177 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000178 llvm::Value *keyValue = EmitScalarExpr(Key);
179 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180
John McCall770a4c12013-04-04 00:20:38 +0000181 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000182 const Expr *Value = DLE->getKeyValueElement(i).Value;
John McCall7f416cc2015-09-08 08:05:57 +0000183 LValue ValueLV = MakeAddrLValue(
184 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000185 ElementType, AlignmentSource::Decl);
John McCall770a4c12013-04-04 00:20:38 +0000186 llvm::Value *valueValue = EmitScalarExpr(Value);
187 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
188 if (TrackNeededObjects) {
189 NeededObjects.push_back(keyValue);
190 NeededObjects.push_back(valueValue);
191 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000192 }
193 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000194
Ted Kremeneke65b0862012-03-06 20:05:56 +0000195 // Generate the argument list.
Fangrui Song6907ce22018-07-30 19:24:48 +0000196 CallArgList Args;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000197 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
198 const ParmVarDecl *argDecl = *PI++;
199 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000200 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000201 if (DLE) {
202 argDecl = *PI++;
203 ArgQT = argDecl->getType().getUnqualifiedType();
John McCall7f416cc2015-09-08 08:05:57 +0000204 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000205 }
206 argDecl = *PI;
207 ArgQT = argDecl->getType().getUnqualifiedType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000208 llvm::Value *Count =
Ted Kremeneke65b0862012-03-06 20:05:56 +0000209 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
210 Args.add(RValue::get(Count), ArgQT);
211
212 // Generate a reference to the class pointer, which will be the receiver.
213 Selector Sel = MethodWithObjects->getSelector();
214 QualType ResultType = E->getType();
215 const ObjCObjectPointerType *InterfacePointerType
216 = ResultType->getAsObjCInterfacePointerType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000217 ObjCInterfaceDecl *Class
Ted Kremeneke65b0862012-03-06 20:05:56 +0000218 = InterfacePointerType->getObjectType()->getInterface();
219 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000220 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000221
222 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000223 RValue result = Runtime.GenerateMessageSend(
224 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
225 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000226
227 // The above message send needs these objects, but in ARC they are
228 // passed in a buffer that is essentially __unsafe_unretained.
229 // Therefore we must prevent the optimizer from releasing them until
230 // after the call.
231 if (TrackNeededObjects) {
232 EmitARCIntrinsicUse(NeededObjects);
233 }
234
Fangrui Song6907ce22018-07-30 19:24:48 +0000235 return Builder.CreateBitCast(result.getScalarVal(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000236 ConvertType(E->getType()));
237}
238
239llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000240 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000241}
242
243llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
244 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000245 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246}
247
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000248/// Emit a selector.
249llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
250 // Untyped selector.
251 // Note that this implementation allows for non-constant strings to be passed
252 // as arguments to @selector(). Currently, the only thing preventing this
253 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000254 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000255}
256
Daniel Dunbar66912a12008-08-20 00:28:19 +0000257llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
258 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000259 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000260}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000262/// Adjust the type of an Objective-C object that doesn't match up due
Douglas Gregore83b9562015-07-07 03:57:53 +0000263/// to type erasure at various points, e.g., related result types or the use
264/// of parameterized classes.
265static RValue AdjustObjCObjectType(CodeGenFunction &CGF, QualType ExpT,
266 RValue Result) {
267 if (!ExpT->isObjCRetainableType())
Douglas Gregor33823722011-06-11 01:09:30 +0000268 return Result;
John McCall31168b02011-06-15 23:02:42 +0000269
Douglas Gregore83b9562015-07-07 03:57:53 +0000270 // If the converted types are the same, we're done.
271 llvm::Type *ExpLLVMTy = CGF.ConvertType(ExpT);
272 if (ExpLLVMTy == Result.getScalarVal()->getType())
Douglas Gregor33823722011-06-11 01:09:30 +0000273 return Result;
Douglas Gregore83b9562015-07-07 03:57:53 +0000274
275 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor33823722011-06-11 01:09:30 +0000276 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000277 ExpLLVMTy));
Douglas Gregor33823722011-06-11 01:09:30 +0000278}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000279
John McCallcf166702011-07-22 08:53:00 +0000280/// Decide whether to extend the lifetime of the receiver of a
281/// returns-inner-pointer message.
282static bool
283shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
284 switch (message->getReceiverKind()) {
285
286 // For a normal instance message, we should extend unless the
287 // receiver is loaded from a variable with precise lifetime.
288 case ObjCMessageExpr::Instance: {
289 const Expr *receiver = message->getInstanceReceiver();
John McCall6380a282015-09-09 23:37:17 +0000290
291 // Look through OVEs.
292 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
293 if (opaque->getSourceExpr())
294 receiver = opaque->getSourceExpr()->IgnoreParens();
295 }
296
John McCallcf166702011-07-22 08:53:00 +0000297 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
298 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
299 receiver = ice->getSubExpr()->IgnoreParens();
300
John McCall6380a282015-09-09 23:37:17 +0000301 // Look through OVEs.
302 if (auto opaque = dyn_cast<OpaqueValueExpr>(receiver)) {
303 if (opaque->getSourceExpr())
304 receiver = opaque->getSourceExpr()->IgnoreParens();
305 }
306
John McCallcf166702011-07-22 08:53:00 +0000307 // Only __strong variables.
308 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
309 return true;
310
311 // All ivars and fields have precise lifetime.
312 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
313 return false;
314
315 // Otherwise, check for variables.
316 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
317 if (!declRef) return true;
318 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
319 if (!var) return true;
320
321 // All variables have precise lifetime except local variables with
322 // automatic storage duration that aren't specially marked.
323 return (var->hasLocalStorage() &&
324 !var->hasAttr<ObjCPreciseLifetimeAttr>());
325 }
326
327 case ObjCMessageExpr::Class:
328 case ObjCMessageExpr::SuperClass:
329 // It's never necessary for class objects.
330 return false;
331
332 case ObjCMessageExpr::SuperInstance:
333 // We generally assume that 'self' lives throughout a method call.
334 return false;
335 }
336
337 llvm_unreachable("invalid receiver kind");
338}
339
John McCall460ce582015-10-22 18:38:17 +0000340/// Given an expression of ObjC pointer type, check whether it was
341/// immediately loaded from an ARC __weak l-value.
342static const Expr *findWeakLValue(const Expr *E) {
343 assert(E->getType()->isObjCRetainableType());
344 E = E->IgnoreParens();
345 if (auto CE = dyn_cast<CastExpr>(E)) {
346 if (CE->getCastKind() == CK_LValueToRValue) {
347 if (CE->getSubExpr()->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
348 return CE->getSubExpr();
349 }
350 }
351
352 return nullptr;
353}
354
Pete Coopere3886802018-12-08 05:13:50 +0000355/// The ObjC runtime may provide entrypoints that are likely to be faster
356/// than an ordinary message send of the appropriate selector.
357///
358/// The entrypoints are guaranteed to be equivalent to just sending the
359/// corresponding message. If the entrypoint is implemented naively as just a
360/// message send, using it is a trade-off: it sacrifices a few cycles of
361/// overhead to save a small amount of code. However, it's possible for
362/// runtimes to detect and special-case classes that use "standard"
363/// behavior; if that's dynamically a large proportion of all objects, using
364/// the entrypoint will also be faster than using a message send.
365///
366/// If the runtime does support a required entrypoint, then this method will
367/// generate a call and return the resulting value. Otherwise it will return
368/// None and the caller can generate a msgSend instead.
369static Optional<llvm::Value *>
370tryGenerateSpecializedMessageSend(CodeGenFunction &CGF, QualType ResultType,
371 llvm::Value *Receiver,
372 const CallArgList& Args, Selector Sel,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000373 const ObjCMethodDecl *method,
374 bool isClassMessage) {
Pete Coopere3886802018-12-08 05:13:50 +0000375 auto &CGM = CGF.CGM;
376 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
377 return None;
378
379 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
380 switch (Sel.getMethodFamily()) {
381 case OMF_alloc:
Pete Cooperde0a8d32019-01-02 17:25:30 +0000382 if (isClassMessage &&
383 Runtime.shouldUseRuntimeFunctionsForAlloc() &&
Pete Coopere3886802018-12-08 05:13:50 +0000384 ResultType->isObjCObjectPointerType()) {
385 // [Foo alloc] -> objc_alloc(Foo)
386 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
387 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
388 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
389 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
390 Args.size() == 1 && Args.front().getType()->isPointerType() &&
391 Sel.getNameForSlot(0) == "allocWithZone") {
392 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
393 if (isa<llvm::ConstantPointerNull>(arg))
394 return CGF.EmitObjCAllocWithZone(Receiver,
395 CGF.ConvertType(ResultType));
396 return None;
397 }
398 }
399 break;
400
Pete Coopere5b64ea2018-12-21 21:00:32 +0000401 case OMF_autorelease:
402 if (ResultType->isObjCObjectPointerType() &&
403 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
404 Runtime.shouldUseARCFunctionsForRetainRelease())
405 return CGF.EmitObjCAutorelease(Receiver, CGF.ConvertType(ResultType));
406 break;
407
408 case OMF_retain:
409 if (ResultType->isObjCObjectPointerType() &&
410 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
411 Runtime.shouldUseARCFunctionsForRetainRelease())
412 return CGF.EmitObjCRetainNonBlock(Receiver, CGF.ConvertType(ResultType));
413 break;
414
415 case OMF_release:
416 if (ResultType->isVoidType() &&
417 CGM.getLangOpts().getGC() == LangOptions::NonGC &&
418 Runtime.shouldUseARCFunctionsForRetainRelease()) {
419 CGF.EmitObjCRelease(Receiver, ARCPreciseLifetime);
420 return nullptr;
421 }
422 break;
423
Pete Coopere3886802018-12-08 05:13:50 +0000424 default:
425 break;
426 }
427 return None;
428}
429
John McCall78a15112010-05-22 01:48:05 +0000430RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
431 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000432 // Only the lookup mechanism and first two arguments of the method
433 // implementation vary between runtimes. We can get the receiver and
434 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000435
John McCall31168b02011-06-15 23:02:42 +0000436 bool isDelegateInit = E->isDelegateInitCall();
437
John McCallcf166702011-07-22 08:53:00 +0000438 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000439
John McCall460ce582015-10-22 18:38:17 +0000440 // If the method is -retain, and the receiver's being loaded from
441 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
442 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
443 method->getMethodFamily() == OMF_retain) {
444 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
445 LValue lvalue = EmitLValue(lvalueExpr);
446 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
447 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
448 }
449 }
450
John McCall31168b02011-06-15 23:02:42 +0000451 // We don't retain the receiver in delegate init calls, and this is
452 // safe because the receiver value is always loaded from 'self',
453 // which we zero out. We don't want to Block_copy block receivers,
454 // though.
455 bool retainSelf =
456 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000457 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000458 method &&
459 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000460
Daniel Dunbar8d480592008-08-11 18:12:00 +0000461 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000462 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000463 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000464 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000465 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000466 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000467 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000468 switch (E->getReceiverKind()) {
469 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000470 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000471 if (retainSelf) {
472 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
473 E->getInstanceReceiver());
474 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000475 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000476 } else
477 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000478 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000479
Douglas Gregor9a129192010-04-21 00:45:42 +0000480 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000481 ReceiverType = E->getClassReceiver();
482 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000483 assert(ObjTy && "Invalid Objective-C class message send");
484 OID = ObjTy->getInterface();
485 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000486 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000487 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000488 break;
489 }
490
491 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000492 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000493 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000494 isSuperMessage = true;
495 break;
496
497 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000498 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000499 Receiver = LoadObjCSelf();
500 isSuperMessage = true;
501 isClassMessage = true;
502 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000503 }
504
John McCallcf166702011-07-22 08:53:00 +0000505 if (retainSelf)
506 Receiver = EmitARCRetainNonBlock(Receiver);
507
508 // In ARC, we sometimes want to "extend the lifetime"
509 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
510 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000511 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000512 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
513 shouldExtendReceiverForInnerPointerMessage(E))
514 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
515
Alp Toker314cc812014-01-25 16:55:45 +0000516 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000517
Daniel Dunbarc722b852008-08-30 03:02:31 +0000518 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000519 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000520
John McCall31168b02011-06-15 23:02:42 +0000521 // For delegate init calls in ARC, do an unsafe store of null into
522 // self. This represents the call taking direct ownership of that
523 // value. We have to do this after emitting the other call
524 // arguments because they might also reference self, but we don't
525 // have to worry about any of them modifying self because that would
526 // be an undefined read and write of an object in unordered
527 // expressions.
528 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000529 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000530 "delegate init calls should only be marked in ARC");
531
532 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000533 Address selfAddr =
534 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000535 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
536 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000537
Douglas Gregor33823722011-06-11 01:09:30 +0000538 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000539 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000540 // super is only valid in an Objective-C method
541 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000542 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000543 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
544 E->getSelector(),
545 OMD->getClassInterface(),
546 isCategoryImpl,
547 Receiver,
548 isClassMessage,
549 Args,
John McCallcf166702011-07-22 08:53:00 +0000550 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000551 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000552 // Call runtime methods directly if we can.
553 if (Optional<llvm::Value *> SpecializedResult =
554 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
Pete Cooperde0a8d32019-01-02 17:25:30 +0000555 E->getSelector(), method,
556 isClassMessage)) {
Pete Coopere3886802018-12-08 05:13:50 +0000557 result = RValue::get(SpecializedResult.getValue());
558 } else {
559 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
560 E->getSelector(), Receiver, Args,
561 OID, method);
562 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000563 }
John McCall31168b02011-06-15 23:02:42 +0000564
565 // For delegate init calls in ARC, implicitly store the result of
566 // the call back into self. This takes ownership of the value.
567 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000568 Address selfAddr =
569 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000570 llvm::Value *newSelf = result.getScalarVal();
571
572 // The delegate return type isn't necessarily a matching type; in
573 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000574 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000575 newSelf = Builder.CreateBitCast(newSelf, selfTy);
576
577 Builder.CreateStore(newSelf, selfAddr);
578 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000579
Douglas Gregore83b9562015-07-07 03:57:53 +0000580 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000581}
582
John McCall31168b02011-06-15 23:02:42 +0000583namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000584struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000585 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000586 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000587
588 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000589 const ObjCInterfaceDecl *iface = impl->getClassInterface();
590 if (!iface->getSuperClass()) return;
591
John McCalldffafde2011-07-13 18:26:47 +0000592 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
593
John McCall31168b02011-06-15 23:02:42 +0000594 // Call [super dealloc] if we have a superclass.
595 llvm::Value *self = CGF.LoadObjCSelf();
596
597 CallArgList args;
598 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
599 CGF.getContext().VoidTy,
600 method->getSelector(),
601 iface,
John McCalldffafde2011-07-13 18:26:47 +0000602 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000603 self,
604 /*is class msg*/ false,
605 args,
606 method);
607 }
608};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000609}
John McCall31168b02011-06-15 23:02:42 +0000610
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000611/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
612/// the LLVM function and sets the other context used by
613/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000614void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000615 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000616 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000617 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000618 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000619 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000620 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000621
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000622 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000623
John McCalla729c622012-02-17 03:33:10 +0000624 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000625 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000626
John McCalla738c252011-03-09 04:27:21 +0000627 args.push_back(OMD->getSelfDecl());
628 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000629
Benjamin Kramerf9890422015-02-17 16:48:30 +0000630 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000631
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000632 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000633 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000634
Adrian Prantl42d71b92014-04-10 23:21:53 +0000635 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
636 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000637
638 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000639 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000640 OMD->isInstanceMethod() &&
641 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000642 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000643 OMD->getSelector().getIdentifierInfoForSlot(0);
644 if (ident->isStr("dealloc"))
645 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
646 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000647}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000648
John McCall31168b02011-06-15 23:02:42 +0000649static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
650 LValue lvalue, QualType type);
651
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000652/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000653/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000654void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000655 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000656 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000657 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000658 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000659 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000660 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000661}
662
John McCallb923ece2011-09-12 23:06:44 +0000663/// emitStructGetterCall - Call the runtime function to load a property
664/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000665static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000666 bool isAtomic, bool hasStrong) {
667 ASTContext &Context = CGF.getContext();
668
John McCall7f416cc2015-09-08 08:05:57 +0000669 Address src =
670 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
671 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000672
Fangrui Song6907ce22018-07-30 19:24:48 +0000673 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000674 // sizeof (Type of Ivar), isAtomic, false);
675 CallArgList args;
676
John McCall7f416cc2015-09-08 08:05:57 +0000677 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
678 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000679
680 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000681 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000682
683 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
684 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
685 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
686 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
687
John McCallb92ab1a2016-10-26 23:46:34 +0000688 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
689 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000690 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000691 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000692}
693
John McCallf4528ae2011-09-13 03:34:09 +0000694/// Determine whether the given architecture supports unaligned atomic
695/// accesses. They don't have to be fast, just faster than a function
696/// call and a mutex.
697static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000698 // FIXME: Allow unaligned atomic load/store on x86. (It is not
699 // currently supported by the backend.)
700 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000701}
702
703/// Return the maximum size that permits atomic accesses for the given
704/// architecture.
705static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
706 llvm::Triple::ArchType arch) {
707 // ARM has 8-byte atomic accesses, but it's not clear whether we
708 // want to rely on them here.
709
710 // In the default case, just assume that any size up to a pointer is
711 // fine given adequate alignment.
712 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
713}
714
715namespace {
716 class PropertyImplStrategy {
717 public:
718 enum StrategyKind {
719 /// The 'native' strategy is to use the architecture's provided
720 /// reads and writes.
721 Native,
722
723 /// Use objc_setProperty and objc_getProperty.
724 GetSetProperty,
725
726 /// Use objc_setProperty for the setter, but use expression
727 /// evaluation for the getter.
728 SetPropertyAndExpressionGet,
729
730 /// Use objc_copyStruct.
731 CopyStruct,
732
733 /// The 'expression' strategy is to emit normal assignment or
734 /// lvalue-to-rvalue expressions.
735 Expression
736 };
737
738 StrategyKind getKind() const { return StrategyKind(Kind); }
739
740 bool hasStrongMember() const { return HasStrong; }
741 bool isAtomic() const { return IsAtomic; }
742 bool isCopy() const { return IsCopy; }
743
744 CharUnits getIvarSize() const { return IvarSize; }
745 CharUnits getIvarAlignment() const { return IvarAlignment; }
746
747 PropertyImplStrategy(CodeGenModule &CGM,
748 const ObjCPropertyImplDecl *propImpl);
749
750 private:
751 unsigned Kind : 8;
752 unsigned IsAtomic : 1;
753 unsigned IsCopy : 1;
754 unsigned HasStrong : 1;
755
756 CharUnits IvarSize;
757 CharUnits IvarAlignment;
758 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000759}
John McCallf4528ae2011-09-13 03:34:09 +0000760
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000761/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000762PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
763 const ObjCPropertyImplDecl *propImpl) {
764 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000765 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000766
John McCall43192862011-09-13 18:31:23 +0000767 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
768 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000769 HasStrong = false; // doesn't matter here.
770
771 // Evaluate the ivar's size and alignment.
772 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
773 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000774 std::tie(IvarSize, IvarAlignment) =
775 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000776
777 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000778 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000779 if (IsCopy) {
780 Kind = GetSetProperty;
781 return;
782 }
783
John McCall43192862011-09-13 18:31:23 +0000784 // Handle retain.
785 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000786 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000787 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000788 // fallthrough
789
790 // In ARC, if the property is non-atomic, use expression emission,
791 // which translates to objc_storeStrong. This isn't required, but
792 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000793 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000794 // Using standard expression emission for the setter is only
795 // acceptable if the ivar is __strong, which won't be true if
796 // the property is annotated with __attribute__((NSObject)).
797 // TODO: falling all the way back to objc_setProperty here is
798 // just laziness, though; we could still use objc_storeStrong
799 // if we hacked it right.
800 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
801 Kind = Expression;
802 else
803 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000804 return;
805
806 // Otherwise, we need to at least use setProperty. However, if
807 // the property isn't atomic, we can use normal expression
808 // emission for the getter.
809 } else if (!IsAtomic) {
810 Kind = SetPropertyAndExpressionGet;
811 return;
812
813 // Otherwise, we have to use both setProperty and getProperty.
814 } else {
815 Kind = GetSetProperty;
816 return;
817 }
818 }
819
820 // If we're not atomic, just use expression accesses.
821 if (!IsAtomic) {
822 Kind = Expression;
823 return;
824 }
825
John McCall0e5c0862011-09-13 05:36:29 +0000826 // Properties on bitfield ivars need to be emitted using expression
827 // accesses even if they're nominally atomic.
828 if (ivar->isBitField()) {
829 Kind = Expression;
830 return;
831 }
832
John McCallf4528ae2011-09-13 03:34:09 +0000833 // GC-qualified or ARC-qualified ivars need to be emitted as
834 // expressions. This actually works out to being atomic anyway,
835 // except for ARC __strong, but that should trigger the above code.
836 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000837 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000838 CGM.getContext().getObjCGCAttrKind(ivarType))) {
839 Kind = Expression;
840 return;
841 }
842
843 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000844 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000845 if (const RecordType *recordType = ivarType->getAs<RecordType>())
846 HasStrong = recordType->getDecl()->hasObjectMember();
847
848 // We can never access structs with object members with a native
849 // access, because we need to use write barriers. This is what
850 // objc_copyStruct is for.
851 if (HasStrong) {
852 Kind = CopyStruct;
853 return;
854 }
855
856 // Otherwise, this is target-dependent and based on the size and
857 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000858
859 // If the size of the ivar is not a power of two, give up. We don't
860 // want to get into the business of doing compare-and-swaps.
861 if (!IvarSize.isPowerOfTwo()) {
862 Kind = CopyStruct;
863 return;
864 }
865
John McCallf4528ae2011-09-13 03:34:09 +0000866 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000867 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000868
869 // Most architectures require memory to fit within a single cache
870 // line, so the alignment has to be at least the size of the access.
871 // Otherwise we have to grab a lock.
872 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
873 Kind = CopyStruct;
874 return;
875 }
876
877 // If the ivar's size exceeds the architecture's maximum atomic
878 // access size, we have to use CopyStruct.
879 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
880 Kind = CopyStruct;
881 return;
882 }
883
884 // Otherwise, we can use native loads and stores.
885 Kind = Native;
886}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000888/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000889///
890/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000891/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000892void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
893 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000894 llvm::Constant *AtomicHelperFn =
895 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000896 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
897 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
898 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000899 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000900
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000901 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000902
903 FinishFunction();
904}
905
John McCallbdd81852011-09-13 06:00:03 +0000906static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
907 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000908 if (!getter) return true;
909
910 // Sema only makes only of these when the ivar has a C++ class type,
911 // so the form is pretty constrained.
912
John McCallbdd81852011-09-13 06:00:03 +0000913 // If the property has a reference type, we might just be binding a
914 // reference, in which case the result will be a gl-value. We should
915 // treat this as a non-trivial operation.
916 if (getter->isGLValue())
917 return false;
918
John McCallf4528ae2011-09-13 03:34:09 +0000919 // If we selected a trivial copy-constructor, we're okay.
920 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
921 return (construct->getConstructor()->isTrivial());
922
923 // The constructor might require cleanups (in which case it's never
924 // trivial).
925 assert(isa<ExprWithCleanups>(getter));
926 return false;
927}
928
Fangrui Song6907ce22018-07-30 19:24:48 +0000929/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000930/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000931static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000932 llvm::Value *returnAddr,
933 ObjCIvarDecl *ivar,
934 llvm::Constant *AtomicHelperFn) {
935 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
936 // AtomicHelperFn);
937 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000938
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000939 // The 1st argument is the return Slot.
940 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000941
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000942 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +0000943 llvm::Value *ivarAddr =
944 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +0000945 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000946 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
947 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000948
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000949 // Third argument is the helper function.
950 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000951
952 llvm::Constant *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000953 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000954 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000955 CGF.EmitCall(
956 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000957 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000958}
959
John McCallf4528ae2011-09-13 03:34:09 +0000960void
961CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000962 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000963 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000964 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000965 // If there's a non-trivial 'get' expression, we just have to emit that.
966 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000967 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +0000968 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
969 propImpl->getGetterCXXConstructor(),
970 /* NRVOCandidate=*/nullptr);
971 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000972 }
973 else {
974 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000975 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000976 ivar, AtomicHelperFn);
977 }
John McCallf4528ae2011-09-13 03:34:09 +0000978 return;
979 }
980
981 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
982 QualType propType = prop->getType();
983 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
984
Fangrui Song6907ce22018-07-30 19:24:48 +0000985 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +0000986
987 // Pick an implementation strategy.
988 PropertyImplStrategy strategy(CGM, propImpl);
989 switch (strategy.getKind()) {
990 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000991 // We don't need to do anything for a zero-size struct.
992 if (strategy.getIvarSize().isZero())
993 return;
994
John McCallf4528ae2011-09-13 03:34:09 +0000995 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
996
997 // Currently, all atomic accesses have to be through integer
998 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000999 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
1000 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +00001001 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1002
1003 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +00001004 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +00001005 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1006 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +00001007 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001008
1009 // Store that value into the return address. Doing this with a
1010 // bitcast is likely to produce some pretty ugly IR, but it's not
1011 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +00001012 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
1013 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
1014 llvm::Value *ivarVal = load;
1015 if (ivarSize > retTySize) {
1016 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
1017 ivarVal = Builder.CreateTrunc(load, newTy);
1018 bitcastType = newTy->getPointerTo();
1019 }
1020 Builder.CreateStore(ivarVal,
1021 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +00001022
1023 // Make sure we don't do an autorelease.
1024 AutoreleaseResult = false;
1025 return;
1026 }
1027
1028 case PropertyImplStrategy::GetSetProperty: {
John McCallb92ab1a2016-10-26 23:46:34 +00001029 llvm::Constant *getPropertyFn =
John McCallf4528ae2011-09-13 03:34:09 +00001030 CGM.getObjCRuntime().GetPropertyGetFunction();
1031 if (!getPropertyFn) {
1032 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001033 return;
1034 }
John McCallb92ab1a2016-10-26 23:46:34 +00001035 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001036
1037 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1038 // FIXME: Can't this be simpler? This might even be worse than the
1039 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001040 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001041 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001042 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1043 llvm::Value *ivarOffset =
1044 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1045
1046 CallArgList args;
1047 args.add(RValue::get(self), getContext().getObjCIdType());
1048 args.add(RValue::get(cmd), getContext().getObjCSelType());
1049 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001050 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1051 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001052
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001053 // FIXME: We shouldn't need to get the function info here, the
1054 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001055 llvm::Instruction *CallInstruction;
Samuel Antao798f11c2015-11-23 22:04:44 +00001056 RValue RV = EmitCall(
John McCallc56a8b32016-03-11 04:30:31 +00001057 getTypes().arrangeBuiltinFunctionCall(propType, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001058 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001059 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1060 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001061
Daniel Dunbara08dff12008-09-24 04:04:31 +00001062 // We need to fix the type here. Ivars with copy & retain are
1063 // always objects so we don't need to worry about complex or
1064 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001065 RV = RValue::get(Builder.CreateBitCast(
1066 RV.getScalarVal(),
1067 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001068
1069 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001070
1071 // objc_getProperty does an autorelease, so we should suppress ours.
1072 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001073
John McCallf4528ae2011-09-13 03:34:09 +00001074 return;
1075 }
1076
1077 case PropertyImplStrategy::CopyStruct:
1078 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1079 strategy.hasStrongMember());
1080 return;
1081
1082 case PropertyImplStrategy::Expression:
1083 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1084 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1085
1086 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001087 switch (getEvaluationKind(ivarType)) {
1088 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001089 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001090 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001091 /*init*/ true);
1092 return;
1093 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001094 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001095 // The return value slot is guaranteed to not be aliased, but
1096 // that's not necessarily the same as "on the stack", so
1097 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001098 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smithe78fac52018-04-05 20:52:58 +00001099 /* Src= */ LV, ivarType, overlapForReturnValue());
1100 return;
1101 }
John McCall47fb9502013-03-07 21:37:08 +00001102 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001103 llvm::Value *value;
1104 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001105 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001106 } else {
1107 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1108 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001109 if (getLangOpts().ObjCAutoRefCount) {
1110 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1111 } else {
1112 value = EmitARCLoadWeak(LV.getAddress());
1113 }
John McCall24fada12011-07-22 05:23:13 +00001114
1115 // Otherwise we want to do a simple load, suppressing the
1116 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001117 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001118 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001119 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001120 }
John McCall31168b02011-06-15 23:02:42 +00001121
Alp Toker314cc812014-01-25 16:55:45 +00001122 value = Builder.CreateBitCast(
1123 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001124 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001125
John McCall24fada12011-07-22 05:23:13 +00001126 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001127 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001128 }
John McCall47fb9502013-03-07 21:37:08 +00001129 }
1130 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001131 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001132
John McCallf4528ae2011-09-13 03:34:09 +00001133 }
1134 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001135}
1136
John McCallb923ece2011-09-12 23:06:44 +00001137/// emitStructSetterCall - Call the runtime function to store the value
1138/// from the first formal parameter into the given ivar.
1139static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1140 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001141 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001142 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001143 CallArgList args;
1144
1145 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001146 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1147 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001148 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001149 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1150 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001151
1152 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001153 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001154 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1155 argVar->getType().getNonReferenceType(), VK_LValue,
1156 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001157 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001158 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1159 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001160
1161 // The third argument is the sizeof the type.
1162 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001163 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1164 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001165
John McCallb923ece2011-09-12 23:06:44 +00001166 // The fourth argument is the 'isAtomic' flag.
1167 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001168
John McCallb923ece2011-09-12 23:06:44 +00001169 // The fifth argument is the 'hasStrong' flag.
1170 // FIXME: should this really always be false?
1171 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1172
John McCallb92ab1a2016-10-26 23:46:34 +00001173 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1174 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001175 CGF.EmitCall(
1176 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001177 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001178}
1179
Fangrui Song6907ce22018-07-30 19:24:48 +00001180/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1181/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001182/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001183static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001184 ObjCMethodDecl *OMD,
1185 ObjCIvarDecl *ivar,
1186 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001187 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001188 // AtomicHelperFn);
1189 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001190
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001191 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001192 llvm::Value *ivarAddr =
1193 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001194 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001195 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1196 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001197
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001198 // The second argument is the address of the parameter variable.
1199 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001200 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1201 argVar->getType().getNonReferenceType(), VK_LValue,
1202 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001203 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001204 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1205 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001206
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001207 // Third argument is the helper function.
1208 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001209
1210 llvm::Constant *fn =
David Chisnall0d75e062012-12-17 18:54:24 +00001211 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001212 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001213 CGF.EmitCall(
1214 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001215 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001216}
1217
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001218
John McCallf4528ae2011-09-13 03:34:09 +00001219static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1220 Expr *setter = PID->getSetterCXXAssignment();
1221 if (!setter) return true;
1222
1223 // Sema only makes only of these when the ivar has a C++ class type,
1224 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001225
1226 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001227 // This also implies that there's nothing non-trivial going on with
1228 // the arguments, because operator= can only be trivial if it's a
1229 // synthesized assignment operator and therefore both parameters are
1230 // references.
1231 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001232 if (const FunctionDecl *callee
1233 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1234 if (callee->isTrivial())
1235 return true;
1236 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001237 }
John McCall7f16c422011-09-10 09:17:20 +00001238
John McCallf4528ae2011-09-13 03:34:09 +00001239 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001240 return false;
1241}
1242
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001243static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001244 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001245 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001246 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001247}
1248
John McCall7f16c422011-09-10 09:17:20 +00001249void
1250CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001251 const ObjCPropertyImplDecl *propImpl,
1252 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001253 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001254 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001255 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001256
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001257 // Just use the setter expression if Sema gave us one and it's
1258 // non-trivial.
1259 if (!hasTrivialSetExpr(propImpl)) {
1260 if (!AtomicHelperFn)
1261 // If non-atomic, assignment is called directly.
1262 EmitStmt(propImpl->getSetterCXXAssignment());
1263 else
1264 // If atomic, assignment is called via a locking api.
1265 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1266 AtomicHelperFn);
1267 return;
1268 }
John McCall7f16c422011-09-10 09:17:20 +00001269
John McCallf4528ae2011-09-13 03:34:09 +00001270 PropertyImplStrategy strategy(CGM, propImpl);
1271 switch (strategy.getKind()) {
1272 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001273 // We don't need to do anything for a zero-size struct.
1274 if (strategy.getIvarSize().isZero())
1275 return;
1276
John McCall7f416cc2015-09-08 08:05:57 +00001277 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001278
John McCallf4528ae2011-09-13 03:34:09 +00001279 LValue ivarLValue =
1280 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001281 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001282
John McCallf4528ae2011-09-13 03:34:09 +00001283 // Currently, all atomic accesses have to be through integer
1284 // types, so there's no point in trying to pick a prettier type.
1285 llvm::Type *bitcastType =
1286 llvm::Type::getIntNTy(getLLVMContext(),
1287 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001288
1289 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001290 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1291 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001292
1293 // This bitcast load is likely to cause some nasty IR.
1294 llvm::Value *load = Builder.CreateLoad(argAddr);
1295
1296 // Perform an atomic store. There are no memory ordering requirements.
1297 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001298 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001299 return;
1300 }
1301
1302 case PropertyImplStrategy::GetSetProperty:
1303 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001304
John McCallb92ab1a2016-10-26 23:46:34 +00001305 llvm::Constant *setOptimizedPropertyFn = nullptr;
1306 llvm::Constant *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001307 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001308 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001309 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001310 CGM.getObjCRuntime()
1311 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1312 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001313 if (!setOptimizedPropertyFn) {
1314 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1315 return;
1316 }
John McCall7f16c422011-09-10 09:17:20 +00001317 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001318 else {
1319 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1320 if (!setPropertyFn) {
1321 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1322 return;
1323 }
1324 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001325
John McCall7f16c422011-09-10 09:17:20 +00001326 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1327 // <is-atomic>, <is-copy>).
1328 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001329 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001330 llvm::Value *self =
1331 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1332 llvm::Value *ivarOffset =
1333 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001334 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1335 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1336 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001337
1338 CallArgList args;
1339 args.add(RValue::get(self), getContext().getObjCIdType());
1340 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001341 if (setOptimizedPropertyFn) {
1342 args.add(RValue::get(arg), getContext().getObjCIdType());
1343 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001344 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001345 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001346 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001347 } else {
1348 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1349 args.add(RValue::get(arg), getContext().getObjCIdType());
1350 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1351 getContext().BoolTy);
1352 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1353 getContext().BoolTy);
1354 // FIXME: We shouldn't need to get the function info here, the runtime
1355 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001356 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001357 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001358 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001359 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001360
John McCall7f16c422011-09-10 09:17:20 +00001361 return;
1362 }
1363
John McCallf4528ae2011-09-13 03:34:09 +00001364 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001365 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001366 return;
John McCallf4528ae2011-09-13 03:34:09 +00001367
1368 case PropertyImplStrategy::Expression:
1369 break;
John McCall7f16c422011-09-10 09:17:20 +00001370 }
1371
1372 // Otherwise, fake up some ASTs and emit a normal assignment.
1373 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001374 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001375 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001376 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1377 selfDecl->getType(), CK_LValueToRValue, &self,
1378 VK_RValue);
1379 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001380 SourceLocation(), SourceLocation(),
1381 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001382
1383 ParmVarDecl *argDecl = *setterMethod->param_begin();
1384 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001385 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1386 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001387 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1388 argType.getUnqualifiedType(), CK_LValueToRValue,
1389 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001390
John McCall7f16c422011-09-10 09:17:20 +00001391 // The property type can differ from the ivar type in some situations with
1392 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1393 // The following absurdity is just to ensure well-formed IR.
1394 CastKind argCK = CK_NoOp;
1395 if (ivarRef.getType()->isObjCObjectPointerType()) {
1396 if (argLoad.getType()->isObjCObjectPointerType())
1397 argCK = CK_BitCast;
1398 else if (argLoad.getType()->isBlockPointerType())
1399 argCK = CK_BlockPointerToObjCPointerCast;
1400 else
1401 argCK = CK_CPointerToObjCPointerCast;
1402 } else if (ivarRef.getType()->isBlockPointerType()) {
1403 if (argLoad.getType()->isBlockPointerType())
1404 argCK = CK_BitCast;
1405 else
1406 argCK = CK_AnyPointerToBlockPointerCast;
1407 } else if (ivarRef.getType()->isPointerType()) {
1408 argCK = CK_BitCast;
1409 }
1410 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1411 ivarRef.getType(), argCK, &argLoad,
1412 VK_RValue);
1413 Expr *finalArg = &argLoad;
1414 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1415 argLoad.getType()))
1416 finalArg = &argCast;
1417
1418
1419 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1420 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001421 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001422 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001423}
1424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001425/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001426///
1427/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001428/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001429void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1430 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001431 llvm::Constant *AtomicHelperFn =
1432 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001433 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1434 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1435 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001436 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001437
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001438 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001439
1440 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001441}
1442
John McCall6a4fa522011-03-22 07:05:39 +00001443namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001444 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001445 private:
1446 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001447 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001448 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001449 bool useEHCleanupForArray;
1450 public:
1451 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1452 CodeGenFunction::Destroyer *destroyer,
1453 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001454 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001455 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001456
Craig Topper4f12f102014-03-12 06:41:41 +00001457 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001458 LValue lvalue
1459 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1460 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001461 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001462 }
1463 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001464}
John McCall6a4fa522011-03-22 07:05:39 +00001465
John McCall4bd0fb12011-07-12 16:41:08 +00001466/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1467static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001468 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001469 QualType type) {
1470 llvm::Value *null = getNullForVariable(addr);
1471 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1472}
John McCall31168b02011-06-15 23:02:42 +00001473
John McCall6a4fa522011-03-22 07:05:39 +00001474static void emitCXXDestructMethod(CodeGenFunction &CGF,
1475 ObjCImplementationDecl *impl) {
1476 CodeGenFunction::RunCleanupsScope scope(CGF);
1477
1478 llvm::Value *self = CGF.LoadObjCSelf();
1479
Jordy Rosea91768e2011-07-22 02:08:32 +00001480 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1481 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001482 ivar; ivar = ivar->getNextIvar()) {
1483 QualType type = ivar->getType();
1484
John McCall6a4fa522011-03-22 07:05:39 +00001485 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001486 QualType::DestructionKind dtorKind = type.isDestructedType();
1487 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001488
Craig Topper8a13c412014-05-21 05:09:00 +00001489 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001490
John McCall4bd0fb12011-07-12 16:41:08 +00001491 // Use a call to objc_storeStrong to destroy strong ivars, for the
1492 // general benefit of the tools.
1493 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001494 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001495
John McCall4bd0fb12011-07-12 16:41:08 +00001496 // Otherwise use the default for the destruction kind.
1497 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001498 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001499 }
John McCall4bd0fb12011-07-12 16:41:08 +00001500
1501 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1502
1503 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1504 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001505 }
1506
1507 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1508}
1509
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001510void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1511 ObjCMethodDecl *MD,
1512 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001513 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001514 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001515
1516 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001517 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001518 // Suppress the final autorelease in ARC.
1519 AutoreleaseResult = false;
1520
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001521 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001522 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001523 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001524 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001525 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001526 EmitAggExpr(IvarInit->getInit(),
1527 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001528 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001529 AggValueSlot::IsNotAliased,
1530 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001531 }
1532 // constructor returns 'self'.
1533 CodeGenTypes &Types = CGM.getTypes();
1534 QualType IdTy(CGM.getContext().getObjCIdType());
1535 llvm::Value *SelfAsId =
1536 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1537 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001538
1539 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001540 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001541 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001542 }
1543 FinishFunction();
1544}
1545
Daniel Dunbara08dff12008-09-24 04:04:31 +00001546llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001547 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001548 DeclRefExpr DRE(getContext(), Self,
1549 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001550 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001551 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001552}
1553
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001554QualType CodeGenFunction::TypeOfSelfObject() {
1555 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1556 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001557 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1558 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001559 return PTy->getPointeeType();
1560}
1561
Chris Lattnerd4808922009-03-22 21:03:39 +00001562void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
John McCallb92ab1a2016-10-26 23:46:34 +00001563 llvm::Constant *EnumerationMutationFnPtr =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001564 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001565 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001566 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1567 return;
1568 }
John McCallb92ab1a2016-10-26 23:46:34 +00001569 CGCallee EnumerationMutationFn =
1570 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001571
Devang Pateld2d66652011-01-19 01:36:36 +00001572 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001573 if (DI)
1574 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001575
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001576 RunCleanupsScope ForScope(*this);
1577
Kuba Mracek82c21752017-04-14 01:00:03 +00001578 // The local variable comes into scope immediately.
1579 AutoVarEmission variable = AutoVarEmission::invalid();
1580 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1581 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1582
John McCall1c926b72011-01-07 01:49:06 +00001583 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001584
Anders Carlsson75658592008-08-31 02:33:12 +00001585 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001586 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001587 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001588 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001589
Anders Carlsson75658592008-08-31 02:33:12 +00001590 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001591 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCall1c926b72011-01-07 01:49:06 +00001593 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001594 IdentifierInfo *II[] = {
1595 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1596 &CGM.getContext().Idents.get("objects"),
1597 &CGM.getContext().Idents.get("count")
1598 };
1599 Selector FastEnumSel =
1600 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001601
1602 QualType ItemsTy =
1603 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001604 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001605 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001606 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001607
John McCall53848232011-07-27 01:07:15 +00001608 // Emit the collection pointer. In ARC, we do a retain.
1609 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001610 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001611 Collection = EmitARCRetainScalarExpr(S.getCollection());
1612
1613 // Enter a cleanup to do the release.
1614 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1615 } else {
1616 Collection = EmitScalarExpr(S.getCollection());
1617 }
Mike Stump11289f42009-09-09 15:08:12 +00001618
John McCall91e82dd2011-08-05 00:14:38 +00001619 // The 'continue' label needs to appear within the cleanup for the
1620 // collection object.
1621 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1622
John McCall1c926b72011-01-07 01:49:06 +00001623 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001624 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001625
1626 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001627 Args.add(RValue::get(StatePtr.getPointer()),
1628 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001629
John McCall1c926b72011-01-07 01:49:06 +00001630 // The second argument is a temporary array with space for NumItems
1631 // pointers. We'll actually be loading elements from the array
1632 // pointer written into the control state; this buffer is so that
1633 // collections that *aren't* backed by arrays can still queue up
1634 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001635 Args.add(RValue::get(ItemsPtr.getPointer()),
1636 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001637
John McCall1c926b72011-01-07 01:49:06 +00001638 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001639 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1640 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1641 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCall1c926b72011-01-07 01:49:06 +00001643 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001644 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001645 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1646 getContext().getNSUIntegerType(),
1647 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001648
John McCall1c926b72011-01-07 01:49:06 +00001649 // The initial number of objects that were returned in the buffer.
1650 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001651
John McCall1c926b72011-01-07 01:49:06 +00001652 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1653 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001654
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001655 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001656
John McCall1c926b72011-01-07 01:49:06 +00001657 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001658 // empty; skip all this. Set the branch weight assuming this has the same
1659 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001660 uint64_t EntryCount = getCurrentProfileCount();
1661 Builder.CreateCondBr(
1662 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1663 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001664 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001665
John McCall1c926b72011-01-07 01:49:06 +00001666 // Otherwise, initialize the loop.
1667 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001668
John McCall1c926b72011-01-07 01:49:06 +00001669 // Save the initial mutations value. This is the value at an
1670 // address that was written into the state object by
1671 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001672 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1673 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1674 llvm::Value *StateMutationsPtr
1675 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001676
John McCall1c926b72011-01-07 01:49:06 +00001677 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001678 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1679 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001680
John McCall1c926b72011-01-07 01:49:06 +00001681 // Start looping. This is the point we return to whenever we have a
1682 // fresh, non-empty batch of objects.
1683 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1684 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001685
John McCall1c926b72011-01-07 01:49:06 +00001686 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001687 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001688 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001689
John McCall1c926b72011-01-07 01:49:06 +00001690 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001691 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001692 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001693
Justin Bogner66242d62015-04-23 23:06:47 +00001694 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001695
John McCall1c926b72011-01-07 01:49:06 +00001696 // Check whether the mutations value has changed from where it was
1697 // at start. StateMutationsPtr should actually be invariant between
1698 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001699 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001700 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001701 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1702 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001703
John McCall1c926b72011-01-07 01:49:06 +00001704 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001705 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall1c926b72011-01-07 01:49:06 +00001707 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1708 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001709
John McCall1c926b72011-01-07 01:49:06 +00001710 // If so, call the enumeration-mutation function.
1711 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001712 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001713 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001714 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001715 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001716 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001717 // FIXME: We shouldn't need to get the function info here, the runtime already
1718 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001719 EmitCall(
1720 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001721 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001722
John McCall1c926b72011-01-07 01:49:06 +00001723 // Otherwise, or if the mutation function returns, just continue.
1724 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001725
John McCall1c926b72011-01-07 01:49:06 +00001726 // Initialize the element variable.
1727 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001728 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001729 LValue elementLValue;
1730 QualType elementType;
1731 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001732 // Initialize the variable, in case it's a __block variable or something.
1733 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001734
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001735 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1736 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1737 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001738 elementLValue = EmitLValue(&tempDRE);
1739 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001740 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001741
1742 if (D->isARCPseudoStrong())
1743 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001744 } else {
1745 elementLValue = LValue(); // suppress warning
1746 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001747 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001748 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001749 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001750
1751 // Fetch the buffer out of the enumeration state.
1752 // TODO: this pointer should actually be invariant between
1753 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001754 Address StateItemsPtr = Builder.CreateStructGEP(
1755 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001756 llvm::Value *EnumStateItems =
1757 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001758
John McCall1c926b72011-01-07 01:49:06 +00001759 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001760 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001761 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001762 llvm::Value *CurrentItem =
1763 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001764
John McCall1c926b72011-01-07 01:49:06 +00001765 // Cast that value to the right type.
1766 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1767 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001768
John McCall1c926b72011-01-07 01:49:06 +00001769 // Make sure we have an l-value. Yes, this gets evaluated every
1770 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001771 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001772 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001773 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001774 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001775 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1776 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001777 }
Mike Stump11289f42009-09-09 15:08:12 +00001778
John McCall9e2e22f2011-02-22 07:16:58 +00001779 // If we do have an element variable, this assignment is the end of
1780 // its initialization.
1781 if (elementIsVariable)
1782 EmitAutoVarCleanups(variable);
1783
John McCall1c926b72011-01-07 01:49:06 +00001784 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001785 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001786 {
1787 RunCleanupsScope Scope(*this);
1788 EmitStmt(S.getBody());
1789 }
Anders Carlsson75658592008-08-31 02:33:12 +00001790 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001791
John McCall1c926b72011-01-07 01:49:06 +00001792 // Destroy the element variable now.
1793 elementVariableScope.ForceCleanup();
1794
1795 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001796 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001797
John McCall1c926b72011-01-07 01:49:06 +00001798 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001799
John McCall1c926b72011-01-07 01:49:06 +00001800 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001801 llvm::Value *indexPlusOne =
1802 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001803
John McCall1c926b72011-01-07 01:49:06 +00001804 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001805 // Set the branch weights based on the simplifying assumption that this is
1806 // like a while-loop, i.e., ignoring that the false branch fetches more
1807 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001808 Builder.CreateCondBr(
1809 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001810 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001811
1812 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1813 count->addIncoming(count, AfterBody.getBlock());
1814
1815 // Otherwise, we have to fetch more elements.
1816 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001817
1818 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001819 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1820 getContext().getNSUIntegerType(),
1821 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001822
John McCall1c926b72011-01-07 01:49:06 +00001823 // If we got a zero count, we're done.
1824 llvm::Value *refetchCount = CountRV.getScalarVal();
1825
1826 // (note that the message send might split FetchMoreBB)
1827 index->addIncoming(zero, Builder.GetInsertBlock());
1828 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1829
1830 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1831 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001832
Anders Carlsson75658592008-08-31 02:33:12 +00001833 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001834 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001835
John McCall9e2e22f2011-02-22 07:16:58 +00001836 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001837 // If the element was not a declaration, set it to be null.
1838
John McCall1c926b72011-01-07 01:49:06 +00001839 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1840 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001841 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001842 }
1843
Eric Christopher7cdf9482011-10-13 21:45:18 +00001844 if (DI)
1845 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001846
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001847 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001848 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001849}
1850
Mike Stump11289f42009-09-09 15:08:12 +00001851void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001852 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001853}
1854
Mike Stump11289f42009-09-09 15:08:12 +00001855void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001856 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1857}
1858
Chris Lattnere132e242008-11-15 21:26:17 +00001859void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001860 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001861 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001862}
1863
John McCall31168b02011-06-15 23:02:42 +00001864namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001865 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001866 CallObjCRelease(llvm::Value *object) : object(object) {}
1867 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001868
Craig Topper4f12f102014-03-12 06:41:41 +00001869 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001870 // Releases at the end of the full-expression are imprecise.
1871 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001872 }
1873 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001874}
John McCall31168b02011-06-15 23:02:42 +00001875
John McCall2d637d22011-09-10 06:18:15 +00001876/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001877/// release at the end of the full-expression.
1878llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1879 llvm::Value *object) {
1880 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001881 // conditional.
1882 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001883 return object;
1884}
1885
1886llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1887 llvm::Value *value) {
1888 return EmitARCRetainAutorelease(type, value);
1889}
1890
John McCalleff18842013-03-23 02:35:54 +00001891/// Given a number of pointers, inform the optimizer that they're
1892/// being intrinsically used up until this point in the program.
1893void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
John McCallb04ecb72015-10-21 18:06:43 +00001894 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001895 if (!fn)
1896 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001897
1898 // This isn't really a "runtime" function, but as an intrinsic it
1899 // doesn't really matter as long as we align things up.
1900 EmitNounwindRuntimeCall(fn, values);
1901}
1902
Pete Cooper2cd35962018-12-18 20:33:00 +00001903static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1904 llvm::Constant *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001905 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001906 // If the target runtime doesn't naturally support ARC, emit weak
1907 // references to the runtime support library. We don't really
1908 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001909 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1910 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001911 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001912 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001913 }
John McCall31168b02011-06-15 23:02:42 +00001914}
1915
1916/// Perform an operation having the signature
1917/// i8* (i8*)
1918/// where a null input causes a no-op and returns null.
1919static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1920 llvm::Value *value,
Pete Coopere3886802018-12-08 05:13:50 +00001921 llvm::Type *returnType,
John McCall31168b02011-06-15 23:02:42 +00001922 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001923 llvm::Intrinsic::ID IntID,
Chad Rosier13799b32012-12-12 17:52:21 +00001924 bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001925 if (isa<llvm::ConstantPointerNull>(value))
1926 return value;
John McCall31168b02011-06-15 23:02:42 +00001927
1928 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001929 fn = CGF.CGM.getIntrinsic(IntID);
1930 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001931 }
1932
1933 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001934 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001935 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1936
1937 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001938 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001939 if (isTailCall)
1940 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001941
1942 // Cast the result back to the original type.
1943 return CGF.Builder.CreateBitCast(call, origType);
1944}
1945
1946/// Perform an operation having the following signature:
1947/// i8* (i8**)
1948static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001949 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001950 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001951 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00001952 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001953 fn = CGF.CGM.getIntrinsic(IntID);
1954 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001955 }
1956
1957 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001958 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001959 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1960
1961 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001962 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001963
1964 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001965 if (origType != CGF.Int8PtrTy)
1966 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001967
1968 return result;
1969}
1970
1971/// Perform an operation having the following signature:
1972/// i8* (i8**, i8*)
1973static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001974 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001975 llvm::Value *value,
1976 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001977 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00001978 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001979 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001980
1981 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001982 fn = CGF.CGM.getIntrinsic(IntID);
1983 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001984 }
1985
Chris Lattner2192fe52011-07-18 04:24:23 +00001986 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001987
John McCall882987f2013-02-28 19:01:20 +00001988 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001989 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001990 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1991 };
1992 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001993
Craig Topper8a13c412014-05-21 05:09:00 +00001994 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001995
1996 return CGF.Builder.CreateBitCast(result, origType);
1997}
1998
1999/// Perform an operation having the following signature:
2000/// void (i8**, i8**)
2001static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002002 Address dst,
2003 Address src,
John McCall31168b02011-06-15 23:02:42 +00002004 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00002005 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00002006 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00002007
2008 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002009 fn = CGF.CGM.getIntrinsic(IntID);
2010 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002011 }
2012
John McCall882987f2013-02-28 19:01:20 +00002013 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002014 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
2015 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00002016 };
2017 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002018}
2019
Pete Cooper2cd35962018-12-18 20:33:00 +00002020/// Perform an operation having the signature
2021/// i8* (i8*)
2022/// where a null input causes a no-op and returns null.
2023static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
2024 llvm::Value *value,
2025 llvm::Type *returnType,
2026 llvm::Constant *&fn,
2027 StringRef fnName) {
2028 if (isa<llvm::ConstantPointerNull>(value))
2029 return value;
2030
2031 if (!fn) {
2032 llvm::FunctionType *fnType =
2033 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2034 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
Pete Coopere5b64ea2018-12-21 21:00:32 +00002035
2036 // We have Native ARC, so set nonlazybind attribute for performance
2037 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
2038 if (fnName == "objc_retain")
2039 f->addFnAttr(llvm::Attribute::NonLazyBind);
Pete Cooper2cd35962018-12-18 20:33:00 +00002040 }
2041
2042 // Cast the argument to 'id'.
2043 llvm::Type *origType = returnType ? returnType : value->getType();
2044 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2045
2046 // Call the function.
2047 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2048
2049 // Cast the result back to the original type.
2050 return CGF.Builder.CreateBitCast(call, origType);
2051}
2052
John McCall31168b02011-06-15 23:02:42 +00002053/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002054/// call i8* \@objc_retain(i8* %value)
2055/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002056llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2057 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002058 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002059 else
2060 return EmitARCRetainNonBlock(value);
2061}
2062
2063/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002064/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002065llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002066 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002067 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002068 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002069}
2070
2071/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002072/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002073///
2074/// \param mandatory - If false, emit the call with metadata
2075/// indicating that it's okay for the optimizer to eliminate this call
2076/// if it can prove that the block never escapes except down the stack.
2077llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2078 bool mandatory) {
2079 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002080 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002081 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002082 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002083
2084 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2085 // tell the optimizer that it doesn't need to do this copy if the
2086 // block doesn't escape, where being passed as an argument doesn't
2087 // count as escaping.
2088 if (!mandatory && isa<llvm::Instruction>(result)) {
2089 llvm::CallInst *call
2090 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002091 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002092
John McCallff613032011-10-04 06:23:45 +00002093 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002094 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002095 }
2096
2097 return result;
John McCall31168b02011-06-15 23:02:42 +00002098}
2099
John McCalle399e5b2016-01-27 18:32:30 +00002100static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002101 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002102 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002103 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002104 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002105 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002106 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002107 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002108 .getARCRetainAutoreleasedReturnValueMarker();
2109
2110 // If we have an empty assembly string, there's nothing to do.
2111 if (assembly.empty()) {
2112
2113 // Otherwise, at -O0, build an inline asm that we're going to call
2114 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002115 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002116 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002117 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002118
John McCall31168b02011-06-15 23:02:42 +00002119 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2120
2121 // If we're at -O1 and above, we don't want to litter the code
2122 // with this marker yet, so leave a breadcrumb for the ARC
2123 // optimizer to pick up.
2124 } else {
2125 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002126 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002127 "clang.arc.retainAutoreleasedReturnValueMarker");
2128 assert(metadata->getNumOperands() <= 1);
2129 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002130 auto &ctx = CGF.getLLVMContext();
2131 metadata->addOperand(llvm::MDNode::get(ctx,
2132 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002133 }
2134 }
2135 }
2136
2137 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002138 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002139 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002140}
John McCall31168b02011-06-15 23:02:42 +00002141
John McCalle399e5b2016-01-27 18:32:30 +00002142/// Retain the given object which is the result of a function call.
2143/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2144///
2145/// Yes, this function name is one character away from a different
2146/// call with completely different semantics.
2147llvm::Value *
2148CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2149 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002150 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002151 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002152 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
John McCall31168b02011-06-15 23:02:42 +00002153}
2154
John McCalle399e5b2016-01-27 18:32:30 +00002155/// Claim a possibly-autoreleased return value at +0. This is only
2156/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002157/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002158/// the value is ignored, or when it is being assigned to an
2159/// __unsafe_unretained variable.
2160///
2161/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2162llvm::Value *
2163CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2164 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002165 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002166 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002167 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002168}
2169
John McCall31168b02011-06-15 23:02:42 +00002170/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002171/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002172void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2173 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002174 if (isa<llvm::ConstantPointerNull>(value)) return;
2175
John McCallb04ecb72015-10-21 18:06:43 +00002176 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002177 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002178 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2179 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002180 }
2181
2182 // Cast the argument to 'id'.
2183 value = Builder.CreateBitCast(value, Int8PtrTy);
2184
2185 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002186 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002187
John McCallcdda29c2013-03-13 03:10:54 +00002188 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002189 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002190 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002191 }
2192}
2193
John McCalle68b8f42012-10-17 02:28:37 +00002194/// Destroy a __strong variable.
2195///
2196/// At -O0, emit a call to store 'null' into the address;
2197/// instrumenting tools prefer this because the address is exposed,
2198/// but it's relatively cumbersome to optimize.
2199///
2200/// At -O1 and above, just load and call objc_release.
2201///
2202/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002203void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002204 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002205 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002206 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002207 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2208 return;
2209 }
2210
2211 llvm::Value *value = Builder.CreateLoad(addr);
2212 EmitARCRelease(value, precise);
2213}
2214
John McCall31168b02011-06-15 23:02:42 +00002215/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002216/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002217llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002218 llvm::Value *value,
2219 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002220 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002221
John McCallb04ecb72015-10-21 18:06:43 +00002222 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002223 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002224 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2225 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002226 }
2227
John McCall882987f2013-02-28 19:01:20 +00002228 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002229 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002230 Builder.CreateBitCast(value, Int8PtrTy)
2231 };
2232 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002233
Craig Topper8a13c412014-05-21 05:09:00 +00002234 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002235 return value;
2236}
2237
2238/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002239/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002240/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002241llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002242 llvm::Value *newValue,
2243 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002244 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002245 bool isBlock = type->isBlockPointerType();
2246
2247 // Use a store barrier at -O0 unless this is a block type or the
2248 // lvalue is inadequately aligned.
2249 if (shouldUseFusedARCCalls() &&
2250 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002251 (dst.getAlignment().isZero() ||
2252 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002253 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2254 }
2255
2256 // Otherwise, split it out.
2257
2258 // Retain the new value.
2259 newValue = EmitARCRetain(type, newValue);
2260
2261 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002262 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002263
2264 // Store. We do this before the release so that any deallocs won't
2265 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002266 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002267
2268 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002269 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002270
2271 return newValue;
2272}
2273
2274/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002275/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002276llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002277 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002278 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002279 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002280}
2281
2282/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002283/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002284llvm::Value *
2285CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002286 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002287 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002288 llvm::Intrinsic::objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002289 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002290}
2291
2292/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002293/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002294llvm::Value *
2295CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002296 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002297 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002298 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002299 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002300}
2301
2302/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002303/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002304/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002305/// %retain = call i8* \@objc_retainBlock(i8* %value)
2306/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002307llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2308 llvm::Value *value) {
2309 if (!type->isBlockPointerType())
2310 return EmitARCRetainAutoreleaseNonBlock(value);
2311
2312 if (isa<llvm::ConstantPointerNull>(value)) return value;
2313
Chris Lattner2192fe52011-07-18 04:24:23 +00002314 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002315 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002316 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002317 value = EmitARCAutorelease(value);
2318 return Builder.CreateBitCast(value, origType);
2319}
2320
2321/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002322/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002323llvm::Value *
2324CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002325 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002326 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002327 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002328}
2329
John McCallb04ecb72015-10-21 18:06:43 +00002330/// i8* \@objc_loadWeak(i8** %addr)
2331/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2332llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2333 return emitARCLoadOperation(*this, addr,
2334 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002335 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002336}
2337
James Dennett14c41ea2012-06-22 05:41:30 +00002338/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002339llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002340 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002341 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002342 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002343}
2344
James Dennett14c41ea2012-06-22 05:41:30 +00002345/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002346/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002347llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002348 llvm::Value *value,
2349 bool ignored) {
2350 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002351 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002352 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002353}
2354
James Dennett14c41ea2012-06-22 05:41:30 +00002355/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002356/// Returns %value. %addr is known to not have a current weak entry.
2357/// Essentially equivalent to:
2358/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002359void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002360 // If we're initializing to null, just write null to memory; no need
2361 // to get the runtime involved. But don't do this if optimization
2362 // is enabled, because accounting for this would make the optimizer
2363 // much more complicated.
2364 if (isa<llvm::ConstantPointerNull>(value) &&
2365 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2366 Builder.CreateStore(value, addr);
2367 return;
2368 }
2369
2370 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002371 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002372 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002373}
2374
James Dennett14c41ea2012-06-22 05:41:30 +00002375/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002376/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002377void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCallb04ecb72015-10-21 18:06:43 +00002378 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002379 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002380 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2381 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002382 }
2383
2384 // Cast the argument to 'id*'.
2385 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2386
John McCall7f416cc2015-09-08 08:05:57 +00002387 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002388}
2389
James Dennett14c41ea2012-06-22 05:41:30 +00002390/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002391/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2392/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002393void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002394 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002395 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002396 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002397}
2398
James Dennett14c41ea2012-06-22 05:41:30 +00002399/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002400/// Disregards the current value in %dest. Essentially
2401/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002402void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002403 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002404 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002405 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002406}
2407
Akira Hatanakad791e922018-03-19 17:38:40 +00002408void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2409 Address SrcAddr) {
2410 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2411 Object = EmitObjCConsumeObject(Ty, Object);
2412 EmitARCStoreWeak(DstAddr, Object, false);
2413}
2414
2415void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2416 Address SrcAddr) {
2417 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2418 Object = EmitObjCConsumeObject(Ty, Object);
2419 EmitARCStoreWeak(DstAddr, Object, false);
2420 EmitARCDestroyWeak(SrcAddr);
2421}
2422
John McCall31168b02011-06-15 23:02:42 +00002423/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002424/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002425llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
John McCallb04ecb72015-10-21 18:06:43 +00002426 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002427 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002428 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2429 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002430 }
2431
John McCall882987f2013-02-28 19:01:20 +00002432 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002433}
2434
2435/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002436/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002437void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2438 assert(value->getType() == Int8PtrTy);
2439
Pete Cooper2cd35962018-12-18 20:33:00 +00002440 if (getInvokeDest()) {
2441 // Call the runtime method not the intrinsic if we are handling exceptions
2442 llvm::Constant *&fn =
2443 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2444 if (!fn) {
2445 llvm::FunctionType *fnType =
2446 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2447 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2448 setARCRuntimeFunctionLinkage(CGM, fn);
2449 }
John McCall31168b02011-06-15 23:02:42 +00002450
Pete Cooper2cd35962018-12-18 20:33:00 +00002451 // objc_autoreleasePoolPop can throw.
2452 EmitRuntimeCallOrInvoke(fn, value);
2453 } else {
2454 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2455 if (!fn) {
2456 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2457 setARCRuntimeFunctionLinkage(CGM, fn);
2458 }
2459
2460 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002461 }
John McCall31168b02011-06-15 23:02:42 +00002462}
2463
2464/// Produce the code to do an MRR version objc_autoreleasepool_push.
2465/// Which is: [[NSAutoreleasePool alloc] init];
2466/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2467/// init is declared as: - (id) init; in its NSObject super class.
2468///
2469llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2470 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002471 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002472 // [NSAutoreleasePool alloc]
2473 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2474 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2475 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002476 RValue AllocRV =
2477 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002478 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002479 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002480
2481 // [Receiver init]
2482 Receiver = AllocRV.getScalarVal();
2483 II = &CGM.getContext().Idents.get("init");
2484 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2485 RValue InitRV =
2486 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2487 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002488 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002489 return InitRV.getScalarVal();
2490}
2491
Pete Coopere3886802018-12-08 05:13:50 +00002492/// Allocate the given objc object.
2493/// call i8* \@objc_alloc(i8* %value)
2494llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2495 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002496 return emitObjCValueOperation(*this, value, resultType,
2497 CGM.getObjCEntrypoints().objc_alloc,
2498 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002499}
2500
2501/// Allocate the given objc object.
2502/// call i8* \@objc_allocWithZone(i8* %value)
2503llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2504 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002505 return emitObjCValueOperation(*this, value, resultType,
2506 CGM.getObjCEntrypoints().objc_allocWithZone,
2507 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002508}
2509
John McCall31168b02011-06-15 23:02:42 +00002510/// Produce the code to do a primitive release.
2511/// [tmp drain];
2512void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2513 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2514 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2515 CallArgList Args;
2516 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002517 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002518}
2519
John McCall82fe67b2011-07-09 01:37:26 +00002520void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002521 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002522 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002523 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002524}
2525
2526void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002527 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002528 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002529 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002530}
2531
2532void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002533 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002534 QualType type) {
2535 CGF.EmitARCDestroyWeak(addr);
2536}
2537
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002538void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2539 QualType type) {
2540 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2541 CGF.EmitARCIntrinsicUse(value);
2542}
2543
Pete Coopere5b64ea2018-12-21 21:00:32 +00002544/// Autorelease the given object.
2545/// call i8* \@objc_autorelease(i8* %value)
2546llvm::Value *CodeGenFunction::EmitObjCAutorelease(llvm::Value *value,
2547 llvm::Type *returnType) {
2548 return emitObjCValueOperation(*this, value, returnType,
2549 CGM.getObjCEntrypoints().objc_autoreleaseRuntimeFunction,
2550 "objc_autorelease");
2551}
2552
2553/// Retain the given object, with normal retain semantics.
2554/// call i8* \@objc_retain(i8* %value)
2555llvm::Value *CodeGenFunction::EmitObjCRetainNonBlock(llvm::Value *value,
2556 llvm::Type *returnType) {
2557 return emitObjCValueOperation(*this, value, returnType,
2558 CGM.getObjCEntrypoints().objc_retainRuntimeFunction,
2559 "objc_retain");
2560}
2561
2562/// Release the given object.
2563/// call void \@objc_release(i8* %value)
2564void CodeGenFunction::EmitObjCRelease(llvm::Value *value,
2565 ARCPreciseLifetime_t precise) {
2566 if (isa<llvm::ConstantPointerNull>(value)) return;
2567
2568 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
2569 if (!fn) {
2570 if (!fn) {
2571 llvm::FunctionType *fnType =
2572 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2573 fn = CGM.CreateRuntimeFunction(fnType, "objc_release");
2574 setARCRuntimeFunctionLinkage(CGM, fn);
2575 // We have Native ARC, so set nonlazybind attribute for performance
2576 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
2577 f->addFnAttr(llvm::Attribute::NonLazyBind);
2578 }
2579 }
2580
2581 // Cast the argument to 'id'.
2582 value = Builder.CreateBitCast(value, Int8PtrTy);
2583
2584 // Call objc_release.
2585 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
2586
2587 if (precise == ARCImpreciseLifetime) {
2588 call->setMetadata("clang.imprecise_release",
2589 llvm::MDNode::get(Builder.getContext(), None));
2590 }
2591}
2592
John McCall31168b02011-06-15 23:02:42 +00002593namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002594 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002595 llvm::Value *Token;
2596
2597 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2598
Craig Topper4f12f102014-03-12 06:41:41 +00002599 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002600 CGF.EmitObjCAutoreleasePoolPop(Token);
2601 }
2602 };
David Blaikie7e70d682015-08-18 22:40:54 +00002603 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002604 llvm::Value *Token;
2605
2606 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2607
Craig Topper4f12f102014-03-12 06:41:41 +00002608 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002609 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2610 }
2611 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002612}
John McCall31168b02011-06-15 23:02:42 +00002613
2614void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002615 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002616 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2617 else
2618 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2619}
2620
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002621static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2622 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002623 case Qualifiers::OCL_None:
2624 case Qualifiers::OCL_ExplicitNone:
2625 case Qualifiers::OCL_Strong:
2626 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002627 return true;
John McCall31168b02011-06-15 23:02:42 +00002628
2629 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002630 return false;
John McCall31168b02011-06-15 23:02:42 +00002631 }
2632
2633 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002634}
2635
2636static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002637 LValue lvalue,
2638 QualType type) {
2639 llvm::Value *result;
2640 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2641 if (shouldRetain) {
2642 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2643 } else {
2644 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2645 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2646 }
2647 return TryEmitResult(result, !shouldRetain);
2648}
2649
2650static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002651 const Expr *e) {
2652 e = e->IgnoreParens();
2653 QualType type = e->getType();
2654
Fangrui Song6907ce22018-07-30 19:24:48 +00002655 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002656 // an extra retain/release pair by zeroing out the source of this
2657 // "move" operation.
2658 if (e->isXValue() &&
2659 !type.isConstQualified() &&
2660 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2661 // Emit the lvalue.
2662 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002663
John McCall154a2fd2011-08-30 00:57:29 +00002664 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002665 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2666 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002667
John McCall154a2fd2011-08-30 00:57:29 +00002668 // Set the source pointer to NULL.
2669 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002670
John McCall154a2fd2011-08-30 00:57:29 +00002671 return TryEmitResult(result, true);
2672 }
2673
John McCall31168b02011-06-15 23:02:42 +00002674 // As a very special optimization, in ARC++, if the l-value is the
2675 // result of a non-volatile assignment, do a simple retain of the
2676 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002677 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002678 !type.isVolatileQualified() &&
2679 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2680 isa<BinaryOperator>(e) &&
2681 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2682 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2683
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002684 // Try to emit code for scalar constant instead of emitting LValue and
2685 // loading it because we are not guaranteed to have an l-value. One of such
2686 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2687 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2688 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2689 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2690 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2691 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2692 }
2693
John McCall31168b02011-06-15 23:02:42 +00002694 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2695}
2696
John McCalle399e5b2016-01-27 18:32:30 +00002697typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2698 llvm::Value *value)>
2699 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002700
John McCalle399e5b2016-01-27 18:32:30 +00002701/// Insert code immediately after a call.
2702static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2703 llvm::Value *value,
2704 ValueTransform doAfterCall,
2705 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002706 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2707 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2708
2709 // Place the retain immediately following the call.
2710 CGF.Builder.SetInsertPoint(call->getParent(),
2711 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002712 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002713
2714 CGF.Builder.restoreIP(ip);
2715 return value;
2716 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2717 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2718
2719 // Place the retain at the beginning of the normal destination block.
2720 llvm::BasicBlock *BB = invoke->getNormalDest();
2721 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002722 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002723
2724 CGF.Builder.restoreIP(ip);
2725 return value;
2726
2727 // Bitcasts can arise because of related-result returns. Rewrite
2728 // the operand.
2729 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2730 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002731 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002732 bitcast->setOperand(0, operand);
2733 return bitcast;
2734
2735 // Generic fall-back case.
2736 } else {
2737 // Retain using the non-block variant: we never need to do a copy
2738 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002739 return doFallback(CGF, value);
2740 }
2741}
2742
2743/// Given that the given expression is some sort of call (which does
2744/// not return retained), emit a retain following it.
2745static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2746 const Expr *e) {
2747 llvm::Value *value = CGF.EmitScalarExpr(e);
2748 return emitARCOperationAfterCall(CGF, value,
2749 [](CodeGenFunction &CGF, llvm::Value *value) {
2750 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2751 },
2752 [](CodeGenFunction &CGF, llvm::Value *value) {
2753 return CGF.EmitARCRetainNonBlock(value);
2754 });
2755}
2756
2757/// Given that the given expression is some sort of call (which does
2758/// not return retained), perform an unsafeClaim following it.
2759static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2760 const Expr *e) {
2761 llvm::Value *value = CGF.EmitScalarExpr(e);
2762 return emitARCOperationAfterCall(CGF, value,
2763 [](CodeGenFunction &CGF, llvm::Value *value) {
2764 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2765 },
2766 [](CodeGenFunction &CGF, llvm::Value *value) {
2767 return value;
2768 });
2769}
2770
2771llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2772 bool allowUnsafeClaim) {
2773 if (allowUnsafeClaim &&
2774 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2775 return emitARCUnsafeClaimCallResult(*this, E);
2776 } else {
2777 llvm::Value *value = emitARCRetainCallResult(*this, E);
2778 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002779 }
2780}
2781
John McCallcd78e802011-09-10 01:16:55 +00002782/// Determine whether it might be important to emit a separate
2783/// objc_retain_block on the result of the given expression, or
2784/// whether it's okay to just emit it in a +1 context.
2785static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2786 assert(e->getType()->isBlockPointerType());
2787 e = e->IgnoreParens();
2788
2789 // For future goodness, emit block expressions directly in +1
2790 // contexts if we can.
2791 if (isa<BlockExpr>(e))
2792 return false;
2793
2794 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2795 switch (cast->getCastKind()) {
2796 // Emitting these operations in +1 contexts is goodness.
2797 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002798 case CK_ARCReclaimReturnedObject:
2799 case CK_ARCConsumeObject:
2800 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002801 return false;
2802
2803 // These operations preserve a block type.
2804 case CK_NoOp:
2805 case CK_BitCast:
2806 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2807
2808 // These operations are known to be bad (or haven't been considered).
2809 case CK_AnyPointerToBlockPointerCast:
2810 default:
2811 return true;
2812 }
2813 }
2814
2815 return true;
2816}
2817
John McCalle399e5b2016-01-27 18:32:30 +00002818namespace {
2819/// A CRTP base class for emitting expressions of retainable object
2820/// pointer type in ARC.
2821template <typename Impl, typename Result> class ARCExprEmitter {
2822protected:
2823 CodeGenFunction &CGF;
2824 Impl &asImpl() { return *static_cast<Impl*>(this); }
2825
2826 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2827
2828public:
2829 Result visit(const Expr *e);
2830 Result visitCastExpr(const CastExpr *e);
2831 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2832 Result visitBinaryOperator(const BinaryOperator *e);
2833 Result visitBinAssign(const BinaryOperator *e);
2834 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2835 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2836 Result visitBinAssignWeak(const BinaryOperator *e);
2837 Result visitBinAssignStrong(const BinaryOperator *e);
2838
2839 // Minimal implementation:
2840 // Result visitLValueToRValue(const Expr *e)
2841 // Result visitConsumeObject(const Expr *e)
2842 // Result visitExtendBlockObject(const Expr *e)
2843 // Result visitReclaimReturnedObject(const Expr *e)
2844 // Result visitCall(const Expr *e)
2845 // Result visitExpr(const Expr *e)
2846 //
2847 // Result emitBitCast(Result result, llvm::Type *resultType)
2848 // llvm::Value *getValueOfResult(Result result)
2849};
2850}
2851
2852/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002853///
2854/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002855template <typename Impl, typename Result>
2856Result
2857ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002858 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002859
2860 // Find the result expression.
2861 const Expr *resultExpr = E->getResultExpr();
2862 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002863 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002864
2865 for (PseudoObjectExpr::const_semantics_iterator
2866 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2867 const Expr *semantic = *i;
2868
2869 // If this semantic expression is an opaque value, bind it
2870 // to the result of its source expression.
2871 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2872 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2873 OVMA opaqueData;
2874
2875 // If this semantic is the result of the pseudo-object
2876 // expression, try to evaluate the source as +1.
2877 if (ov == resultExpr) {
2878 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002879 result = asImpl().visit(ov->getSourceExpr());
2880 opaqueData = OVMA::bind(CGF, ov,
2881 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002882
2883 // Otherwise, just bind it.
2884 } else {
2885 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2886 }
2887 opaques.push_back(opaqueData);
2888
2889 // Otherwise, if the expression is the result, evaluate it
2890 // and remember the result.
2891 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002892 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002893
2894 // Otherwise, evaluate the expression in an ignored context.
2895 } else {
2896 CGF.EmitIgnoredExpr(semantic);
2897 }
2898 }
2899
2900 // Unbind all the opaques now.
2901 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2902 opaques[i].unbind(CGF);
2903
2904 return result;
2905}
2906
John McCalle399e5b2016-01-27 18:32:30 +00002907template <typename Impl, typename Result>
2908Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2909 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002910
John McCalle399e5b2016-01-27 18:32:30 +00002911 // No-op casts don't change the type, so we just ignore them.
2912 case CK_NoOp:
2913 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002914
John McCalle399e5b2016-01-27 18:32:30 +00002915 // These casts can change the type.
2916 case CK_CPointerToObjCPointerCast:
2917 case CK_BlockPointerToObjCPointerCast:
2918 case CK_AnyPointerToBlockPointerCast:
2919 case CK_BitCast: {
2920 llvm::Type *resultType = CGF.ConvertType(e->getType());
2921 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2922 Result result = asImpl().visit(e->getSubExpr());
2923 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002924 }
2925
John McCalle399e5b2016-01-27 18:32:30 +00002926 // Handle some casts specially.
2927 case CK_LValueToRValue:
2928 return asImpl().visitLValueToRValue(e->getSubExpr());
2929 case CK_ARCConsumeObject:
2930 return asImpl().visitConsumeObject(e->getSubExpr());
2931 case CK_ARCExtendBlockObject:
2932 return asImpl().visitExtendBlockObject(e->getSubExpr());
2933 case CK_ARCReclaimReturnedObject:
2934 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2935
2936 // Otherwise, use the default logic.
2937 default:
2938 return asImpl().visitExpr(e);
2939 }
2940}
2941
2942template <typename Impl, typename Result>
2943Result
2944ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2945 switch (e->getOpcode()) {
2946 case BO_Comma:
2947 CGF.EmitIgnoredExpr(e->getLHS());
2948 CGF.EnsureInsertPoint();
2949 return asImpl().visit(e->getRHS());
2950
2951 case BO_Assign:
2952 return asImpl().visitBinAssign(e);
2953
2954 default:
2955 return asImpl().visitExpr(e);
2956 }
2957}
2958
2959template <typename Impl, typename Result>
2960Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2961 switch (e->getLHS()->getType().getObjCLifetime()) {
2962 case Qualifiers::OCL_ExplicitNone:
2963 return asImpl().visitBinAssignUnsafeUnretained(e);
2964
2965 case Qualifiers::OCL_Weak:
2966 return asImpl().visitBinAssignWeak(e);
2967
2968 case Qualifiers::OCL_Autoreleasing:
2969 return asImpl().visitBinAssignAutoreleasing(e);
2970
2971 case Qualifiers::OCL_Strong:
2972 return asImpl().visitBinAssignStrong(e);
2973
2974 case Qualifiers::OCL_None:
2975 return asImpl().visitExpr(e);
2976 }
2977 llvm_unreachable("bad ObjC ownership qualifier");
2978}
2979
2980/// The default rule for __unsafe_unretained emits the RHS recursively,
2981/// stores into the unsafe variable, and propagates the result outward.
2982template <typename Impl, typename Result>
2983Result ARCExprEmitter<Impl,Result>::
2984 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2985 // Recursively emit the RHS.
2986 // For __block safety, do this before emitting the LHS.
2987 Result result = asImpl().visit(e->getRHS());
2988
2989 // Perform the store.
2990 LValue lvalue =
2991 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2992 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2993 lvalue);
2994
2995 return result;
2996}
2997
2998template <typename Impl, typename Result>
2999Result
3000ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
3001 return asImpl().visitExpr(e);
3002}
3003
3004template <typename Impl, typename Result>
3005Result
3006ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
3007 return asImpl().visitExpr(e);
3008}
3009
3010template <typename Impl, typename Result>
3011Result
3012ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
3013 return asImpl().visitExpr(e);
3014}
3015
3016/// The general expression-emission logic.
3017template <typename Impl, typename Result>
3018Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
3019 // We should *never* see a nested full-expression here, because if
3020 // we fail to emit at +1, our caller must not retain after we close
3021 // out the full-expression. This isn't as important in the unsafe
3022 // emitter.
3023 assert(!isa<ExprWithCleanups>(e));
3024
3025 // Look through parens, __extension__, generic selection, etc.
3026 e = e->IgnoreParens();
3027
3028 // Handle certain kinds of casts.
3029 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
3030 return asImpl().visitCastExpr(ce);
3031
3032 // Handle the comma operator.
3033 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
3034 return asImpl().visitBinaryOperator(op);
3035
3036 // TODO: handle conditional operators here
3037
3038 // For calls and message sends, use the retained-call logic.
3039 // Delegate inits are a special case in that they're the only
3040 // returns-retained expression that *isn't* surrounded by
3041 // a consume.
3042 } else if (isa<CallExpr>(e) ||
3043 (isa<ObjCMessageExpr>(e) &&
3044 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
3045 return asImpl().visitCall(e);
3046
3047 // Look through pseudo-object expressions.
3048 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
3049 return asImpl().visitPseudoObjectExpr(pseudo);
3050 }
3051
3052 return asImpl().visitExpr(e);
3053}
3054
3055namespace {
3056
3057/// An emitter for +1 results.
3058struct ARCRetainExprEmitter :
3059 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
3060
3061 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3062
3063 llvm::Value *getValueOfResult(TryEmitResult result) {
3064 return result.getPointer();
3065 }
3066
3067 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
3068 llvm::Value *value = result.getPointer();
3069 value = CGF.Builder.CreateBitCast(value, resultType);
3070 result.setPointer(value);
3071 return result;
3072 }
3073
3074 TryEmitResult visitLValueToRValue(const Expr *e) {
3075 return tryEmitARCRetainLoadOfScalar(CGF, e);
3076 }
3077
3078 /// For consumptions, just emit the subexpression and thus elide
3079 /// the retain/release pair.
3080 TryEmitResult visitConsumeObject(const Expr *e) {
3081 llvm::Value *result = CGF.EmitScalarExpr(e);
3082 return TryEmitResult(result, true);
3083 }
3084
3085 /// Block extends are net +0. Naively, we could just recurse on
3086 /// the subexpression, but actually we need to ensure that the
3087 /// value is copied as a block, so there's a little filter here.
3088 TryEmitResult visitExtendBlockObject(const Expr *e) {
3089 llvm::Value *result; // will be a +0 value
3090
3091 // If we can't safely assume the sub-expression will produce a
3092 // block-copied value, emit the sub-expression at +0.
3093 if (shouldEmitSeparateBlockRetain(e)) {
3094 result = CGF.EmitScalarExpr(e);
3095
3096 // Otherwise, try to emit the sub-expression at +1 recursively.
3097 } else {
3098 TryEmitResult subresult = asImpl().visit(e);
3099
3100 // If that produced a retained value, just use that.
3101 if (subresult.getInt()) {
3102 return subresult;
3103 }
3104
3105 // Otherwise it's +0.
3106 result = subresult.getPointer();
3107 }
3108
3109 // Retain the object as a block.
3110 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3111 return TryEmitResult(result, true);
3112 }
3113
3114 /// For reclaims, emit the subexpression as a retained call and
3115 /// skip the consumption.
3116 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3117 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3118 return TryEmitResult(result, true);
3119 }
3120
3121 /// When we have an undecorated call, retroactively do a claim.
3122 TryEmitResult visitCall(const Expr *e) {
3123 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3124 return TryEmitResult(result, true);
3125 }
3126
3127 // TODO: maybe special-case visitBinAssignWeak?
3128
3129 TryEmitResult visitExpr(const Expr *e) {
3130 // We didn't find an obvious production, so emit what we've got and
3131 // tell the caller that we didn't manage to retain.
3132 llvm::Value *result = CGF.EmitScalarExpr(e);
3133 return TryEmitResult(result, false);
3134 }
3135};
3136}
3137
3138static TryEmitResult
3139tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3140 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003141}
3142
3143static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3144 LValue lvalue,
3145 QualType type) {
3146 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3147 llvm::Value *value = result.getPointer();
3148 if (!result.getInt())
3149 value = CGF.EmitARCRetain(type, value);
3150 return value;
3151}
3152
3153/// EmitARCRetainScalarExpr - Semantically equivalent to
3154/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3155/// best-effort attempt to peephole expressions that naturally produce
3156/// retained objects.
3157llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003158 // The retain needs to happen within the full-expression.
3159 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3160 enterFullExpression(cleanups);
3161 RunCleanupsScope scope(*this);
3162 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3163 }
3164
John McCall31168b02011-06-15 23:02:42 +00003165 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3166 llvm::Value *value = result.getPointer();
3167 if (!result.getInt())
3168 value = EmitARCRetain(e->getType(), value);
3169 return value;
3170}
3171
3172llvm::Value *
3173CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003174 // The retain needs to happen within the full-expression.
3175 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3176 enterFullExpression(cleanups);
3177 RunCleanupsScope scope(*this);
3178 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3179 }
3180
John McCall31168b02011-06-15 23:02:42 +00003181 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3182 llvm::Value *value = result.getPointer();
3183 if (result.getInt())
3184 value = EmitARCAutorelease(value);
3185 else
3186 value = EmitARCRetainAutorelease(e->getType(), value);
3187 return value;
3188}
3189
John McCallff613032011-10-04 06:23:45 +00003190llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3191 llvm::Value *result;
3192 bool doRetain;
3193
3194 if (shouldEmitSeparateBlockRetain(e)) {
3195 result = EmitScalarExpr(e);
3196 doRetain = true;
3197 } else {
3198 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3199 result = subresult.getPointer();
3200 doRetain = !subresult.getInt();
3201 }
3202
3203 if (doRetain)
3204 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3205 return EmitObjCConsumeObject(e->getType(), result);
3206}
3207
John McCall248512a2011-10-01 10:32:24 +00003208llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3209 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003210 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003211 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003212 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003213 return EmitARCRetainAutoreleaseScalarExpr(expr);
3214 }
3215
3216 // Otherwise, use the normal scalar-expression emission. The
3217 // exception machinery doesn't do anything special with the
3218 // exception like retaining it, so there's no safety associated with
3219 // only running cleanups after the throw has started, and when it
3220 // matters it tends to be substantially inferior code.
3221 return EmitScalarExpr(expr);
3222}
3223
John McCalle399e5b2016-01-27 18:32:30 +00003224namespace {
3225
3226/// An emitter for assigning into an __unsafe_unretained context.
3227struct ARCUnsafeUnretainedExprEmitter :
3228 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3229
3230 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3231
3232 llvm::Value *getValueOfResult(llvm::Value *value) {
3233 return value;
3234 }
3235
3236 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3237 return CGF.Builder.CreateBitCast(value, resultType);
3238 }
3239
3240 llvm::Value *visitLValueToRValue(const Expr *e) {
3241 return CGF.EmitScalarExpr(e);
3242 }
3243
3244 /// For consumptions, just emit the subexpression and perform the
3245 /// consumption like normal.
3246 llvm::Value *visitConsumeObject(const Expr *e) {
3247 llvm::Value *value = CGF.EmitScalarExpr(e);
3248 return CGF.EmitObjCConsumeObject(e->getType(), value);
3249 }
3250
3251 /// No special logic for block extensions. (This probably can't
3252 /// actually happen in this emitter, though.)
3253 llvm::Value *visitExtendBlockObject(const Expr *e) {
3254 return CGF.EmitARCExtendBlockObject(e);
3255 }
3256
3257 /// For reclaims, perform an unsafeClaim if that's enabled.
3258 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3259 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3260 }
3261
3262 /// When we have an undecorated call, just emit it without adding
3263 /// the unsafeClaim.
3264 llvm::Value *visitCall(const Expr *e) {
3265 return CGF.EmitScalarExpr(e);
3266 }
3267
3268 /// Just do normal scalar emission in the default case.
3269 llvm::Value *visitExpr(const Expr *e) {
3270 return CGF.EmitScalarExpr(e);
3271 }
3272};
3273}
3274
3275static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3276 const Expr *e) {
3277 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3278}
3279
3280/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3281/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3282/// avoiding any spurious retains, including by performing reclaims
3283/// with objc_unsafeClaimAutoreleasedReturnValue.
3284llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3285 // Look through full-expressions.
3286 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3287 enterFullExpression(cleanups);
3288 RunCleanupsScope scope(*this);
3289 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3290 }
3291
3292 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3293}
3294
3295std::pair<LValue,llvm::Value*>
3296CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3297 bool ignored) {
3298 // Evaluate the RHS first. If we're ignoring the result, assume
3299 // that we can emit at an unsafe +0.
3300 llvm::Value *value;
3301 if (ignored) {
3302 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3303 } else {
3304 value = EmitScalarExpr(e->getRHS());
3305 }
3306
3307 // Emit the LHS and perform the store.
3308 LValue lvalue = EmitLValue(e->getLHS());
3309 EmitStoreOfScalar(value, lvalue);
3310
3311 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3312}
3313
John McCall31168b02011-06-15 23:02:42 +00003314std::pair<LValue,llvm::Value*>
3315CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3316 bool ignored) {
3317 // Evaluate the RHS first.
3318 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3319 llvm::Value *value = result.getPointer();
3320
John McCallb726a552011-07-28 07:23:35 +00003321 bool hasImmediateRetain = result.getInt();
3322
3323 // If we didn't emit a retained object, and the l-value is of block
3324 // type, then we need to emit the block-retain immediately in case
3325 // it invalidates the l-value.
3326 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003327 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003328 hasImmediateRetain = true;
3329 }
3330
John McCall31168b02011-06-15 23:02:42 +00003331 LValue lvalue = EmitLValue(e->getLHS());
3332
3333 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003334 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003335 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003336 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003337 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003338 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003339 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003340 }
3341
3342 return std::pair<LValue,llvm::Value*>(lvalue, value);
3343}
3344
3345std::pair<LValue,llvm::Value*>
3346CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3347 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3348 LValue lvalue = EmitLValue(e->getLHS());
3349
Eli Friedmana0544d62011-12-03 04:14:32 +00003350 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003351
3352 return std::pair<LValue,llvm::Value*>(lvalue, value);
3353}
3354
3355void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003356 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003357 const Stmt *subStmt = ARPS.getSubStmt();
3358 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3359
3360 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003361 if (DI)
3362 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003363
3364 // Keep track of the current cleanup stack depth.
3365 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003366 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003367 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3368 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3369 } else {
3370 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3371 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3372 }
3373
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003374 for (const auto *I : S.body())
3375 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003376
Eric Christopher7cdf9482011-10-13 21:45:18 +00003377 if (DI)
3378 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003379}
John McCall1bd25562011-06-24 23:21:27 +00003380
3381/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3382/// make sure it survives garbage collection until this point.
3383void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3384 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003385 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003386 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00003387 llvm::Value *extender
3388 = llvm::InlineAsm::get(extenderType,
3389 /* assembly */ "",
3390 /* constraints */ "r",
3391 /* side effects */ true);
3392
3393 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003394 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003395}
3396
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003397/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003398/// non-trivial copy assignment function, produce following helper function.
3399/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3400///
3401llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003402CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3403 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003404 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003405 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003406 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003407 QualType Ty = PID->getPropertyIvarDecl()->getType();
3408 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003409 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003410 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003411 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003412 return nullptr;
3413 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003414 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003415 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003416 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3417 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3418 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003419
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003420 ASTContext &C = getContext();
3421 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003422 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003423
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003424 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003425 QualType DestTy = C.getPointerType(Ty);
3426 QualType SrcTy = Ty;
3427 SrcTy.addConst();
3428 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003429
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003430 SmallVector<QualType, 2> ArgTys;
3431 ArgTys.push_back(DestTy);
3432 ArgTys.push_back(SrcTy);
3433 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3434
3435 FunctionDecl *FD = FunctionDecl::Create(
3436 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3437 FunctionTy, nullptr, SC_Static, false, false);
3438
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003439 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003440 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3441 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003442 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003443 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3444 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003445 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003446
John McCallc56a8b32016-03-11 04:30:31 +00003447 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003448 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003449
John McCalla729c622012-02-17 03:33:10 +00003450 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003451
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003452 llvm::Function *Fn =
3453 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003454 "__assign_helper_atomic_property_",
3455 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003456
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003457 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003458
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003459 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003460
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003461 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3462 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003463 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003464 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003465
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003466 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3467 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003468 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003469 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003470
John McCall113bee02012-03-10 09:33:50 +00003471 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003472 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003473 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3474 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3475 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003476
Bruno Riccic5885cf2018-12-21 15:20:32 +00003477 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003478
3479 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003480 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003481 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003482 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003483}
3484
3485llvm::Constant *
3486CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3487 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003488 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003489 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003490 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003491 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3492 QualType Ty = PD->getType();
3493 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003494 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003495 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003496 return nullptr;
3497 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003498 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003499 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003500 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3501 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3502 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003503
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003504 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003505 IdentifierInfo *II =
3506 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003507
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003508 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003509 QualType DestTy = C.getPointerType(Ty);
3510 QualType SrcTy = Ty;
3511 SrcTy.addConst();
3512 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003513
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003514 SmallVector<QualType, 2> ArgTys;
3515 ArgTys.push_back(DestTy);
3516 ArgTys.push_back(SrcTy);
3517 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3518
3519 FunctionDecl *FD = FunctionDecl::Create(
3520 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3521 FunctionTy, nullptr, SC_Static, false, false);
3522
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003523 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003524 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3525 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003526 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003527 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3528 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003529 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003530
John McCallc56a8b32016-03-11 04:30:31 +00003531 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003532 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003533
John McCalla729c622012-02-17 03:33:10 +00003534 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003535
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003536 llvm::Function *Fn = llvm::Function::Create(
3537 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3538 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003539
3540 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003541
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003542 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003543
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003544 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3545 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003546
John McCall113bee02012-03-10 09:33:50 +00003547 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003548 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003549
3550 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003551 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003552
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003553 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003554 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003555 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3556 CXXConstExpr->arg_end());
3557
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003558 CXXConstructExpr *TheCXXConstructExpr =
3559 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3560 CXXConstExpr->getConstructor(),
3561 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003562 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003563 CXXConstExpr->hadMultipleCandidates(),
3564 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003565 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003566 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003567 CXXConstExpr->getConstructionKind(),
3568 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003569
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003570 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3571 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003572
John McCall113bee02012-03-10 09:33:50 +00003573 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003574 CharUnits Alignment
3575 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003576 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003577 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3578 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003579 AggValueSlot::IsDestructed,
3580 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003581 AggValueSlot::IsNotAliased,
3582 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003583
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003584 FinishFunction();
3585 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3586 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3587 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003588}
3589
Eli Friedmanec75fec2012-02-28 01:08:45 +00003590llvm::Value *
3591CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3592 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003593 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3594 Selector CopySelector =
3595 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003596 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3597 Selector AutoreleaseSelector =
3598 getContext().Selectors.getNullarySelector(AutoreleaseID);
3599
3600 // Emit calls to retain/autorelease.
3601 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3602 llvm::Value *Val = Block;
3603 RValue Result;
3604 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003605 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003606 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003607 Val = Result.getScalarVal();
3608 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3609 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003610 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003611 Val = Result.getScalarVal();
3612 return Val;
3613}
3614
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003615llvm::Value *
3616CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3617 assert(Args.size() == 3 && "Expected 3 argument here!");
3618
3619 if (!CGM.IsOSVersionAtLeastFn) {
3620 llvm::FunctionType *FTy =
3621 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3622 CGM.IsOSVersionAtLeastFn =
3623 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3624 }
3625
3626 llvm::Value *CallRes =
3627 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3628
3629 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3630}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003631
Alex Lorenza8fbef42017-03-23 11:14:27 +00003632void CodeGenModule::emitAtAvailableLinkGuard() {
3633 if (!IsOSVersionAtLeastFn)
3634 return;
3635 // @available requires CoreFoundation only on Darwin.
3636 if (!Target.getTriple().isOSDarwin())
3637 return;
3638 // Add -framework CoreFoundation to the linker commands. We still want to
3639 // emit the core foundation reference down below because otherwise if
3640 // CoreFoundation is not used in the code, the linker won't link the
3641 // framework.
3642 auto &Context = getLLVMContext();
3643 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3644 llvm::MDString::get(Context, "CoreFoundation")};
3645 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3646 // Emit a reference to a symbol from CoreFoundation to ensure that
3647 // CoreFoundation is linked into the final binary.
3648 llvm::FunctionType *FTy =
3649 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3650 llvm::Constant *CFFunc =
3651 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3652
3653 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3654 llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3655 CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3656 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3657 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3658 CodeGenFunction CGF(*this);
3659 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3660 CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3661 CGF.Builder.CreateUnreachable();
3662 addCompilerUsedGlobal(CFLinkCheckFunc);
3663}
3664
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003665CGObjCRuntime::~CGObjCRuntime() {}