blob: 4cc86ad0946eecbf968c83f435f12d59998a83f6 [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,
373 const ObjCMethodDecl *method) {
374 auto &CGM = CGF.CGM;
375 if (!CGM.getCodeGenOpts().ObjCConvertMessagesToRuntimeCalls)
376 return None;
377
378 auto &Runtime = CGM.getLangOpts().ObjCRuntime;
379 switch (Sel.getMethodFamily()) {
380 case OMF_alloc:
381 if (Runtime.shouldUseRuntimeFunctionsForAlloc() &&
382 ResultType->isObjCObjectPointerType()) {
383 // [Foo alloc] -> objc_alloc(Foo)
384 if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "alloc")
385 return CGF.EmitObjCAlloc(Receiver, CGF.ConvertType(ResultType));
386 // [Foo allocWithZone:nil] -> objc_allocWithZone(Foo)
387 if (Sel.isKeywordSelector() && Sel.getNumArgs() == 1 &&
388 Args.size() == 1 && Args.front().getType()->isPointerType() &&
389 Sel.getNameForSlot(0) == "allocWithZone") {
390 const llvm::Value* arg = Args.front().getKnownRValue().getScalarVal();
391 if (isa<llvm::ConstantPointerNull>(arg))
392 return CGF.EmitObjCAllocWithZone(Receiver,
393 CGF.ConvertType(ResultType));
394 return None;
395 }
396 }
397 break;
398
399 default:
400 break;
401 }
402 return None;
403}
404
John McCall78a15112010-05-22 01:48:05 +0000405RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
406 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000407 // Only the lookup mechanism and first two arguments of the method
408 // implementation vary between runtimes. We can get the receiver and
409 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000410
John McCall31168b02011-06-15 23:02:42 +0000411 bool isDelegateInit = E->isDelegateInitCall();
412
John McCallcf166702011-07-22 08:53:00 +0000413 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000414
John McCall460ce582015-10-22 18:38:17 +0000415 // If the method is -retain, and the receiver's being loaded from
416 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
417 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
418 method->getMethodFamily() == OMF_retain) {
419 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
420 LValue lvalue = EmitLValue(lvalueExpr);
421 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
422 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
423 }
424 }
425
John McCall31168b02011-06-15 23:02:42 +0000426 // We don't retain the receiver in delegate init calls, and this is
427 // safe because the receiver value is always loaded from 'self',
428 // which we zero out. We don't want to Block_copy block receivers,
429 // though.
430 bool retainSelf =
431 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000432 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000433 method &&
434 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000435
Daniel Dunbar8d480592008-08-11 18:12:00 +0000436 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000437 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000438 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000439 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000440 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000441 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000442 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000443 switch (E->getReceiverKind()) {
444 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000445 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000446 if (retainSelf) {
447 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
448 E->getInstanceReceiver());
449 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000450 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000451 } else
452 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000453 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000454
Douglas Gregor9a129192010-04-21 00:45:42 +0000455 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000456 ReceiverType = E->getClassReceiver();
457 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000458 assert(ObjTy && "Invalid Objective-C class message send");
459 OID = ObjTy->getInterface();
460 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000461 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000462 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000463 break;
464 }
465
466 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000467 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000468 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000469 isSuperMessage = true;
470 break;
471
472 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000473 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000474 Receiver = LoadObjCSelf();
475 isSuperMessage = true;
476 isClassMessage = true;
477 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000478 }
479
John McCallcf166702011-07-22 08:53:00 +0000480 if (retainSelf)
481 Receiver = EmitARCRetainNonBlock(Receiver);
482
483 // In ARC, we sometimes want to "extend the lifetime"
484 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
485 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000486 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000487 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
488 shouldExtendReceiverForInnerPointerMessage(E))
489 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
490
Alp Toker314cc812014-01-25 16:55:45 +0000491 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000492
Daniel Dunbarc722b852008-08-30 03:02:31 +0000493 CallArgList Args;
Vedant Kumared00ea02017-03-06 05:28:22 +0000494 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump11289f42009-09-09 15:08:12 +0000495
John McCall31168b02011-06-15 23:02:42 +0000496 // For delegate init calls in ARC, do an unsafe store of null into
497 // self. This represents the call taking direct ownership of that
498 // value. We have to do this after emitting the other call
499 // arguments because they might also reference self, but we don't
500 // have to worry about any of them modifying self because that would
501 // be an undefined read and write of an object in unordered
502 // expressions.
503 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000504 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000505 "delegate init calls should only be marked in ARC");
506
507 // Do an unsafe store of null into self.
John McCall7f416cc2015-09-08 08:05:57 +0000508 Address selfAddr =
509 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000510 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
511 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000512
Douglas Gregor33823722011-06-11 01:09:30 +0000513 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000514 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000515 // super is only valid in an Objective-C method
516 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000517 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000518 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
519 E->getSelector(),
520 OMD->getClassInterface(),
521 isCategoryImpl,
522 Receiver,
523 isClassMessage,
524 Args,
John McCallcf166702011-07-22 08:53:00 +0000525 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000526 } else {
Pete Coopere3886802018-12-08 05:13:50 +0000527 // Call runtime methods directly if we can.
528 if (Optional<llvm::Value *> SpecializedResult =
529 tryGenerateSpecializedMessageSend(*this, ResultType, Receiver, Args,
530 E->getSelector(), method)) {
531 result = RValue::get(SpecializedResult.getValue());
532 } else {
533 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
534 E->getSelector(), Receiver, Args,
535 OID, method);
536 }
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000537 }
John McCall31168b02011-06-15 23:02:42 +0000538
539 // For delegate init calls in ARC, implicitly store the result of
540 // the call back into self. This takes ownership of the value.
541 if (isDelegateInit) {
John McCall7f416cc2015-09-08 08:05:57 +0000542 Address selfAddr =
543 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCall31168b02011-06-15 23:02:42 +0000544 llvm::Value *newSelf = result.getScalarVal();
545
546 // The delegate return type isn't necessarily a matching type; in
547 // fact, it's quite likely to be 'id'.
John McCall7f416cc2015-09-08 08:05:57 +0000548 llvm::Type *selfTy = selfAddr.getElementType();
John McCall31168b02011-06-15 23:02:42 +0000549 newSelf = Builder.CreateBitCast(newSelf, selfTy);
550
551 Builder.CreateStore(newSelf, selfAddr);
552 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000553
Douglas Gregore83b9562015-07-07 03:57:53 +0000554 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000555}
556
John McCall31168b02011-06-15 23:02:42 +0000557namespace {
David Blaikie7e70d682015-08-18 22:40:54 +0000558struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000559 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000560 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000561
562 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000563 const ObjCInterfaceDecl *iface = impl->getClassInterface();
564 if (!iface->getSuperClass()) return;
565
John McCalldffafde2011-07-13 18:26:47 +0000566 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
567
John McCall31168b02011-06-15 23:02:42 +0000568 // Call [super dealloc] if we have a superclass.
569 llvm::Value *self = CGF.LoadObjCSelf();
570
571 CallArgList args;
572 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
573 CGF.getContext().VoidTy,
574 method->getSelector(),
575 iface,
John McCalldffafde2011-07-13 18:26:47 +0000576 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000577 self,
578 /*is class msg*/ false,
579 args,
580 method);
581 }
582};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000583}
John McCall31168b02011-06-15 23:02:42 +0000584
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000585/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
586/// the LLVM function and sets the other context used by
587/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000588void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000589 const ObjCContainerDecl *CD) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000590 SourceLocation StartLoc = OMD->getBeginLoc();
John McCalla738c252011-03-09 04:27:21 +0000591 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000592 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000593 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000594 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000595
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000596 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000597
John McCalla729c622012-02-17 03:33:10 +0000598 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000599 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000600
John McCalla738c252011-03-09 04:27:21 +0000601 args.push_back(OMD->getSelfDecl());
602 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000603
Benjamin Kramerf9890422015-02-17 16:48:30 +0000604 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000605
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000606 CurGD = OMD;
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000607 CurEHLocation = OMD->getEndLoc();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000608
Adrian Prantl42d71b92014-04-10 23:21:53 +0000609 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
610 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000611
612 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000613 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000614 OMD->isInstanceMethod() &&
615 OMD->getSelector().isUnarySelector()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000616 const IdentifierInfo *ident =
John McCall31168b02011-06-15 23:02:42 +0000617 OMD->getSelector().getIdentifierInfoForSlot(0);
618 if (ident->isStr("dealloc"))
619 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
620 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000621}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000622
John McCall31168b02011-06-15 23:02:42 +0000623static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
624 LValue lvalue, QualType type);
625
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000626/// Generate an Objective-C method. An Objective-C method is a C function with
Raphael Isemannb23ccec2018-12-10 12:37:46 +0000627/// its pointer, name, and types registered in the class structure.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000628void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000629 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a561452015-12-06 14:32:39 +0000630 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000631 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogner66242d62015-04-23 23:06:47 +0000632 incrementProfileCounter(OMD->getBody());
Adrian Prantl56741e22014-01-07 22:05:55 +0000633 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000634 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000635}
636
John McCallb923ece2011-09-12 23:06:44 +0000637/// emitStructGetterCall - Call the runtime function to load a property
638/// into the return value slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000639static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
John McCallb923ece2011-09-12 23:06:44 +0000640 bool isAtomic, bool hasStrong) {
641 ASTContext &Context = CGF.getContext();
642
John McCall7f416cc2015-09-08 08:05:57 +0000643 Address src =
644 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
645 .getAddress();
John McCallb923ece2011-09-12 23:06:44 +0000646
Fangrui Song6907ce22018-07-30 19:24:48 +0000647 // objc_copyStruct (ReturnValue, &structIvar,
John McCallb923ece2011-09-12 23:06:44 +0000648 // sizeof (Type of Ivar), isAtomic, false);
649 CallArgList args;
650
John McCall7f416cc2015-09-08 08:05:57 +0000651 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
652 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000653
654 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCall7f416cc2015-09-08 08:05:57 +0000655 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCallb923ece2011-09-12 23:06:44 +0000656
657 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
658 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
659 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
660 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
661
John McCallb92ab1a2016-10-26 23:46:34 +0000662 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
663 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +0000664 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000665 callee, ReturnValueSlot(), args);
John McCallb923ece2011-09-12 23:06:44 +0000666}
667
John McCallf4528ae2011-09-13 03:34:09 +0000668/// Determine whether the given architecture supports unaligned atomic
669/// accesses. They don't have to be fast, just faster than a function
670/// call and a mutex.
671static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000672 // FIXME: Allow unaligned atomic load/store on x86. (It is not
673 // currently supported by the backend.)
674 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000675}
676
677/// Return the maximum size that permits atomic accesses for the given
678/// architecture.
679static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
680 llvm::Triple::ArchType arch) {
681 // ARM has 8-byte atomic accesses, but it's not clear whether we
682 // want to rely on them here.
683
684 // In the default case, just assume that any size up to a pointer is
685 // fine given adequate alignment.
686 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
687}
688
689namespace {
690 class PropertyImplStrategy {
691 public:
692 enum StrategyKind {
693 /// The 'native' strategy is to use the architecture's provided
694 /// reads and writes.
695 Native,
696
697 /// Use objc_setProperty and objc_getProperty.
698 GetSetProperty,
699
700 /// Use objc_setProperty for the setter, but use expression
701 /// evaluation for the getter.
702 SetPropertyAndExpressionGet,
703
704 /// Use objc_copyStruct.
705 CopyStruct,
706
707 /// The 'expression' strategy is to emit normal assignment or
708 /// lvalue-to-rvalue expressions.
709 Expression
710 };
711
712 StrategyKind getKind() const { return StrategyKind(Kind); }
713
714 bool hasStrongMember() const { return HasStrong; }
715 bool isAtomic() const { return IsAtomic; }
716 bool isCopy() const { return IsCopy; }
717
718 CharUnits getIvarSize() const { return IvarSize; }
719 CharUnits getIvarAlignment() const { return IvarAlignment; }
720
721 PropertyImplStrategy(CodeGenModule &CGM,
722 const ObjCPropertyImplDecl *propImpl);
723
724 private:
725 unsigned Kind : 8;
726 unsigned IsAtomic : 1;
727 unsigned IsCopy : 1;
728 unsigned HasStrong : 1;
729
730 CharUnits IvarSize;
731 CharUnits IvarAlignment;
732 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000733}
John McCallf4528ae2011-09-13 03:34:09 +0000734
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000735/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000736PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
737 const ObjCPropertyImplDecl *propImpl) {
738 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000739 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000740
John McCall43192862011-09-13 18:31:23 +0000741 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
742 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000743 HasStrong = false; // doesn't matter here.
744
745 // Evaluate the ivar's size and alignment.
746 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
747 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000748 std::tie(IvarSize, IvarAlignment) =
749 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000750
751 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000752 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000753 if (IsCopy) {
754 Kind = GetSetProperty;
755 return;
756 }
757
John McCall43192862011-09-13 18:31:23 +0000758 // Handle retain.
759 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000760 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000761 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000762 // fallthrough
763
764 // In ARC, if the property is non-atomic, use expression emission,
765 // which translates to objc_storeStrong. This isn't required, but
766 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000767 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000768 // Using standard expression emission for the setter is only
769 // acceptable if the ivar is __strong, which won't be true if
770 // the property is annotated with __attribute__((NSObject)).
771 // TODO: falling all the way back to objc_setProperty here is
772 // just laziness, though; we could still use objc_storeStrong
773 // if we hacked it right.
774 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
775 Kind = Expression;
776 else
777 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000778 return;
779
780 // Otherwise, we need to at least use setProperty. However, if
781 // the property isn't atomic, we can use normal expression
782 // emission for the getter.
783 } else if (!IsAtomic) {
784 Kind = SetPropertyAndExpressionGet;
785 return;
786
787 // Otherwise, we have to use both setProperty and getProperty.
788 } else {
789 Kind = GetSetProperty;
790 return;
791 }
792 }
793
794 // If we're not atomic, just use expression accesses.
795 if (!IsAtomic) {
796 Kind = Expression;
797 return;
798 }
799
John McCall0e5c0862011-09-13 05:36:29 +0000800 // Properties on bitfield ivars need to be emitted using expression
801 // accesses even if they're nominally atomic.
802 if (ivar->isBitField()) {
803 Kind = Expression;
804 return;
805 }
806
John McCallf4528ae2011-09-13 03:34:09 +0000807 // GC-qualified or ARC-qualified ivars need to be emitted as
808 // expressions. This actually works out to being atomic anyway,
809 // except for ARC __strong, but that should trigger the above code.
810 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000811 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000812 CGM.getContext().getObjCGCAttrKind(ivarType))) {
813 Kind = Expression;
814 return;
815 }
816
817 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000818 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000819 if (const RecordType *recordType = ivarType->getAs<RecordType>())
820 HasStrong = recordType->getDecl()->hasObjectMember();
821
822 // We can never access structs with object members with a native
823 // access, because we need to use write barriers. This is what
824 // objc_copyStruct is for.
825 if (HasStrong) {
826 Kind = CopyStruct;
827 return;
828 }
829
830 // Otherwise, this is target-dependent and based on the size and
831 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000832
833 // If the size of the ivar is not a power of two, give up. We don't
834 // want to get into the business of doing compare-and-swaps.
835 if (!IvarSize.isPowerOfTwo()) {
836 Kind = CopyStruct;
837 return;
838 }
839
John McCallf4528ae2011-09-13 03:34:09 +0000840 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000841 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000842
843 // Most architectures require memory to fit within a single cache
844 // line, so the alignment has to be at least the size of the access.
845 // Otherwise we have to grab a lock.
846 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
847 Kind = CopyStruct;
848 return;
849 }
850
851 // If the ivar's size exceeds the architecture's maximum atomic
852 // access size, we have to use CopyStruct.
853 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
854 Kind = CopyStruct;
855 return;
856 }
857
858 // Otherwise, we can use native loads and stores.
859 Kind = Native;
860}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000862/// Generate an Objective-C property getter function.
James Dennettbe302452012-06-15 22:10:14 +0000863///
864/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000865/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000866void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
867 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000868 llvm::Constant *AtomicHelperFn =
869 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000870 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
871 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
872 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000873 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000874
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000875 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000876
877 FinishFunction();
878}
879
John McCallbdd81852011-09-13 06:00:03 +0000880static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
881 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000882 if (!getter) return true;
883
884 // Sema only makes only of these when the ivar has a C++ class type,
885 // so the form is pretty constrained.
886
John McCallbdd81852011-09-13 06:00:03 +0000887 // If the property has a reference type, we might just be binding a
888 // reference, in which case the result will be a gl-value. We should
889 // treat this as a non-trivial operation.
890 if (getter->isGLValue())
891 return false;
892
John McCallf4528ae2011-09-13 03:34:09 +0000893 // If we selected a trivial copy-constructor, we're okay.
894 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
895 return (construct->getConstructor()->isTrivial());
896
897 // The constructor might require cleanups (in which case it's never
898 // trivial).
899 assert(isa<ExprWithCleanups>(getter));
900 return false;
901}
902
Fangrui Song6907ce22018-07-30 19:24:48 +0000903/// emitCPPObjectAtomicGetterCall - Call the runtime function to
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000904/// copy the ivar into the resturn slot.
Fangrui Song6907ce22018-07-30 19:24:48 +0000905static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000906 llvm::Value *returnAddr,
907 ObjCIvarDecl *ivar,
908 llvm::Constant *AtomicHelperFn) {
909 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
910 // AtomicHelperFn);
911 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +0000912
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000913 // The 1st argument is the return Slot.
914 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000915
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000916 // The 2nd argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +0000917 llvm::Value *ivarAddr =
918 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +0000919 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000920 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
921 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000922
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000923 // Third argument is the helper function.
924 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +0000925
926 llvm::Constant *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000927 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +0000928 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCallc56a8b32016-03-11 04:30:31 +0000929 CGF.EmitCall(
930 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +0000931 callee, ReturnValueSlot(), args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000932}
933
John McCallf4528ae2011-09-13 03:34:09 +0000934void
935CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000936 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000937 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000938 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000939 // If there's a non-trivial 'get' expression, we just have to emit that.
940 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000941 if (!AtomicHelperFn) {
Bruno Ricci023b1d12018-10-30 14:40:49 +0000942 auto *ret = ReturnStmt::Create(getContext(), SourceLocation(),
943 propImpl->getGetterCXXConstructor(),
944 /* NRVOCandidate=*/nullptr);
945 EmitReturnStmt(*ret);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000946 }
947 else {
948 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +0000949 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000950 ivar, AtomicHelperFn);
951 }
John McCallf4528ae2011-09-13 03:34:09 +0000952 return;
953 }
954
955 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
956 QualType propType = prop->getType();
957 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
958
Fangrui Song6907ce22018-07-30 19:24:48 +0000959 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4528ae2011-09-13 03:34:09 +0000960
961 // Pick an implementation strategy.
962 PropertyImplStrategy strategy(CGM, propImpl);
963 switch (strategy.getKind()) {
964 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000965 // We don't need to do anything for a zero-size struct.
966 if (strategy.getIvarSize().isZero())
967 return;
968
John McCallf4528ae2011-09-13 03:34:09 +0000969 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
970
971 // Currently, all atomic accesses have to be through integer
972 // types, so there's no point in trying to pick a prettier type.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000973 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
974 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCallf4528ae2011-09-13 03:34:09 +0000975 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
976
977 // Perform an atomic load. This does not impose ordering constraints.
John McCall7f416cc2015-09-08 08:05:57 +0000978 Address ivarAddr = LV.getAddress();
John McCallf4528ae2011-09-13 03:34:09 +0000979 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
980 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastien92f4ef12016-04-06 17:26:42 +0000981 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +0000982
983 // Store that value into the return address. Doing this with a
984 // bitcast is likely to produce some pretty ugly IR, but it's not
985 // the *most* terrible thing in the world.
Akira Hatanakade6f25f2016-05-26 00:37:30 +0000986 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
987 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
988 llvm::Value *ivarVal = load;
989 if (ivarSize > retTySize) {
990 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
991 ivarVal = Builder.CreateTrunc(load, newTy);
992 bitcastType = newTy->getPointerTo();
993 }
994 Builder.CreateStore(ivarVal,
995 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCallf4528ae2011-09-13 03:34:09 +0000996
997 // Make sure we don't do an autorelease.
998 AutoreleaseResult = false;
999 return;
1000 }
1001
1002 case PropertyImplStrategy::GetSetProperty: {
John McCallb92ab1a2016-10-26 23:46:34 +00001003 llvm::Constant *getPropertyFn =
John McCallf4528ae2011-09-13 03:34:09 +00001004 CGM.getObjCRuntime().GetPropertyGetFunction();
1005 if (!getPropertyFn) {
1006 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001007 return;
1008 }
John McCallb92ab1a2016-10-26 23:46:34 +00001009 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001010
1011 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
1012 // FIXME: Can't this be simpler? This might even be worse than the
1013 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +00001014 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001015 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCallf4528ae2011-09-13 03:34:09 +00001016 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1017 llvm::Value *ivarOffset =
1018 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1019
1020 CallArgList args;
1021 args.add(RValue::get(self), getContext().getObjCIdType());
1022 args.add(RValue::get(cmd), getContext().getObjCSelType());
1023 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +00001024 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1025 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +00001026
Daniel Dunbar1ef73732009-02-03 23:43:59 +00001027 // FIXME: We shouldn't need to get the function info here, the
1028 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001029 llvm::Instruction *CallInstruction;
Samuel Antao798f11c2015-11-23 22:04:44 +00001030 RValue RV = EmitCall(
John McCallc56a8b32016-03-11 04:30:31 +00001031 getTypes().arrangeBuiltinFunctionCall(propType, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001032 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian13b43042014-01-30 00:16:39 +00001033 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
1034 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +00001035
Daniel Dunbara08dff12008-09-24 04:04:31 +00001036 // We need to fix the type here. Ivars with copy & retain are
1037 // always objects so we don't need to worry about complex or
1038 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +00001039 RV = RValue::get(Builder.CreateBitCast(
1040 RV.getScalarVal(),
1041 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +00001042
1043 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +00001044
1045 // objc_getProperty does an autorelease, so we should suppress ours.
1046 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +00001047
John McCallf4528ae2011-09-13 03:34:09 +00001048 return;
1049 }
1050
1051 case PropertyImplStrategy::CopyStruct:
1052 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
1053 strategy.hasStrongMember());
1054 return;
1055
1056 case PropertyImplStrategy::Expression:
1057 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1058 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1059
1060 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +00001061 switch (getEvaluationKind(ivarType)) {
1062 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001063 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001064 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall47fb9502013-03-07 21:37:08 +00001065 /*init*/ true);
1066 return;
1067 }
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001068 case TEK_Aggregate: {
John McCallf4528ae2011-09-13 03:34:09 +00001069 // The return value slot is guaranteed to not be aliased, but
1070 // that's not necessarily the same as "on the stack", so
1071 // we still potentially need objc_memmove_collectable.
Ivan A. Kosarev1860b522018-01-25 14:21:55 +00001072 EmitAggregateCopy(/* Dest= */ MakeAddrLValue(ReturnValue, ivarType),
Richard Smithe78fac52018-04-05 20:52:58 +00001073 /* Src= */ LV, ivarType, overlapForReturnValue());
1074 return;
1075 }
John McCall47fb9502013-03-07 21:37:08 +00001076 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +00001077 llvm::Value *value;
1078 if (propType->isReferenceType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001079 value = LV.getAddress().getPointer();
John McCall24fada12011-07-22 05:23:13 +00001080 } else {
1081 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1082 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001083 if (getLangOpts().ObjCAutoRefCount) {
1084 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1085 } else {
1086 value = EmitARCLoadWeak(LV.getAddress());
1087 }
John McCall24fada12011-07-22 05:23:13 +00001088
1089 // Otherwise we want to do a simple load, suppressing the
1090 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +00001091 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001092 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +00001093 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00001094 }
John McCall31168b02011-06-15 23:02:42 +00001095
Alp Toker314cc812014-01-25 16:55:45 +00001096 value = Builder.CreateBitCast(
1097 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +00001098 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001099
John McCall24fada12011-07-22 05:23:13 +00001100 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +00001101 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +00001102 }
John McCall47fb9502013-03-07 21:37:08 +00001103 }
1104 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +00001105 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001106
John McCallf4528ae2011-09-13 03:34:09 +00001107 }
1108 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001109}
1110
John McCallb923ece2011-09-12 23:06:44 +00001111/// emitStructSetterCall - Call the runtime function to store the value
1112/// from the first formal parameter into the given ivar.
1113static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1114 ObjCIvarDecl *ivar) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001115 // objc_copyStruct (&structIvar, &Arg,
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001116 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +00001117 CallArgList args;
1118
1119 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +00001120 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1121 CGF.LoadObjCSelf(), ivar, 0)
John McCall7f416cc2015-09-08 08:05:57 +00001122 .getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001123 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1124 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001125
1126 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +00001127 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001128 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1129 argVar->getType().getNonReferenceType(), VK_LValue,
1130 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001131 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCallb923ece2011-09-12 23:06:44 +00001132 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1133 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +00001134
1135 // The third argument is the sizeof the type.
1136 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +00001137 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1138 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +00001139
John McCallb923ece2011-09-12 23:06:44 +00001140 // The fourth argument is the 'isAtomic' flag.
1141 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001142
John McCallb923ece2011-09-12 23:06:44 +00001143 // The fifth argument is the 'hasStrong' flag.
1144 // FIXME: should this really always be false?
1145 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1146
John McCallb92ab1a2016-10-26 23:46:34 +00001147 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1148 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001149 CGF.EmitCall(
1150 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001151 callee, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001152}
1153
Fangrui Song6907ce22018-07-30 19:24:48 +00001154/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1155/// the value from the first formal parameter into the given ivar, using
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001156/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
Fangrui Song6907ce22018-07-30 19:24:48 +00001157static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001158 ObjCMethodDecl *OMD,
1159 ObjCIvarDecl *ivar,
1160 llvm::Constant *AtomicHelperFn) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001161 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001162 // AtomicHelperFn);
1163 CallArgList args;
Fangrui Song6907ce22018-07-30 19:24:48 +00001164
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001165 // The first argument is the address of the ivar.
Fangrui Song6907ce22018-07-30 19:24:48 +00001166 llvm::Value *ivarAddr =
1167 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCall7f416cc2015-09-08 08:05:57 +00001168 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001169 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1170 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001171
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001172 // The second argument is the address of the parameter variable.
1173 ParmVarDecl *argVar = *OMD->param_begin();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001174 DeclRefExpr argRef(CGF.getContext(), argVar, false,
1175 argVar->getType().getNonReferenceType(), VK_LValue,
1176 SourceLocation());
John McCall7f416cc2015-09-08 08:05:57 +00001177 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001178 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1179 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001180
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001181 // Third argument is the helper function.
1182 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00001183
1184 llvm::Constant *fn =
David Chisnall0d75e062012-12-17 18:54:24 +00001185 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001186 CGCallee callee = CGCallee::forDirect(fn);
John McCallc56a8b32016-03-11 04:30:31 +00001187 CGF.EmitCall(
1188 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001189 callee, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001190}
1191
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001192
John McCallf4528ae2011-09-13 03:34:09 +00001193static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1194 Expr *setter = PID->getSetterCXXAssignment();
1195 if (!setter) return true;
1196
1197 // Sema only makes only of these when the ivar has a C++ class type,
1198 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001199
1200 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001201 // This also implies that there's nothing non-trivial going on with
1202 // the arguments, because operator= can only be trivial if it's a
1203 // synthesized assignment operator and therefore both parameters are
1204 // references.
1205 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001206 if (const FunctionDecl *callee
1207 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1208 if (callee->isTrivial())
1209 return true;
1210 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001211 }
John McCall7f16c422011-09-10 09:17:20 +00001212
John McCallf4528ae2011-09-13 03:34:09 +00001213 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001214 return false;
1215}
1216
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001217static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001218 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001219 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001220 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001221}
1222
John McCall7f16c422011-09-10 09:17:20 +00001223void
1224CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001225 const ObjCPropertyImplDecl *propImpl,
1226 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001227 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001228 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001229 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001230
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001231 // Just use the setter expression if Sema gave us one and it's
1232 // non-trivial.
1233 if (!hasTrivialSetExpr(propImpl)) {
1234 if (!AtomicHelperFn)
1235 // If non-atomic, assignment is called directly.
1236 EmitStmt(propImpl->getSetterCXXAssignment());
1237 else
1238 // If atomic, assignment is called via a locking api.
1239 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1240 AtomicHelperFn);
1241 return;
1242 }
John McCall7f16c422011-09-10 09:17:20 +00001243
John McCallf4528ae2011-09-13 03:34:09 +00001244 PropertyImplStrategy strategy(CGM, propImpl);
1245 switch (strategy.getKind()) {
1246 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001247 // We don't need to do anything for a zero-size struct.
1248 if (strategy.getIvarSize().isZero())
1249 return;
1250
John McCall7f416cc2015-09-08 08:05:57 +00001251 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall7f16c422011-09-10 09:17:20 +00001252
John McCallf4528ae2011-09-13 03:34:09 +00001253 LValue ivarLValue =
1254 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCall7f416cc2015-09-08 08:05:57 +00001255 Address ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001256
John McCallf4528ae2011-09-13 03:34:09 +00001257 // Currently, all atomic accesses have to be through integer
1258 // types, so there's no point in trying to pick a prettier type.
1259 llvm::Type *bitcastType =
1260 llvm::Type::getIntNTy(getLLVMContext(),
1261 getContext().toBits(strategy.getIvarSize()));
John McCallf4528ae2011-09-13 03:34:09 +00001262
1263 // Cast both arguments to the chosen operation type.
John McCall7f416cc2015-09-08 08:05:57 +00001264 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1265 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCallf4528ae2011-09-13 03:34:09 +00001266
1267 // This bitcast load is likely to cause some nasty IR.
1268 llvm::Value *load = Builder.CreateLoad(argAddr);
1269
1270 // Perform an atomic store. There are no memory ordering requirements.
1271 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastien92f4ef12016-04-06 17:26:42 +00001272 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCallf4528ae2011-09-13 03:34:09 +00001273 return;
1274 }
1275
1276 case PropertyImplStrategy::GetSetProperty:
1277 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001278
John McCallb92ab1a2016-10-26 23:46:34 +00001279 llvm::Constant *setOptimizedPropertyFn = nullptr;
1280 llvm::Constant *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001281 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001282 // 10.8 and iOS 6.0 code and GC is off
Fangrui Song6907ce22018-07-30 19:24:48 +00001283 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001284 CGM.getObjCRuntime()
1285 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1286 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001287 if (!setOptimizedPropertyFn) {
1288 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1289 return;
1290 }
John McCall7f16c422011-09-10 09:17:20 +00001291 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001292 else {
1293 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1294 if (!setPropertyFn) {
1295 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1296 return;
1297 }
1298 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001299
John McCall7f16c422011-09-10 09:17:20 +00001300 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1301 // <is-atomic>, <is-copy>).
1302 llvm::Value *cmd =
John McCall7f416cc2015-09-08 08:05:57 +00001303 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall7f16c422011-09-10 09:17:20 +00001304 llvm::Value *self =
1305 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1306 llvm::Value *ivarOffset =
1307 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCall7f416cc2015-09-08 08:05:57 +00001308 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1309 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1310 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall7f16c422011-09-10 09:17:20 +00001311
1312 CallArgList args;
1313 args.add(RValue::get(self), getContext().getObjCIdType());
1314 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001315 if (setOptimizedPropertyFn) {
1316 args.add(RValue::get(arg), getContext().getObjCIdType());
1317 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCallb92ab1a2016-10-26 23:46:34 +00001318 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001319 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001320 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001321 } else {
1322 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1323 args.add(RValue::get(arg), getContext().getObjCIdType());
1324 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1325 getContext().BoolTy);
1326 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1327 getContext().BoolTy);
1328 // FIXME: We shouldn't need to get the function info here, the runtime
1329 // already should have computed it to build the function.
John McCallb92ab1a2016-10-26 23:46:34 +00001330 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCallc56a8b32016-03-11 04:30:31 +00001331 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCallb92ab1a2016-10-26 23:46:34 +00001332 callee, ReturnValueSlot(), args);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001333 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001334
John McCall7f16c422011-09-10 09:17:20 +00001335 return;
1336 }
1337
John McCallf4528ae2011-09-13 03:34:09 +00001338 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001339 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001340 return;
John McCallf4528ae2011-09-13 03:34:09 +00001341
1342 case PropertyImplStrategy::Expression:
1343 break;
John McCall7f16c422011-09-10 09:17:20 +00001344 }
1345
1346 // Otherwise, fake up some ASTs and emit a normal assignment.
1347 ValueDecl *selfDecl = setterMethod->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001348 DeclRefExpr self(getContext(), selfDecl, false, selfDecl->getType(),
John McCall113bee02012-03-10 09:33:50 +00001349 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001350 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1351 selfDecl->getType(), CK_LValueToRValue, &self,
1352 VK_RValue);
1353 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001354 SourceLocation(), SourceLocation(),
1355 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001356
1357 ParmVarDecl *argDecl = *setterMethod->param_begin();
1358 QualType argType = argDecl->getType().getNonReferenceType();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001359 DeclRefExpr arg(getContext(), argDecl, false, argType, VK_LValue,
1360 SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001361 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1362 argType.getUnqualifiedType(), CK_LValueToRValue,
1363 &arg, VK_RValue);
Fangrui Song6907ce22018-07-30 19:24:48 +00001364
John McCall7f16c422011-09-10 09:17:20 +00001365 // The property type can differ from the ivar type in some situations with
1366 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1367 // The following absurdity is just to ensure well-formed IR.
1368 CastKind argCK = CK_NoOp;
1369 if (ivarRef.getType()->isObjCObjectPointerType()) {
1370 if (argLoad.getType()->isObjCObjectPointerType())
1371 argCK = CK_BitCast;
1372 else if (argLoad.getType()->isBlockPointerType())
1373 argCK = CK_BlockPointerToObjCPointerCast;
1374 else
1375 argCK = CK_CPointerToObjCPointerCast;
1376 } else if (ivarRef.getType()->isBlockPointerType()) {
1377 if (argLoad.getType()->isBlockPointerType())
1378 argCK = CK_BitCast;
1379 else
1380 argCK = CK_AnyPointerToBlockPointerCast;
1381 } else if (ivarRef.getType()->isPointerType()) {
1382 argCK = CK_BitCast;
1383 }
1384 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1385 ivarRef.getType(), argCK, &argLoad,
1386 VK_RValue);
1387 Expr *finalArg = &argLoad;
1388 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1389 argLoad.getType()))
1390 finalArg = &argCast;
1391
1392
1393 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1394 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemet484aa452017-03-27 19:17:25 +00001395 SourceLocation(), FPOptions());
John McCall7f16c422011-09-10 09:17:20 +00001396 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001397}
1398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001399/// Generate an Objective-C property setter function.
James Dennettbe302452012-06-15 22:10:14 +00001400///
1401/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001402/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001403void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1404 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001405 llvm::Constant *AtomicHelperFn =
1406 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001407 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1408 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1409 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001410 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001411
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001412 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001413
1414 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001415}
1416
John McCall6a4fa522011-03-22 07:05:39 +00001417namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001418 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001419 private:
1420 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001421 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001422 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001423 bool useEHCleanupForArray;
1424 public:
1425 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1426 CodeGenFunction::Destroyer *destroyer,
1427 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001428 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001429 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001430
Craig Topper4f12f102014-03-12 06:41:41 +00001431 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001432 LValue lvalue
1433 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1434 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001435 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001436 }
1437 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001438}
John McCall6a4fa522011-03-22 07:05:39 +00001439
John McCall4bd0fb12011-07-12 16:41:08 +00001440/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1441static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001442 Address addr,
John McCall4bd0fb12011-07-12 16:41:08 +00001443 QualType type) {
1444 llvm::Value *null = getNullForVariable(addr);
1445 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1446}
John McCall31168b02011-06-15 23:02:42 +00001447
John McCall6a4fa522011-03-22 07:05:39 +00001448static void emitCXXDestructMethod(CodeGenFunction &CGF,
1449 ObjCImplementationDecl *impl) {
1450 CodeGenFunction::RunCleanupsScope scope(CGF);
1451
1452 llvm::Value *self = CGF.LoadObjCSelf();
1453
Jordy Rosea91768e2011-07-22 02:08:32 +00001454 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1455 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001456 ivar; ivar = ivar->getNextIvar()) {
1457 QualType type = ivar->getType();
1458
John McCall6a4fa522011-03-22 07:05:39 +00001459 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001460 QualType::DestructionKind dtorKind = type.isDestructedType();
1461 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001462
Craig Topper8a13c412014-05-21 05:09:00 +00001463 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001464
John McCall4bd0fb12011-07-12 16:41:08 +00001465 // Use a call to objc_storeStrong to destroy strong ivars, for the
1466 // general benefit of the tools.
1467 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001468 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001469
John McCall4bd0fb12011-07-12 16:41:08 +00001470 // Otherwise use the default for the destruction kind.
1471 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001472 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001473 }
John McCall4bd0fb12011-07-12 16:41:08 +00001474
1475 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1476
1477 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1478 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001479 }
1480
1481 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1482}
1483
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001484void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1485 ObjCMethodDecl *MD,
1486 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001487 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001488 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001489
1490 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001491 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001492 // Suppress the final autorelease in ARC.
1493 AutoreleaseResult = false;
1494
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001495 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001496 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001497 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fangrui Song6907ce22018-07-30 19:24:48 +00001498 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001499 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001500 EmitAggExpr(IvarInit->getInit(),
1501 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001502 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00001503 AggValueSlot::IsNotAliased,
1504 AggValueSlot::DoesNotOverlap));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001505 }
1506 // constructor returns 'self'.
1507 CodeGenTypes &Types = CGM.getTypes();
1508 QualType IdTy(CGM.getContext().getObjCIdType());
1509 llvm::Value *SelfAsId =
1510 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1511 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001512
1513 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001514 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001515 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001516 }
1517 FinishFunction();
1518}
1519
Daniel Dunbara08dff12008-09-24 04:04:31 +00001520llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001521 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001522 DeclRefExpr DRE(getContext(), Self,
1523 /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
John McCalldec348f72013-05-03 07:33:41 +00001524 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001525 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001526}
1527
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001528QualType CodeGenFunction::TypeOfSelfObject() {
1529 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1530 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001531 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1532 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001533 return PTy->getPointeeType();
1534}
1535
Chris Lattnerd4808922009-03-22 21:03:39 +00001536void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
John McCallb92ab1a2016-10-26 23:46:34 +00001537 llvm::Constant *EnumerationMutationFnPtr =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001538 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCallb92ab1a2016-10-26 23:46:34 +00001539 if (!EnumerationMutationFnPtr) {
Daniel Dunbara08dff12008-09-24 04:04:31 +00001540 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1541 return;
1542 }
John McCallb92ab1a2016-10-26 23:46:34 +00001543 CGCallee EnumerationMutationFn =
1544 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbara08dff12008-09-24 04:04:31 +00001545
Devang Pateld2d66652011-01-19 01:36:36 +00001546 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001547 if (DI)
1548 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001549
Kuba Mracek5e5e4e72017-04-14 16:53:25 +00001550 RunCleanupsScope ForScope(*this);
1551
Kuba Mracek82c21752017-04-14 01:00:03 +00001552 // The local variable comes into scope immediately.
1553 AutoVarEmission variable = AutoVarEmission::invalid();
1554 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1555 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1556
John McCall1c926b72011-01-07 01:49:06 +00001557 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001558
Anders Carlsson75658592008-08-31 02:33:12 +00001559 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001560 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCall7f416cc2015-09-08 08:05:57 +00001561 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001562 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001563
Anders Carlsson75658592008-08-31 02:33:12 +00001564 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001565 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001566
John McCall1c926b72011-01-07 01:49:06 +00001567 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001568 IdentifierInfo *II[] = {
1569 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1570 &CGM.getContext().Idents.get("objects"),
1571 &CGM.getContext().Idents.get("count")
1572 };
1573 Selector FastEnumSel =
1574 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001575
1576 QualType ItemsTy =
1577 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001578 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001579 ArrayType::Normal, 0);
John McCall7f416cc2015-09-08 08:05:57 +00001580 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001581
John McCall53848232011-07-27 01:07:15 +00001582 // Emit the collection pointer. In ARC, we do a retain.
1583 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001584 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001585 Collection = EmitARCRetainScalarExpr(S.getCollection());
1586
1587 // Enter a cleanup to do the release.
1588 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1589 } else {
1590 Collection = EmitScalarExpr(S.getCollection());
1591 }
Mike Stump11289f42009-09-09 15:08:12 +00001592
John McCall91e82dd2011-08-05 00:14:38 +00001593 // The 'continue' label needs to appear within the cleanup for the
1594 // collection object.
1595 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1596
John McCall1c926b72011-01-07 01:49:06 +00001597 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001598 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001599
1600 // The first argument is a temporary of the enumeration-state type.
John McCall7f416cc2015-09-08 08:05:57 +00001601 Args.add(RValue::get(StatePtr.getPointer()),
1602 getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001603
John McCall1c926b72011-01-07 01:49:06 +00001604 // The second argument is a temporary array with space for NumItems
1605 // pointers. We'll actually be loading elements from the array
1606 // pointer written into the control state; this buffer is so that
1607 // collections that *aren't* backed by arrays can still queue up
1608 // batches of elements.
John McCall7f416cc2015-09-08 08:05:57 +00001609 Args.add(RValue::get(ItemsPtr.getPointer()),
1610 getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001611
John McCall1c926b72011-01-07 01:49:06 +00001612 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001613 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1614 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1615 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump11289f42009-09-09 15:08:12 +00001616
John McCall1c926b72011-01-07 01:49:06 +00001617 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001618 RValue CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001619 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1620 getContext().getNSUIntegerType(),
1621 FastEnumSel, Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001622
John McCall1c926b72011-01-07 01:49:06 +00001623 // The initial number of objects that were returned in the buffer.
1624 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001625
John McCall1c926b72011-01-07 01:49:06 +00001626 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1627 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001628
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001629 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001630
John McCall1c926b72011-01-07 01:49:06 +00001631 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001632 // empty; skip all this. Set the branch weight assuming this has the same
1633 // probability of exiting the loop as any other loop exit.
Justin Bogner66242d62015-04-23 23:06:47 +00001634 uint64_t EntryCount = getCurrentProfileCount();
1635 Builder.CreateCondBr(
1636 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1637 LoopInitBB,
Justin Bogner65512642015-05-02 05:00:55 +00001638 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlsson75658592008-08-31 02:33:12 +00001639
John McCall1c926b72011-01-07 01:49:06 +00001640 // Otherwise, initialize the loop.
1641 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001642
John McCall1c926b72011-01-07 01:49:06 +00001643 // Save the initial mutations value. This is the value at an
1644 // address that was written into the state object by
1645 // countByEnumeratingWithState:objects:count:.
John McCall7f416cc2015-09-08 08:05:57 +00001646 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1647 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1648 llvm::Value *StateMutationsPtr
1649 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001650
John McCall1c926b72011-01-07 01:49:06 +00001651 llvm::Value *initialMutations =
John McCall7f416cc2015-09-08 08:05:57 +00001652 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1653 "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001654
John McCall1c926b72011-01-07 01:49:06 +00001655 // Start looping. This is the point we return to whenever we have a
1656 // fresh, non-empty batch of objects.
1657 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1658 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001659
John McCall1c926b72011-01-07 01:49:06 +00001660 // The current index into the buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001661 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001662 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001663
John McCall1c926b72011-01-07 01:49:06 +00001664 // The current buffer size.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001665 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001666 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001667
Justin Bogner66242d62015-04-23 23:06:47 +00001668 incrementProfileCounter(&S);
Bob Wilson8ab16912014-02-24 01:13:09 +00001669
John McCall1c926b72011-01-07 01:49:06 +00001670 // Check whether the mutations value has changed from where it was
1671 // at start. StateMutationsPtr should actually be invariant between
1672 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001673 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001674 llvm::Value *currentMutations
John McCall7f416cc2015-09-08 08:05:57 +00001675 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1676 "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001677
John McCall1c926b72011-01-07 01:49:06 +00001678 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001679 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001680
John McCall1c926b72011-01-07 01:49:06 +00001681 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1682 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001683
John McCall1c926b72011-01-07 01:49:06 +00001684 // If so, call the enumeration-mutation function.
1685 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001686 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001687 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001688 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001689 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001690 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001691 // FIXME: We shouldn't need to get the function info here, the runtime already
1692 // should have computed it to build the function.
John McCallc56a8b32016-03-11 04:30:31 +00001693 EmitCall(
1694 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001695 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001696
John McCall1c926b72011-01-07 01:49:06 +00001697 // Otherwise, or if the mutation function returns, just continue.
1698 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001699
John McCall1c926b72011-01-07 01:49:06 +00001700 // Initialize the element variable.
1701 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001702 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001703 LValue elementLValue;
1704 QualType elementType;
1705 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001706 // Initialize the variable, in case it's a __block variable or something.
1707 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001708
Bruno Ricci5fc4db72018-12-21 14:10:18 +00001709 const VarDecl *D = cast<VarDecl>(SD->getSingleDecl());
1710 DeclRefExpr tempDRE(getContext(), const_cast<VarDecl *>(D), false,
1711 D->getType(), VK_LValue, SourceLocation());
John McCall1c926b72011-01-07 01:49:06 +00001712 elementLValue = EmitLValue(&tempDRE);
1713 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001714 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001715
1716 if (D->isARCPseudoStrong())
1717 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001718 } else {
1719 elementLValue = LValue(); // suppress warning
1720 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001721 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001722 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001723 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001724
1725 // Fetch the buffer out of the enumeration state.
1726 // TODO: this pointer should actually be invariant between
1727 // refreshes, which would help us do certain loop optimizations.
John McCall7f416cc2015-09-08 08:05:57 +00001728 Address StateItemsPtr = Builder.CreateStructGEP(
1729 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001730 llvm::Value *EnumStateItems =
1731 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001732
John McCall1c926b72011-01-07 01:49:06 +00001733 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001734 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001735 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCall7f416cc2015-09-08 08:05:57 +00001736 llvm::Value *CurrentItem =
1737 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump11289f42009-09-09 15:08:12 +00001738
John McCall1c926b72011-01-07 01:49:06 +00001739 // Cast that value to the right type.
1740 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1741 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001742
John McCall1c926b72011-01-07 01:49:06 +00001743 // Make sure we have an l-value. Yes, this gets evaluated every
1744 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001745 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001746 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001747 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001748 } else {
Akira Hatanaka642f7992016-10-18 19:05:41 +00001749 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1750 /*isInit*/ true);
John McCalld4631322011-06-17 06:42:21 +00001751 }
Mike Stump11289f42009-09-09 15:08:12 +00001752
John McCall9e2e22f2011-02-22 07:16:58 +00001753 // If we do have an element variable, this assignment is the end of
1754 // its initialization.
1755 if (elementIsVariable)
1756 EmitAutoVarCleanups(variable);
1757
John McCall1c926b72011-01-07 01:49:06 +00001758 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001759 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001760 {
1761 RunCleanupsScope Scope(*this);
1762 EmitStmt(S.getBody());
1763 }
Anders Carlsson75658592008-08-31 02:33:12 +00001764 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001765
John McCall1c926b72011-01-07 01:49:06 +00001766 // Destroy the element variable now.
1767 elementVariableScope.ForceCleanup();
1768
1769 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001770 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001771
John McCall1c926b72011-01-07 01:49:06 +00001772 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001773
John McCall1c926b72011-01-07 01:49:06 +00001774 // First we check in the local buffer.
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001775 llvm::Value *indexPlusOne =
1776 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001777
John McCall1c926b72011-01-07 01:49:06 +00001778 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001779 // Set the branch weights based on the simplifying assumption that this is
1780 // like a while-loop, i.e., ignoring that the false branch fetches more
1781 // elements and then returns to the loop.
Justin Bogner66242d62015-04-23 23:06:47 +00001782 Builder.CreateCondBr(
1783 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner65512642015-05-02 05:00:55 +00001784 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001785
1786 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1787 count->addIncoming(count, AfterBody.getBlock());
1788
1789 // Otherwise, we have to fetch more elements.
1790 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001791
1792 CountRV =
Saleem Abdulrasool94bb1a02017-09-08 23:41:17 +00001793 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1794 getContext().getNSUIntegerType(),
1795 FastEnumSel, Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001796
John McCall1c926b72011-01-07 01:49:06 +00001797 // If we got a zero count, we're done.
1798 llvm::Value *refetchCount = CountRV.getScalarVal();
1799
1800 // (note that the message send might split FetchMoreBB)
1801 index->addIncoming(zero, Builder.GetInsertBlock());
1802 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1803
1804 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1805 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001806
Anders Carlsson75658592008-08-31 02:33:12 +00001807 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001808 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001809
John McCall9e2e22f2011-02-22 07:16:58 +00001810 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001811 // If the element was not a declaration, set it to be null.
1812
John McCall1c926b72011-01-07 01:49:06 +00001813 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1814 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001815 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001816 }
1817
Eric Christopher7cdf9482011-10-13 21:45:18 +00001818 if (DI)
1819 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001820
Akira Hatanaka2d3690b2016-04-12 23:10:58 +00001821 ForScope.ForceCleanup();
John McCallad5d61e2010-07-23 21:56:41 +00001822 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001823}
1824
Mike Stump11289f42009-09-09 15:08:12 +00001825void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001826 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001827}
1828
Mike Stump11289f42009-09-09 15:08:12 +00001829void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001830 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1831}
1832
Chris Lattnere132e242008-11-15 21:26:17 +00001833void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001834 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001835 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001836}
1837
John McCall31168b02011-06-15 23:02:42 +00001838namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001839 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001840 CallObjCRelease(llvm::Value *object) : object(object) {}
1841 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001842
Craig Topper4f12f102014-03-12 06:41:41 +00001843 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001844 // Releases at the end of the full-expression are imprecise.
1845 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001846 }
1847 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001848}
John McCall31168b02011-06-15 23:02:42 +00001849
John McCall2d637d22011-09-10 06:18:15 +00001850/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001851/// release at the end of the full-expression.
1852llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1853 llvm::Value *object) {
1854 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001855 // conditional.
1856 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001857 return object;
1858}
1859
1860llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1861 llvm::Value *value) {
1862 return EmitARCRetainAutorelease(type, value);
1863}
1864
John McCalleff18842013-03-23 02:35:54 +00001865/// Given a number of pointers, inform the optimizer that they're
1866/// being intrinsically used up until this point in the program.
1867void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
John McCallb04ecb72015-10-21 18:06:43 +00001868 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
Pete Cooper6c47f542018-12-20 18:05:41 +00001869 if (!fn)
1870 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_clang_arc_use);
John McCalleff18842013-03-23 02:35:54 +00001871
1872 // This isn't really a "runtime" function, but as an intrinsic it
1873 // doesn't really matter as long as we align things up.
1874 EmitNounwindRuntimeCall(fn, values);
1875}
1876
Pete Cooper2cd35962018-12-18 20:33:00 +00001877static void setARCRuntimeFunctionLinkage(CodeGenModule &CGM,
1878 llvm::Constant *RTF) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001879 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001880 // If the target runtime doesn't naturally support ARC, emit weak
1881 // references to the runtime support library. We don't really
1882 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasool6cb07442016-12-15 06:59:05 +00001883 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1884 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001885 F->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001886 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001887 }
John McCall31168b02011-06-15 23:02:42 +00001888}
1889
1890/// Perform an operation having the signature
1891/// i8* (i8*)
1892/// where a null input causes a no-op and returns null.
1893static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1894 llvm::Value *value,
Pete Coopere3886802018-12-08 05:13:50 +00001895 llvm::Type *returnType,
John McCall31168b02011-06-15 23:02:42 +00001896 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001897 llvm::Intrinsic::ID IntID,
Chad Rosier13799b32012-12-12 17:52:21 +00001898 bool isTailCall = false) {
Saleem Abdulrasoole60561c2017-02-11 17:24:07 +00001899 if (isa<llvm::ConstantPointerNull>(value))
1900 return value;
John McCall31168b02011-06-15 23:02:42 +00001901
1902 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001903 fn = CGF.CGM.getIntrinsic(IntID);
1904 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001905 }
1906
1907 // Cast the argument to 'id'.
Pete Coopere3886802018-12-08 05:13:50 +00001908 llvm::Type *origType = returnType ? returnType : value->getType();
John McCall31168b02011-06-15 23:02:42 +00001909 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1910
1911 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001912 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001913 if (isTailCall)
1914 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001915
1916 // Cast the result back to the original type.
1917 return CGF.Builder.CreateBitCast(call, origType);
1918}
1919
1920/// Perform an operation having the following signature:
1921/// i8* (i8**)
1922static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001923 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001924 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001925 llvm::Intrinsic::ID IntID) {
John McCall31168b02011-06-15 23:02:42 +00001926 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001927 fn = CGF.CGM.getIntrinsic(IntID);
1928 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001929 }
1930
1931 // Cast the argument to 'id*'.
John McCall7f416cc2015-09-08 08:05:57 +00001932 llvm::Type *origType = addr.getElementType();
John McCall31168b02011-06-15 23:02:42 +00001933 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1934
1935 // Call the function.
John McCall7f416cc2015-09-08 08:05:57 +00001936 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00001937
1938 // Cast the result back to a dereference of the original type.
John McCall7f416cc2015-09-08 08:05:57 +00001939 if (origType != CGF.Int8PtrTy)
1940 result = CGF.Builder.CreateBitCast(result, origType);
John McCall31168b02011-06-15 23:02:42 +00001941
1942 return result;
1943}
1944
1945/// Perform an operation having the following signature:
1946/// i8* (i8**, i8*)
1947static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001948 Address addr,
John McCall31168b02011-06-15 23:02:42 +00001949 llvm::Value *value,
1950 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001951 llvm::Intrinsic::ID IntID,
John McCall31168b02011-06-15 23:02:42 +00001952 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00001953 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00001954
1955 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001956 fn = CGF.CGM.getIntrinsic(IntID);
1957 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001958 }
1959
Chris Lattner2192fe52011-07-18 04:24:23 +00001960 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001961
John McCall882987f2013-02-28 19:01:20 +00001962 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001963 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00001964 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1965 };
1966 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001967
Craig Topper8a13c412014-05-21 05:09:00 +00001968 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001969
1970 return CGF.Builder.CreateBitCast(result, origType);
1971}
1972
1973/// Perform an operation having the following signature:
1974/// void (i8**, i8**)
1975static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00001976 Address dst,
1977 Address src,
John McCall31168b02011-06-15 23:02:42 +00001978 llvm::Constant *&fn,
Pete Cooper2cd35962018-12-18 20:33:00 +00001979 llvm::Intrinsic::ID IntID) {
John McCall7f416cc2015-09-08 08:05:57 +00001980 assert(dst.getType() == src.getType());
John McCall31168b02011-06-15 23:02:42 +00001981
1982 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00001983 fn = CGF.CGM.getIntrinsic(IntID);
1984 setARCRuntimeFunctionLinkage(CGF.CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00001985 }
1986
John McCall882987f2013-02-28 19:01:20 +00001987 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00001988 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1989 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCall882987f2013-02-28 19:01:20 +00001990 };
1991 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001992}
1993
Pete Cooper2cd35962018-12-18 20:33:00 +00001994/// Perform an operation having the signature
1995/// i8* (i8*)
1996/// where a null input causes a no-op and returns null.
1997static llvm::Value *emitObjCValueOperation(CodeGenFunction &CGF,
1998 llvm::Value *value,
1999 llvm::Type *returnType,
2000 llvm::Constant *&fn,
2001 StringRef fnName) {
2002 if (isa<llvm::ConstantPointerNull>(value))
2003 return value;
2004
2005 if (!fn) {
2006 llvm::FunctionType *fnType =
2007 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
2008 fn = CGF.CGM.CreateRuntimeFunction(fnType, fnName);
2009 }
2010
2011 // Cast the argument to 'id'.
2012 llvm::Type *origType = returnType ? returnType : value->getType();
2013 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
2014
2015 // Call the function.
2016 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
2017
2018 // Cast the result back to the original type.
2019 return CGF.Builder.CreateBitCast(call, origType);
2020}
2021
John McCall31168b02011-06-15 23:02:42 +00002022/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00002023/// call i8* \@objc_retain(i8* %value)
2024/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002025llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
2026 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00002027 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00002028 else
2029 return EmitARCRetainNonBlock(value);
2030}
2031
2032/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002033/// call i8* \@objc_retain(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002034llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002035 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002036 CGM.getObjCEntrypoints().objc_retain,
Pete Cooper2cd35962018-12-18 20:33:00 +00002037 llvm::Intrinsic::objc_retain);
John McCall31168b02011-06-15 23:02:42 +00002038}
2039
2040/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00002041/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00002042///
2043/// \param mandatory - If false, emit the call with metadata
2044/// indicating that it's okay for the optimizer to eliminate this call
2045/// if it can prove that the block never escapes except down the stack.
2046llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
2047 bool mandatory) {
2048 llvm::Value *result
Pete Coopere3886802018-12-08 05:13:50 +00002049 = emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002050 CGM.getObjCEntrypoints().objc_retainBlock,
Pete Cooper2cd35962018-12-18 20:33:00 +00002051 llvm::Intrinsic::objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002052
2053 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2054 // tell the optimizer that it doesn't need to do this copy if the
2055 // block doesn't escape, where being passed as an argument doesn't
2056 // count as escaping.
2057 if (!mandatory && isa<llvm::Instruction>(result)) {
2058 llvm::CallInst *call
2059 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallb04ecb72015-10-21 18:06:43 +00002060 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCallff613032011-10-04 06:23:45 +00002061
John McCallff613032011-10-04 06:23:45 +00002062 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002063 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00002064 }
2065
2066 return result;
John McCall31168b02011-06-15 23:02:42 +00002067}
2068
John McCalle399e5b2016-01-27 18:32:30 +00002069static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCall31168b02011-06-15 23:02:42 +00002070 // Fetch the void(void) inline asm which marks that we're going to
John McCalle399e5b2016-01-27 18:32:30 +00002071 // do something with the autoreleased return value.
John McCall31168b02011-06-15 23:02:42 +00002072 llvm::InlineAsm *&marker
John McCalle399e5b2016-01-27 18:32:30 +00002073 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCall31168b02011-06-15 23:02:42 +00002074 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002075 StringRef assembly
John McCalle399e5b2016-01-27 18:32:30 +00002076 = CGF.CGM.getTargetCodeGenInfo()
John McCall31168b02011-06-15 23:02:42 +00002077 .getARCRetainAutoreleasedReturnValueMarker();
2078
2079 // If we have an empty assembly string, there's nothing to do.
2080 if (assembly.empty()) {
2081
2082 // Otherwise, at -O0, build an inline asm that we're going to call
2083 // in a moment.
John McCalle399e5b2016-01-27 18:32:30 +00002084 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall31168b02011-06-15 23:02:42 +00002085 llvm::FunctionType *type =
John McCalle399e5b2016-01-27 18:32:30 +00002086 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00002087
John McCall31168b02011-06-15 23:02:42 +00002088 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2089
2090 // If we're at -O1 and above, we don't want to litter the code
2091 // with this marker yet, so leave a breadcrumb for the ARC
2092 // optimizer to pick up.
2093 } else {
2094 llvm::NamedMDNode *metadata =
John McCalle399e5b2016-01-27 18:32:30 +00002095 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCall31168b02011-06-15 23:02:42 +00002096 "clang.arc.retainAutoreleasedReturnValueMarker");
2097 assert(metadata->getNumOperands() <= 1);
2098 if (metadata->getNumOperands() == 0) {
John McCalle399e5b2016-01-27 18:32:30 +00002099 auto &ctx = CGF.getLLVMContext();
2100 metadata->addOperand(llvm::MDNode::get(ctx,
2101 llvm::MDString::get(ctx, assembly)));
John McCall31168b02011-06-15 23:02:42 +00002102 }
2103 }
2104 }
2105
2106 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie43f9bb72015-05-18 22:14:03 +00002107 if (marker)
Shoaib Meenaif6985692018-03-19 19:34:39 +00002108 CGF.Builder.CreateCall(marker, None, CGF.getBundlesForFunclet(marker));
John McCalle399e5b2016-01-27 18:32:30 +00002109}
John McCall31168b02011-06-15 23:02:42 +00002110
John McCalle399e5b2016-01-27 18:32:30 +00002111/// Retain the given object which is the result of a function call.
2112/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2113///
2114/// Yes, this function name is one character away from a different
2115/// call with completely different semantics.
2116llvm::Value *
2117CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2118 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002119 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002120 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002121 llvm::Intrinsic::objc_retainAutoreleasedReturnValue);
John McCall31168b02011-06-15 23:02:42 +00002122}
2123
John McCalle399e5b2016-01-27 18:32:30 +00002124/// Claim a possibly-autoreleased return value at +0. This is only
2125/// valid to do in contexts which do not rely on the retain to keep
Hiroshi Inoueef04f642018-01-26 08:15:52 +00002126/// the object valid for all of its uses; for example, when
John McCalle399e5b2016-01-27 18:32:30 +00002127/// the value is ignored, or when it is being assigned to an
2128/// __unsafe_unretained variable.
2129///
2130/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2131llvm::Value *
2132CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2133 emitAutoreleasedReturnValueMarker(*this);
Pete Coopere3886802018-12-08 05:13:50 +00002134 return emitARCValueOperation(*this, value, nullptr,
John McCalle399e5b2016-01-27 18:32:30 +00002135 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002136 llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue);
John McCalle399e5b2016-01-27 18:32:30 +00002137}
2138
John McCall31168b02011-06-15 23:02:42 +00002139/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002140/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00002141void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2142 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00002143 if (isa<llvm::ConstantPointerNull>(value)) return;
2144
John McCallb04ecb72015-10-21 18:06:43 +00002145 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
John McCall31168b02011-06-15 23:02:42 +00002146 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002147 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_release);
2148 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002149 }
2150
2151 // Cast the argument to 'id'.
2152 value = Builder.CreateBitCast(value, Int8PtrTy);
2153
2154 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002155 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002156
John McCallcdda29c2013-03-13 03:10:54 +00002157 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002158 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002159 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002160 }
2161}
2162
John McCalle68b8f42012-10-17 02:28:37 +00002163/// Destroy a __strong variable.
2164///
2165/// At -O0, emit a call to store 'null' into the address;
2166/// instrumenting tools prefer this because the address is exposed,
2167/// but it's relatively cumbersome to optimize.
2168///
2169/// At -O1 and above, just load and call objc_release.
2170///
2171/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall7f416cc2015-09-08 08:05:57 +00002172void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCallcdda29c2013-03-13 03:10:54 +00002173 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002174 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCall7f416cc2015-09-08 08:05:57 +00002175 llvm::Value *null = getNullForVariable(addr);
John McCalle68b8f42012-10-17 02:28:37 +00002176 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2177 return;
2178 }
2179
2180 llvm::Value *value = Builder.CreateLoad(addr);
2181 EmitARCRelease(value, precise);
2182}
2183
John McCall31168b02011-06-15 23:02:42 +00002184/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002185/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall7f416cc2015-09-08 08:05:57 +00002186llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002187 llvm::Value *value,
2188 bool ignored) {
John McCall7f416cc2015-09-08 08:05:57 +00002189 assert(addr.getElementType() == value->getType());
John McCall31168b02011-06-15 23:02:42 +00002190
John McCallb04ecb72015-10-21 18:06:43 +00002191 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCall31168b02011-06-15 23:02:42 +00002192 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002193 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_storeStrong);
2194 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002195 }
2196
John McCall882987f2013-02-28 19:01:20 +00002197 llvm::Value *args[] = {
John McCall7f416cc2015-09-08 08:05:57 +00002198 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCall882987f2013-02-28 19:01:20 +00002199 Builder.CreateBitCast(value, Int8PtrTy)
2200 };
2201 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002202
Craig Topper8a13c412014-05-21 05:09:00 +00002203 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002204 return value;
2205}
2206
2207/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002208/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002209/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002210llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002211 llvm::Value *newValue,
2212 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002213 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002214 bool isBlock = type->isBlockPointerType();
2215
2216 // Use a store barrier at -O0 unless this is a block type or the
2217 // lvalue is inadequately aligned.
2218 if (shouldUseFusedARCCalls() &&
2219 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002220 (dst.getAlignment().isZero() ||
2221 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002222 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2223 }
2224
2225 // Otherwise, split it out.
2226
2227 // Retain the new value.
2228 newValue = EmitARCRetain(type, newValue);
2229
2230 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002231 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002232
2233 // Store. We do this before the release so that any deallocs won't
2234 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002235 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002236
2237 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002238 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002239
2240 return newValue;
2241}
2242
2243/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002244/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper94867712016-03-21 20:50:03 +00002245llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002246 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002247 CGM.getObjCEntrypoints().objc_autorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002248 llvm::Intrinsic::objc_autorelease);
John McCall31168b02011-06-15 23:02:42 +00002249}
2250
2251/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002252/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002253llvm::Value *
2254CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002255 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002256 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002257 llvm::Intrinsic::objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002258 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002259}
2260
2261/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002262/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002263llvm::Value *
2264CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002265 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002266 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Pete Cooper2cd35962018-12-18 20:33:00 +00002267 llvm::Intrinsic::objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002268 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002269}
2270
2271/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002272/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002273/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002274/// %retain = call i8* \@objc_retainBlock(i8* %value)
2275/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002276llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2277 llvm::Value *value) {
2278 if (!type->isBlockPointerType())
2279 return EmitARCRetainAutoreleaseNonBlock(value);
2280
2281 if (isa<llvm::ConstantPointerNull>(value)) return value;
2282
Chris Lattner2192fe52011-07-18 04:24:23 +00002283 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002284 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002285 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002286 value = EmitARCAutorelease(value);
2287 return Builder.CreateBitCast(value, origType);
2288}
2289
2290/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002291/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002292llvm::Value *
2293CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Coopere3886802018-12-08 05:13:50 +00002294 return emitARCValueOperation(*this, value, nullptr,
John McCallb04ecb72015-10-21 18:06:43 +00002295 CGM.getObjCEntrypoints().objc_retainAutorelease,
Pete Cooper2cd35962018-12-18 20:33:00 +00002296 llvm::Intrinsic::objc_retainAutorelease);
John McCall31168b02011-06-15 23:02:42 +00002297}
2298
John McCallb04ecb72015-10-21 18:06:43 +00002299/// i8* \@objc_loadWeak(i8** %addr)
2300/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2301llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2302 return emitARCLoadOperation(*this, addr,
2303 CGM.getObjCEntrypoints().objc_loadWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002304 llvm::Intrinsic::objc_loadWeak);
John McCallb04ecb72015-10-21 18:06:43 +00002305}
2306
James Dennett14c41ea2012-06-22 05:41:30 +00002307/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall7f416cc2015-09-08 08:05:57 +00002308llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCall31168b02011-06-15 23:02:42 +00002309 return emitARCLoadOperation(*this, addr,
John McCallb04ecb72015-10-21 18:06:43 +00002310 CGM.getObjCEntrypoints().objc_loadWeakRetained,
Pete Cooper2cd35962018-12-18 20:33:00 +00002311 llvm::Intrinsic::objc_loadWeakRetained);
John McCall31168b02011-06-15 23:02:42 +00002312}
2313
James Dennett14c41ea2012-06-22 05:41:30 +00002314/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002315/// Returns %value.
John McCall7f416cc2015-09-08 08:05:57 +00002316llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCall31168b02011-06-15 23:02:42 +00002317 llvm::Value *value,
2318 bool ignored) {
2319 return emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002320 CGM.getObjCEntrypoints().objc_storeWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002321 llvm::Intrinsic::objc_storeWeak, ignored);
John McCall31168b02011-06-15 23:02:42 +00002322}
2323
James Dennett14c41ea2012-06-22 05:41:30 +00002324/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002325/// Returns %value. %addr is known to not have a current weak entry.
2326/// Essentially equivalent to:
2327/// *addr = nil; objc_storeWeak(addr, value);
John McCall7f416cc2015-09-08 08:05:57 +00002328void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCall31168b02011-06-15 23:02:42 +00002329 // If we're initializing to null, just write null to memory; no need
2330 // to get the runtime involved. But don't do this if optimization
2331 // is enabled, because accounting for this would make the optimizer
2332 // much more complicated.
2333 if (isa<llvm::ConstantPointerNull>(value) &&
2334 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2335 Builder.CreateStore(value, addr);
2336 return;
2337 }
2338
2339 emitARCStoreOperation(*this, addr, value,
John McCallb04ecb72015-10-21 18:06:43 +00002340 CGM.getObjCEntrypoints().objc_initWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002341 llvm::Intrinsic::objc_initWeak, /*ignored*/ true);
John McCall31168b02011-06-15 23:02:42 +00002342}
2343
James Dennett14c41ea2012-06-22 05:41:30 +00002344/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002345/// Essentially objc_storeWeak(addr, nil).
John McCall7f416cc2015-09-08 08:05:57 +00002346void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCallb04ecb72015-10-21 18:06:43 +00002347 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCall31168b02011-06-15 23:02:42 +00002348 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002349 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_destroyWeak);
2350 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002351 }
2352
2353 // Cast the argument to 'id*'.
2354 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2355
John McCall7f416cc2015-09-08 08:05:57 +00002356 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCall31168b02011-06-15 23:02:42 +00002357}
2358
James Dennett14c41ea2012-06-22 05:41:30 +00002359/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002360/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2361/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCall7f416cc2015-09-08 08:05:57 +00002362void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002363 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002364 CGM.getObjCEntrypoints().objc_moveWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002365 llvm::Intrinsic::objc_moveWeak);
John McCall31168b02011-06-15 23:02:42 +00002366}
2367
James Dennett14c41ea2012-06-22 05:41:30 +00002368/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002369/// Disregards the current value in %dest. Essentially
2370/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCall7f416cc2015-09-08 08:05:57 +00002371void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCall31168b02011-06-15 23:02:42 +00002372 emitARCCopyOperation(*this, dst, src,
John McCallb04ecb72015-10-21 18:06:43 +00002373 CGM.getObjCEntrypoints().objc_copyWeak,
Pete Cooper2cd35962018-12-18 20:33:00 +00002374 llvm::Intrinsic::objc_copyWeak);
John McCall31168b02011-06-15 23:02:42 +00002375}
2376
Akira Hatanakad791e922018-03-19 17:38:40 +00002377void CodeGenFunction::emitARCCopyAssignWeak(QualType Ty, Address DstAddr,
2378 Address SrcAddr) {
2379 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2380 Object = EmitObjCConsumeObject(Ty, Object);
2381 EmitARCStoreWeak(DstAddr, Object, false);
2382}
2383
2384void CodeGenFunction::emitARCMoveAssignWeak(QualType Ty, Address DstAddr,
2385 Address SrcAddr) {
2386 llvm::Value *Object = EmitARCLoadWeakRetained(SrcAddr);
2387 Object = EmitObjCConsumeObject(Ty, Object);
2388 EmitARCStoreWeak(DstAddr, Object, false);
2389 EmitARCDestroyWeak(SrcAddr);
2390}
2391
John McCall31168b02011-06-15 23:02:42 +00002392/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002393/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002394llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
John McCallb04ecb72015-10-21 18:06:43 +00002395 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCall31168b02011-06-15 23:02:42 +00002396 if (!fn) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002397 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPush);
2398 setARCRuntimeFunctionLinkage(CGM, fn);
John McCall31168b02011-06-15 23:02:42 +00002399 }
2400
John McCall882987f2013-02-28 19:01:20 +00002401 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002402}
2403
2404/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002405/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002406void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2407 assert(value->getType() == Int8PtrTy);
2408
Pete Cooper2cd35962018-12-18 20:33:00 +00002409 if (getInvokeDest()) {
2410 // Call the runtime method not the intrinsic if we are handling exceptions
2411 llvm::Constant *&fn =
2412 CGM.getObjCEntrypoints().objc_autoreleasePoolPopInvoke;
2413 if (!fn) {
2414 llvm::FunctionType *fnType =
2415 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2416 fn = CGM.CreateRuntimeFunction(fnType, "objc_autoreleasePoolPop");
2417 setARCRuntimeFunctionLinkage(CGM, fn);
2418 }
John McCall31168b02011-06-15 23:02:42 +00002419
Pete Cooper2cd35962018-12-18 20:33:00 +00002420 // objc_autoreleasePoolPop can throw.
2421 EmitRuntimeCallOrInvoke(fn, value);
2422 } else {
2423 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
2424 if (!fn) {
2425 fn = CGM.getIntrinsic(llvm::Intrinsic::objc_autoreleasePoolPop);
2426 setARCRuntimeFunctionLinkage(CGM, fn);
2427 }
2428
2429 EmitRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002430 }
John McCall31168b02011-06-15 23:02:42 +00002431}
2432
2433/// Produce the code to do an MRR version objc_autoreleasepool_push.
2434/// Which is: [[NSAutoreleasePool alloc] init];
2435/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2436/// init is declared as: - (id) init; in its NSObject super class.
2437///
2438llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2439 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002440 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002441 // [NSAutoreleasePool alloc]
2442 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2443 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2444 CallArgList Args;
Fangrui Song6907ce22018-07-30 19:24:48 +00002445 RValue AllocRV =
2446 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
John McCall31168b02011-06-15 23:02:42 +00002447 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002448 AllocSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002449
2450 // [Receiver init]
2451 Receiver = AllocRV.getScalarVal();
2452 II = &CGM.getContext().Idents.get("init");
2453 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2454 RValue InitRV =
2455 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2456 getContext().getObjCIdType(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002457 InitSel, Receiver, Args);
John McCall31168b02011-06-15 23:02:42 +00002458 return InitRV.getScalarVal();
2459}
2460
Pete Coopere3886802018-12-08 05:13:50 +00002461/// Allocate the given objc object.
2462/// call i8* \@objc_alloc(i8* %value)
2463llvm::Value *CodeGenFunction::EmitObjCAlloc(llvm::Value *value,
2464 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002465 return emitObjCValueOperation(*this, value, resultType,
2466 CGM.getObjCEntrypoints().objc_alloc,
2467 "objc_alloc");
Pete Coopere3886802018-12-08 05:13:50 +00002468}
2469
2470/// Allocate the given objc object.
2471/// call i8* \@objc_allocWithZone(i8* %value)
2472llvm::Value *CodeGenFunction::EmitObjCAllocWithZone(llvm::Value *value,
2473 llvm::Type *resultType) {
Pete Cooper2cd35962018-12-18 20:33:00 +00002474 return emitObjCValueOperation(*this, value, resultType,
2475 CGM.getObjCEntrypoints().objc_allocWithZone,
2476 "objc_allocWithZone");
Pete Coopere3886802018-12-08 05:13:50 +00002477}
2478
John McCall31168b02011-06-15 23:02:42 +00002479/// Produce the code to do a primitive release.
2480/// [tmp drain];
2481void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2482 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2483 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2484 CallArgList Args;
2485 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Fangrui Song6907ce22018-07-30 19:24:48 +00002486 getContext().VoidTy, DrainSel, Arg, Args);
John McCall31168b02011-06-15 23:02:42 +00002487}
2488
John McCall82fe67b2011-07-09 01:37:26 +00002489void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002490 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002491 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002492 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002493}
2494
2495void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002496 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002497 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002498 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002499}
2500
2501void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCall7f416cc2015-09-08 08:05:57 +00002502 Address addr,
John McCall82fe67b2011-07-09 01:37:26 +00002503 QualType type) {
2504 CGF.EmitARCDestroyWeak(addr);
2505}
2506
Akira Hatanakaa6b6dcc2017-04-28 18:50:57 +00002507void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2508 QualType type) {
2509 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2510 CGF.EmitARCIntrinsicUse(value);
2511}
2512
John McCall31168b02011-06-15 23:02:42 +00002513namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002514 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002515 llvm::Value *Token;
2516
2517 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2518
Craig Topper4f12f102014-03-12 06:41:41 +00002519 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002520 CGF.EmitObjCAutoreleasePoolPop(Token);
2521 }
2522 };
David Blaikie7e70d682015-08-18 22:40:54 +00002523 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCall31168b02011-06-15 23:02:42 +00002524 llvm::Value *Token;
2525
2526 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2527
Craig Topper4f12f102014-03-12 06:41:41 +00002528 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002529 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2530 }
2531 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002532}
John McCall31168b02011-06-15 23:02:42 +00002533
2534void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002535 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002536 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2537 else
2538 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2539}
2540
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002541static bool shouldRetainObjCLifetime(Qualifiers::ObjCLifetime lifetime) {
2542 switch (lifetime) {
John McCall31168b02011-06-15 23:02:42 +00002543 case Qualifiers::OCL_None:
2544 case Qualifiers::OCL_ExplicitNone:
2545 case Qualifiers::OCL_Strong:
2546 case Qualifiers::OCL_Autoreleasing:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002547 return true;
John McCall31168b02011-06-15 23:02:42 +00002548
2549 case Qualifiers::OCL_Weak:
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002550 return false;
John McCall31168b02011-06-15 23:02:42 +00002551 }
2552
2553 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002554}
2555
2556static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002557 LValue lvalue,
2558 QualType type) {
2559 llvm::Value *result;
2560 bool shouldRetain = shouldRetainObjCLifetime(type.getObjCLifetime());
2561 if (shouldRetain) {
2562 result = CGF.EmitLoadOfLValue(lvalue, SourceLocation()).getScalarVal();
2563 } else {
2564 assert(type.getObjCLifetime() == Qualifiers::OCL_Weak);
2565 result = CGF.EmitARCLoadWeakRetained(lvalue.getAddress());
2566 }
2567 return TryEmitResult(result, !shouldRetain);
2568}
2569
2570static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
John McCall31168b02011-06-15 23:02:42 +00002571 const Expr *e) {
2572 e = e->IgnoreParens();
2573 QualType type = e->getType();
2574
Fangrui Song6907ce22018-07-30 19:24:48 +00002575 // If we're loading retained from a __strong xvalue, we can avoid
John McCall154a2fd2011-08-30 00:57:29 +00002576 // an extra retain/release pair by zeroing out the source of this
2577 // "move" operation.
2578 if (e->isXValue() &&
2579 !type.isConstQualified() &&
2580 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2581 // Emit the lvalue.
2582 LValue lv = CGF.EmitLValue(e);
Fangrui Song6907ce22018-07-30 19:24:48 +00002583
John McCall154a2fd2011-08-30 00:57:29 +00002584 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002585 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2586 SourceLocation()).getScalarVal();
Fangrui Song6907ce22018-07-30 19:24:48 +00002587
John McCall154a2fd2011-08-30 00:57:29 +00002588 // Set the source pointer to NULL.
2589 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
Fangrui Song6907ce22018-07-30 19:24:48 +00002590
John McCall154a2fd2011-08-30 00:57:29 +00002591 return TryEmitResult(result, true);
2592 }
2593
John McCall31168b02011-06-15 23:02:42 +00002594 // As a very special optimization, in ARC++, if the l-value is the
2595 // result of a non-volatile assignment, do a simple retain of the
2596 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002597 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002598 !type.isVolatileQualified() &&
2599 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2600 isa<BinaryOperator>(e) &&
2601 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2602 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2603
Volodymyr Sapsai8b286f92018-11-01 22:50:08 +00002604 // Try to emit code for scalar constant instead of emitting LValue and
2605 // loading it because we are not guaranteed to have an l-value. One of such
2606 // cases is DeclRefExpr referencing non-odr-used constant-evaluated variable.
2607 if (const auto *decl_expr = dyn_cast<DeclRefExpr>(e)) {
2608 auto *DRE = const_cast<DeclRefExpr *>(decl_expr);
2609 if (CodeGenFunction::ConstantEmission constant = CGF.tryEmitAsConstant(DRE))
2610 return TryEmitResult(CGF.emitScalarConstant(constant, DRE),
2611 !shouldRetainObjCLifetime(type.getObjCLifetime()));
2612 }
2613
John McCall31168b02011-06-15 23:02:42 +00002614 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2615}
2616
John McCalle399e5b2016-01-27 18:32:30 +00002617typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2618 llvm::Value *value)>
2619 ValueTransform;
John McCall31168b02011-06-15 23:02:42 +00002620
John McCalle399e5b2016-01-27 18:32:30 +00002621/// Insert code immediately after a call.
2622static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2623 llvm::Value *value,
2624 ValueTransform doAfterCall,
2625 ValueTransform doFallback) {
John McCall31168b02011-06-15 23:02:42 +00002626 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2627 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2628
2629 // Place the retain immediately following the call.
2630 CGF.Builder.SetInsertPoint(call->getParent(),
2631 ++llvm::BasicBlock::iterator(call));
John McCalle399e5b2016-01-27 18:32:30 +00002632 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002633
2634 CGF.Builder.restoreIP(ip);
2635 return value;
2636 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2637 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2638
2639 // Place the retain at the beginning of the normal destination block.
2640 llvm::BasicBlock *BB = invoke->getNormalDest();
2641 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCalle399e5b2016-01-27 18:32:30 +00002642 value = doAfterCall(CGF, value);
John McCall31168b02011-06-15 23:02:42 +00002643
2644 CGF.Builder.restoreIP(ip);
2645 return value;
2646
2647 // Bitcasts can arise because of related-result returns. Rewrite
2648 // the operand.
2649 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2650 llvm::Value *operand = bitcast->getOperand(0);
John McCalle399e5b2016-01-27 18:32:30 +00002651 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCall31168b02011-06-15 23:02:42 +00002652 bitcast->setOperand(0, operand);
2653 return bitcast;
2654
2655 // Generic fall-back case.
2656 } else {
2657 // Retain using the non-block variant: we never need to do a copy
2658 // of a block that's been returned to us.
John McCalle399e5b2016-01-27 18:32:30 +00002659 return doFallback(CGF, value);
2660 }
2661}
2662
2663/// Given that the given expression is some sort of call (which does
2664/// not return retained), emit a retain following it.
2665static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2666 const Expr *e) {
2667 llvm::Value *value = CGF.EmitScalarExpr(e);
2668 return emitARCOperationAfterCall(CGF, value,
2669 [](CodeGenFunction &CGF, llvm::Value *value) {
2670 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2671 },
2672 [](CodeGenFunction &CGF, llvm::Value *value) {
2673 return CGF.EmitARCRetainNonBlock(value);
2674 });
2675}
2676
2677/// Given that the given expression is some sort of call (which does
2678/// not return retained), perform an unsafeClaim following it.
2679static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2680 const Expr *e) {
2681 llvm::Value *value = CGF.EmitScalarExpr(e);
2682 return emitARCOperationAfterCall(CGF, value,
2683 [](CodeGenFunction &CGF, llvm::Value *value) {
2684 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2685 },
2686 [](CodeGenFunction &CGF, llvm::Value *value) {
2687 return value;
2688 });
2689}
2690
2691llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2692 bool allowUnsafeClaim) {
2693 if (allowUnsafeClaim &&
2694 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2695 return emitARCUnsafeClaimCallResult(*this, E);
2696 } else {
2697 llvm::Value *value = emitARCRetainCallResult(*this, E);
2698 return EmitObjCConsumeObject(E->getType(), value);
John McCall31168b02011-06-15 23:02:42 +00002699 }
2700}
2701
John McCallcd78e802011-09-10 01:16:55 +00002702/// Determine whether it might be important to emit a separate
2703/// objc_retain_block on the result of the given expression, or
2704/// whether it's okay to just emit it in a +1 context.
2705static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2706 assert(e->getType()->isBlockPointerType());
2707 e = e->IgnoreParens();
2708
2709 // For future goodness, emit block expressions directly in +1
2710 // contexts if we can.
2711 if (isa<BlockExpr>(e))
2712 return false;
2713
2714 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2715 switch (cast->getCastKind()) {
2716 // Emitting these operations in +1 contexts is goodness.
2717 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002718 case CK_ARCReclaimReturnedObject:
2719 case CK_ARCConsumeObject:
2720 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002721 return false;
2722
2723 // These operations preserve a block type.
2724 case CK_NoOp:
2725 case CK_BitCast:
2726 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2727
2728 // These operations are known to be bad (or haven't been considered).
2729 case CK_AnyPointerToBlockPointerCast:
2730 default:
2731 return true;
2732 }
2733 }
2734
2735 return true;
2736}
2737
John McCalle399e5b2016-01-27 18:32:30 +00002738namespace {
2739/// A CRTP base class for emitting expressions of retainable object
2740/// pointer type in ARC.
2741template <typename Impl, typename Result> class ARCExprEmitter {
2742protected:
2743 CodeGenFunction &CGF;
2744 Impl &asImpl() { return *static_cast<Impl*>(this); }
2745
2746 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2747
2748public:
2749 Result visit(const Expr *e);
2750 Result visitCastExpr(const CastExpr *e);
2751 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2752 Result visitBinaryOperator(const BinaryOperator *e);
2753 Result visitBinAssign(const BinaryOperator *e);
2754 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2755 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2756 Result visitBinAssignWeak(const BinaryOperator *e);
2757 Result visitBinAssignStrong(const BinaryOperator *e);
2758
2759 // Minimal implementation:
2760 // Result visitLValueToRValue(const Expr *e)
2761 // Result visitConsumeObject(const Expr *e)
2762 // Result visitExtendBlockObject(const Expr *e)
2763 // Result visitReclaimReturnedObject(const Expr *e)
2764 // Result visitCall(const Expr *e)
2765 // Result visitExpr(const Expr *e)
2766 //
2767 // Result emitBitCast(Result result, llvm::Type *resultType)
2768 // llvm::Value *getValueOfResult(Result result)
2769};
2770}
2771
2772/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCallfe96e0b2011-11-06 09:01:30 +00002773///
2774/// This massively duplicates emitPseudoObjectRValue.
John McCalle399e5b2016-01-27 18:32:30 +00002775template <typename Impl, typename Result>
2776Result
2777ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002778 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002779
2780 // Find the result expression.
2781 const Expr *resultExpr = E->getResultExpr();
2782 assert(resultExpr);
John McCalle399e5b2016-01-27 18:32:30 +00002783 Result result;
John McCallfe96e0b2011-11-06 09:01:30 +00002784
2785 for (PseudoObjectExpr::const_semantics_iterator
2786 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2787 const Expr *semantic = *i;
2788
2789 // If this semantic expression is an opaque value, bind it
2790 // to the result of its source expression.
2791 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2792 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2793 OVMA opaqueData;
2794
2795 // If this semantic is the result of the pseudo-object
2796 // expression, try to evaluate the source as +1.
2797 if (ov == resultExpr) {
2798 assert(!OVMA::shouldBindAsLValue(ov));
John McCalle399e5b2016-01-27 18:32:30 +00002799 result = asImpl().visit(ov->getSourceExpr());
2800 opaqueData = OVMA::bind(CGF, ov,
2801 RValue::get(asImpl().getValueOfResult(result)));
John McCallfe96e0b2011-11-06 09:01:30 +00002802
2803 // Otherwise, just bind it.
2804 } else {
2805 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2806 }
2807 opaques.push_back(opaqueData);
2808
2809 // Otherwise, if the expression is the result, evaluate it
2810 // and remember the result.
2811 } else if (semantic == resultExpr) {
John McCalle399e5b2016-01-27 18:32:30 +00002812 result = asImpl().visit(semantic);
John McCallfe96e0b2011-11-06 09:01:30 +00002813
2814 // Otherwise, evaluate the expression in an ignored context.
2815 } else {
2816 CGF.EmitIgnoredExpr(semantic);
2817 }
2818 }
2819
2820 // Unbind all the opaques now.
2821 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2822 opaques[i].unbind(CGF);
2823
2824 return result;
2825}
2826
John McCalle399e5b2016-01-27 18:32:30 +00002827template <typename Impl, typename Result>
2828Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2829 switch (e->getCastKind()) {
John McCall53848232011-07-27 01:07:15 +00002830
John McCalle399e5b2016-01-27 18:32:30 +00002831 // No-op casts don't change the type, so we just ignore them.
2832 case CK_NoOp:
2833 return asImpl().visit(e->getSubExpr());
John McCall31168b02011-06-15 23:02:42 +00002834
John McCalle399e5b2016-01-27 18:32:30 +00002835 // These casts can change the type.
2836 case CK_CPointerToObjCPointerCast:
2837 case CK_BlockPointerToObjCPointerCast:
2838 case CK_AnyPointerToBlockPointerCast:
2839 case CK_BitCast: {
2840 llvm::Type *resultType = CGF.ConvertType(e->getType());
2841 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2842 Result result = asImpl().visit(e->getSubExpr());
2843 return asImpl().emitBitCast(result, resultType);
John McCall31168b02011-06-15 23:02:42 +00002844 }
2845
John McCalle399e5b2016-01-27 18:32:30 +00002846 // Handle some casts specially.
2847 case CK_LValueToRValue:
2848 return asImpl().visitLValueToRValue(e->getSubExpr());
2849 case CK_ARCConsumeObject:
2850 return asImpl().visitConsumeObject(e->getSubExpr());
2851 case CK_ARCExtendBlockObject:
2852 return asImpl().visitExtendBlockObject(e->getSubExpr());
2853 case CK_ARCReclaimReturnedObject:
2854 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2855
2856 // Otherwise, use the default logic.
2857 default:
2858 return asImpl().visitExpr(e);
2859 }
2860}
2861
2862template <typename Impl, typename Result>
2863Result
2864ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2865 switch (e->getOpcode()) {
2866 case BO_Comma:
2867 CGF.EmitIgnoredExpr(e->getLHS());
2868 CGF.EnsureInsertPoint();
2869 return asImpl().visit(e->getRHS());
2870
2871 case BO_Assign:
2872 return asImpl().visitBinAssign(e);
2873
2874 default:
2875 return asImpl().visitExpr(e);
2876 }
2877}
2878
2879template <typename Impl, typename Result>
2880Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2881 switch (e->getLHS()->getType().getObjCLifetime()) {
2882 case Qualifiers::OCL_ExplicitNone:
2883 return asImpl().visitBinAssignUnsafeUnretained(e);
2884
2885 case Qualifiers::OCL_Weak:
2886 return asImpl().visitBinAssignWeak(e);
2887
2888 case Qualifiers::OCL_Autoreleasing:
2889 return asImpl().visitBinAssignAutoreleasing(e);
2890
2891 case Qualifiers::OCL_Strong:
2892 return asImpl().visitBinAssignStrong(e);
2893
2894 case Qualifiers::OCL_None:
2895 return asImpl().visitExpr(e);
2896 }
2897 llvm_unreachable("bad ObjC ownership qualifier");
2898}
2899
2900/// The default rule for __unsafe_unretained emits the RHS recursively,
2901/// stores into the unsafe variable, and propagates the result outward.
2902template <typename Impl, typename Result>
2903Result ARCExprEmitter<Impl,Result>::
2904 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2905 // Recursively emit the RHS.
2906 // For __block safety, do this before emitting the LHS.
2907 Result result = asImpl().visit(e->getRHS());
2908
2909 // Perform the store.
2910 LValue lvalue =
2911 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2912 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2913 lvalue);
2914
2915 return result;
2916}
2917
2918template <typename Impl, typename Result>
2919Result
2920ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2921 return asImpl().visitExpr(e);
2922}
2923
2924template <typename Impl, typename Result>
2925Result
2926ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
2927 return asImpl().visitExpr(e);
2928}
2929
2930template <typename Impl, typename Result>
2931Result
2932ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
2933 return asImpl().visitExpr(e);
2934}
2935
2936/// The general expression-emission logic.
2937template <typename Impl, typename Result>
2938Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
2939 // We should *never* see a nested full-expression here, because if
2940 // we fail to emit at +1, our caller must not retain after we close
2941 // out the full-expression. This isn't as important in the unsafe
2942 // emitter.
2943 assert(!isa<ExprWithCleanups>(e));
2944
2945 // Look through parens, __extension__, generic selection, etc.
2946 e = e->IgnoreParens();
2947
2948 // Handle certain kinds of casts.
2949 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2950 return asImpl().visitCastExpr(ce);
2951
2952 // Handle the comma operator.
2953 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
2954 return asImpl().visitBinaryOperator(op);
2955
2956 // TODO: handle conditional operators here
2957
2958 // For calls and message sends, use the retained-call logic.
2959 // Delegate inits are a special case in that they're the only
2960 // returns-retained expression that *isn't* surrounded by
2961 // a consume.
2962 } else if (isa<CallExpr>(e) ||
2963 (isa<ObjCMessageExpr>(e) &&
2964 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2965 return asImpl().visitCall(e);
2966
2967 // Look through pseudo-object expressions.
2968 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2969 return asImpl().visitPseudoObjectExpr(pseudo);
2970 }
2971
2972 return asImpl().visitExpr(e);
2973}
2974
2975namespace {
2976
2977/// An emitter for +1 results.
2978struct ARCRetainExprEmitter :
2979 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
2980
2981 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
2982
2983 llvm::Value *getValueOfResult(TryEmitResult result) {
2984 return result.getPointer();
2985 }
2986
2987 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
2988 llvm::Value *value = result.getPointer();
2989 value = CGF.Builder.CreateBitCast(value, resultType);
2990 result.setPointer(value);
2991 return result;
2992 }
2993
2994 TryEmitResult visitLValueToRValue(const Expr *e) {
2995 return tryEmitARCRetainLoadOfScalar(CGF, e);
2996 }
2997
2998 /// For consumptions, just emit the subexpression and thus elide
2999 /// the retain/release pair.
3000 TryEmitResult visitConsumeObject(const Expr *e) {
3001 llvm::Value *result = CGF.EmitScalarExpr(e);
3002 return TryEmitResult(result, true);
3003 }
3004
3005 /// Block extends are net +0. Naively, we could just recurse on
3006 /// the subexpression, but actually we need to ensure that the
3007 /// value is copied as a block, so there's a little filter here.
3008 TryEmitResult visitExtendBlockObject(const Expr *e) {
3009 llvm::Value *result; // will be a +0 value
3010
3011 // If we can't safely assume the sub-expression will produce a
3012 // block-copied value, emit the sub-expression at +0.
3013 if (shouldEmitSeparateBlockRetain(e)) {
3014 result = CGF.EmitScalarExpr(e);
3015
3016 // Otherwise, try to emit the sub-expression at +1 recursively.
3017 } else {
3018 TryEmitResult subresult = asImpl().visit(e);
3019
3020 // If that produced a retained value, just use that.
3021 if (subresult.getInt()) {
3022 return subresult;
3023 }
3024
3025 // Otherwise it's +0.
3026 result = subresult.getPointer();
3027 }
3028
3029 // Retain the object as a block.
3030 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
3031 return TryEmitResult(result, true);
3032 }
3033
3034 /// For reclaims, emit the subexpression as a retained call and
3035 /// skip the consumption.
3036 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
3037 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3038 return TryEmitResult(result, true);
3039 }
3040
3041 /// When we have an undecorated call, retroactively do a claim.
3042 TryEmitResult visitCall(const Expr *e) {
3043 llvm::Value *result = emitARCRetainCallResult(CGF, e);
3044 return TryEmitResult(result, true);
3045 }
3046
3047 // TODO: maybe special-case visitBinAssignWeak?
3048
3049 TryEmitResult visitExpr(const Expr *e) {
3050 // We didn't find an obvious production, so emit what we've got and
3051 // tell the caller that we didn't manage to retain.
3052 llvm::Value *result = CGF.EmitScalarExpr(e);
3053 return TryEmitResult(result, false);
3054 }
3055};
3056}
3057
3058static TryEmitResult
3059tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
3060 return ARCRetainExprEmitter(CGF).visit(e);
John McCall31168b02011-06-15 23:02:42 +00003061}
3062
3063static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
3064 LValue lvalue,
3065 QualType type) {
3066 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
3067 llvm::Value *value = result.getPointer();
3068 if (!result.getInt())
3069 value = CGF.EmitARCRetain(type, value);
3070 return value;
3071}
3072
3073/// EmitARCRetainScalarExpr - Semantically equivalent to
3074/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
3075/// best-effort attempt to peephole expressions that naturally produce
3076/// retained objects.
3077llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003078 // The retain needs to happen within the full-expression.
3079 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3080 enterFullExpression(cleanups);
3081 RunCleanupsScope scope(*this);
3082 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
3083 }
3084
John McCall31168b02011-06-15 23:02:42 +00003085 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3086 llvm::Value *value = result.getPointer();
3087 if (!result.getInt())
3088 value = EmitARCRetain(e->getType(), value);
3089 return value;
3090}
3091
3092llvm::Value *
3093CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00003094 // The retain needs to happen within the full-expression.
3095 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3096 enterFullExpression(cleanups);
3097 RunCleanupsScope scope(*this);
3098 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
3099 }
3100
John McCall31168b02011-06-15 23:02:42 +00003101 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
3102 llvm::Value *value = result.getPointer();
3103 if (result.getInt())
3104 value = EmitARCAutorelease(value);
3105 else
3106 value = EmitARCRetainAutorelease(e->getType(), value);
3107 return value;
3108}
3109
John McCallff613032011-10-04 06:23:45 +00003110llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3111 llvm::Value *result;
3112 bool doRetain;
3113
3114 if (shouldEmitSeparateBlockRetain(e)) {
3115 result = EmitScalarExpr(e);
3116 doRetain = true;
3117 } else {
3118 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3119 result = subresult.getPointer();
3120 doRetain = !subresult.getInt();
3121 }
3122
3123 if (doRetain)
3124 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3125 return EmitObjCConsumeObject(e->getType(), result);
3126}
3127
John McCall248512a2011-10-01 10:32:24 +00003128llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3129 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003130 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00003131 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00003132 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00003133 return EmitARCRetainAutoreleaseScalarExpr(expr);
3134 }
3135
3136 // Otherwise, use the normal scalar-expression emission. The
3137 // exception machinery doesn't do anything special with the
3138 // exception like retaining it, so there's no safety associated with
3139 // only running cleanups after the throw has started, and when it
3140 // matters it tends to be substantially inferior code.
3141 return EmitScalarExpr(expr);
3142}
3143
John McCalle399e5b2016-01-27 18:32:30 +00003144namespace {
3145
3146/// An emitter for assigning into an __unsafe_unretained context.
3147struct ARCUnsafeUnretainedExprEmitter :
3148 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3149
3150 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3151
3152 llvm::Value *getValueOfResult(llvm::Value *value) {
3153 return value;
3154 }
3155
3156 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3157 return CGF.Builder.CreateBitCast(value, resultType);
3158 }
3159
3160 llvm::Value *visitLValueToRValue(const Expr *e) {
3161 return CGF.EmitScalarExpr(e);
3162 }
3163
3164 /// For consumptions, just emit the subexpression and perform the
3165 /// consumption like normal.
3166 llvm::Value *visitConsumeObject(const Expr *e) {
3167 llvm::Value *value = CGF.EmitScalarExpr(e);
3168 return CGF.EmitObjCConsumeObject(e->getType(), value);
3169 }
3170
3171 /// No special logic for block extensions. (This probably can't
3172 /// actually happen in this emitter, though.)
3173 llvm::Value *visitExtendBlockObject(const Expr *e) {
3174 return CGF.EmitARCExtendBlockObject(e);
3175 }
3176
3177 /// For reclaims, perform an unsafeClaim if that's enabled.
3178 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3179 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3180 }
3181
3182 /// When we have an undecorated call, just emit it without adding
3183 /// the unsafeClaim.
3184 llvm::Value *visitCall(const Expr *e) {
3185 return CGF.EmitScalarExpr(e);
3186 }
3187
3188 /// Just do normal scalar emission in the default case.
3189 llvm::Value *visitExpr(const Expr *e) {
3190 return CGF.EmitScalarExpr(e);
3191 }
3192};
3193}
3194
3195static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3196 const Expr *e) {
3197 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3198}
3199
3200/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3201/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3202/// avoiding any spurious retains, including by performing reclaims
3203/// with objc_unsafeClaimAutoreleasedReturnValue.
3204llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3205 // Look through full-expressions.
3206 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3207 enterFullExpression(cleanups);
3208 RunCleanupsScope scope(*this);
3209 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3210 }
3211
3212 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3213}
3214
3215std::pair<LValue,llvm::Value*>
3216CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3217 bool ignored) {
3218 // Evaluate the RHS first. If we're ignoring the result, assume
3219 // that we can emit at an unsafe +0.
3220 llvm::Value *value;
3221 if (ignored) {
3222 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3223 } else {
3224 value = EmitScalarExpr(e->getRHS());
3225 }
3226
3227 // Emit the LHS and perform the store.
3228 LValue lvalue = EmitLValue(e->getLHS());
3229 EmitStoreOfScalar(value, lvalue);
3230
3231 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3232}
3233
John McCall31168b02011-06-15 23:02:42 +00003234std::pair<LValue,llvm::Value*>
3235CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3236 bool ignored) {
3237 // Evaluate the RHS first.
3238 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3239 llvm::Value *value = result.getPointer();
3240
John McCallb726a552011-07-28 07:23:35 +00003241 bool hasImmediateRetain = result.getInt();
3242
3243 // If we didn't emit a retained object, and the l-value is of block
3244 // type, then we need to emit the block-retain immediately in case
3245 // it invalidates the l-value.
3246 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00003247 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00003248 hasImmediateRetain = true;
3249 }
3250
John McCall31168b02011-06-15 23:02:42 +00003251 LValue lvalue = EmitLValue(e->getLHS());
3252
3253 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00003254 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00003255 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00003256 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00003257 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00003258 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00003259 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00003260 }
3261
3262 return std::pair<LValue,llvm::Value*>(lvalue, value);
3263}
3264
3265std::pair<LValue,llvm::Value*>
3266CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3267 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3268 LValue lvalue = EmitLValue(e->getLHS());
3269
Eli Friedmana0544d62011-12-03 04:14:32 +00003270 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00003271
3272 return std::pair<LValue,llvm::Value*>(lvalue, value);
3273}
3274
3275void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003276 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00003277 const Stmt *subStmt = ARPS.getSubStmt();
3278 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3279
3280 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00003281 if (DI)
3282 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003283
3284 // Keep track of the current cleanup stack depth.
3285 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00003286 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00003287 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3288 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3289 } else {
3290 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3291 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3292 }
3293
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003294 for (const auto *I : S.body())
3295 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00003296
Eric Christopher7cdf9482011-10-13 21:45:18 +00003297 if (DI)
3298 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00003299}
John McCall1bd25562011-06-24 23:21:27 +00003300
3301/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3302/// make sure it survives garbage collection until this point.
3303void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3304 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00003305 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00003306 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00003307 llvm::Value *extender
3308 = llvm::InlineAsm::get(extenderType,
3309 /* assembly */ "",
3310 /* constraints */ "r",
3311 /* side effects */ true);
3312
3313 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00003314 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00003315}
3316
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003317/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003318/// non-trivial copy assignment function, produce following helper function.
3319/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3320///
3321llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003322CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3323 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003324 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003325 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003326 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003327 QualType Ty = PID->getPropertyIvarDecl()->getType();
3328 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003329 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003330 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003331 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003332 return nullptr;
3333 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003334 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003335 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003336 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3337 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3338 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003339
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003340 ASTContext &C = getContext();
3341 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003342 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003343
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003344 QualType ReturnTy = C.VoidTy;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003345 QualType DestTy = C.getPointerType(Ty);
3346 QualType SrcTy = Ty;
3347 SrcTy.addConst();
3348 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003349
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003350 SmallVector<QualType, 2> ArgTys;
3351 ArgTys.push_back(DestTy);
3352 ArgTys.push_back(SrcTy);
3353 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3354
3355 FunctionDecl *FD = FunctionDecl::Create(
3356 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3357 FunctionTy, nullptr, SC_Static, false, false);
3358
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003359 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003360 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3361 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003362 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003363 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3364 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003365 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003366
John McCallc56a8b32016-03-11 04:30:31 +00003367 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003368 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003369
John McCalla729c622012-02-17 03:33:10 +00003370 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003371
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003372 llvm::Function *Fn =
3373 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003374 "__assign_helper_atomic_property_",
3375 &CGM.getModule());
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003376
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003377 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003378
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003379 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003380
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003381 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3382 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003383 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003384 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003385
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003386 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3387 SourceLocation());
John McCall113bee02012-03-10 09:33:50 +00003388 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003389 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003390
John McCall113bee02012-03-10 09:33:50 +00003391 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003392 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Bruno Riccic5885cf2018-12-21 15:20:32 +00003393 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
3394 C, OO_Equal, CalleeExp->getCallee(), Args, DestTy->getPointeeType(),
3395 VK_LValue, SourceLocation(), FPOptions());
Fangrui Song6907ce22018-07-30 19:24:48 +00003396
Bruno Riccic5885cf2018-12-21 15:20:32 +00003397 EmitStmt(TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003398
3399 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003400 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003401 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00003402 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003403}
3404
3405llvm::Constant *
3406CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3407 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00003408 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00003409 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00003410 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003411 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3412 QualType Ty = PD->getType();
3413 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00003414 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003415 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00003416 return nullptr;
3417 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003418 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00003419 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003420 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3421 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3422 return HelperFn;
Fangrui Song6907ce22018-07-30 19:24:48 +00003423
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003424 ASTContext &C = getContext();
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003425 IdentifierInfo *II =
3426 &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
Craig Topper8a13c412014-05-21 05:09:00 +00003427
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003428 QualType ReturnTy = C.VoidTy;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003429 QualType DestTy = C.getPointerType(Ty);
3430 QualType SrcTy = Ty;
3431 SrcTy.addConst();
3432 SrcTy = C.getPointerType(SrcTy);
Fangrui Song6907ce22018-07-30 19:24:48 +00003433
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003434 SmallVector<QualType, 2> ArgTys;
3435 ArgTys.push_back(DestTy);
3436 ArgTys.push_back(SrcTy);
3437 QualType FunctionTy = C.getFunctionType(ReturnTy, ArgTys, {});
3438
3439 FunctionDecl *FD = FunctionDecl::Create(
3440 C, C.getTranslationUnitDecl(), SourceLocation(), SourceLocation(), II,
3441 FunctionTy, nullptr, SC_Static, false, false);
3442
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003443 FunctionArgList args;
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003444 ImplicitParamDecl DstDecl(C, FD, SourceLocation(), /*Id=*/nullptr, DestTy,
3445 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003446 args.push_back(&DstDecl);
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003447 ImplicitParamDecl SrcDecl(C, FD, SourceLocation(), /*Id=*/nullptr, SrcTy,
3448 ImplicitParamDecl::Other);
Alexey Bataev56223232017-06-09 13:40:18 +00003449 args.push_back(&SrcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00003450
John McCallc56a8b32016-03-11 04:30:31 +00003451 const CGFunctionInfo &FI =
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003452 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
Reid Kleckner4982b822014-01-31 22:54:50 +00003453
John McCalla729c622012-02-17 03:33:10 +00003454 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fangrui Song6907ce22018-07-30 19:24:48 +00003455
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003456 llvm::Function *Fn = llvm::Function::Create(
3457 LTy, llvm::GlobalValue::InternalLinkage, "__copy_helper_atomic_property_",
3458 &CGM.getModule());
Rafael Espindola51ec5a92018-02-28 23:46:35 +00003459
3460 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
Akira Hatanaka44a59f82015-10-28 02:30:47 +00003461
Jonas Devlieghere64a26302018-11-11 00:56:15 +00003462 StartFunction(FD, ReturnTy, Fn, FI, args);
Fangrui Song6907ce22018-07-30 19:24:48 +00003463
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003464 DeclRefExpr SrcExpr(getContext(), &SrcDecl, false, SrcTy, VK_RValue,
3465 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003466
John McCall113bee02012-03-10 09:33:50 +00003467 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
Aaron Ballmana5038552018-01-09 13:07:03 +00003468 VK_LValue, OK_Ordinary, SourceLocation(), false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003469
3470 CXXConstructExpr *CXXConstExpr =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003471 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
Fangrui Song6907ce22018-07-30 19:24:48 +00003472
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003473 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00003474 ConstructorArgs.push_back(&SRC);
Benjamin Kramerf367dd92015-06-12 15:31:50 +00003475 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3476 CXXConstExpr->arg_end());
3477
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003478 CXXConstructExpr *TheCXXConstructExpr =
3479 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3480 CXXConstExpr->getConstructor(),
3481 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003482 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003483 CXXConstExpr->hadMultipleCandidates(),
3484 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003485 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003486 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003487 CXXConstExpr->getConstructionKind(),
3488 SourceRange());
Fangrui Song6907ce22018-07-30 19:24:48 +00003489
Bruno Ricci5fc4db72018-12-21 14:10:18 +00003490 DeclRefExpr DstExpr(getContext(), &DstDecl, false, DestTy, VK_RValue,
3491 SourceLocation());
Fangrui Song6907ce22018-07-30 19:24:48 +00003492
John McCall113bee02012-03-10 09:33:50 +00003493 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003494 CharUnits Alignment
3495 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fangrui Song6907ce22018-07-30 19:24:48 +00003496 EmitAggExpr(TheCXXConstructExpr,
John McCall7f416cc2015-09-08 08:05:57 +00003497 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3498 Qualifiers(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003499 AggValueSlot::IsDestructed,
3500 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +00003501 AggValueSlot::IsNotAliased,
3502 AggValueSlot::DoesNotOverlap));
Fangrui Song6907ce22018-07-30 19:24:48 +00003503
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003504 FinishFunction();
3505 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3506 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3507 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003508}
3509
Eli Friedmanec75fec2012-02-28 01:08:45 +00003510llvm::Value *
3511CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3512 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003513 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3514 Selector CopySelector =
3515 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003516 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3517 Selector AutoreleaseSelector =
3518 getContext().Selectors.getNullarySelector(AutoreleaseID);
3519
3520 // Emit calls to retain/autorelease.
3521 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3522 llvm::Value *Val = Block;
3523 RValue Result;
3524 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003525 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003526 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003527 Val = Result.getScalarVal();
3528 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3529 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003530 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003531 Val = Result.getScalarVal();
3532 return Val;
3533}
3534
Erik Pilkington9c42a8d2017-02-23 21:08:08 +00003535llvm::Value *
3536CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3537 assert(Args.size() == 3 && "Expected 3 argument here!");
3538
3539 if (!CGM.IsOSVersionAtLeastFn) {
3540 llvm::FunctionType *FTy =
3541 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3542 CGM.IsOSVersionAtLeastFn =
3543 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3544 }
3545
3546 llvm::Value *CallRes =
3547 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3548
3549 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3550}
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003551
Alex Lorenza8fbef42017-03-23 11:14:27 +00003552void CodeGenModule::emitAtAvailableLinkGuard() {
3553 if (!IsOSVersionAtLeastFn)
3554 return;
3555 // @available requires CoreFoundation only on Darwin.
3556 if (!Target.getTriple().isOSDarwin())
3557 return;
3558 // Add -framework CoreFoundation to the linker commands. We still want to
3559 // emit the core foundation reference down below because otherwise if
3560 // CoreFoundation is not used in the code, the linker won't link the
3561 // framework.
3562 auto &Context = getLLVMContext();
3563 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3564 llvm::MDString::get(Context, "CoreFoundation")};
3565 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3566 // Emit a reference to a symbol from CoreFoundation to ensure that
3567 // CoreFoundation is linked into the final binary.
3568 llvm::FunctionType *FTy =
3569 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3570 llvm::Constant *CFFunc =
3571 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3572
3573 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3574 llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3575 CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3576 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3577 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3578 CodeGenFunction CGF(*this);
3579 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3580 CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3581 CGF.Builder.CreateUnreachable();
3582 addCompilerUsedGlobal(CFLinkCheckFunc);
3583}
3584
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00003585CGObjCRuntime::~CGObjCRuntime() {}