blob: f26263d9472d37a740582a9401cfaba2f80aa002 [file] [log] [blame]
Erik Pilkington7884e5f2017-02-21 20:31:01 +00001//===---- CGObjC.cpp - Emit LLVM Code for Objective-C ---------------------===//
Anders Carlsson55085182007-08-21 17:43:55 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Mark Lacey8b549992013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruth235e24a2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCallf85e1932011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Douglas Gregora6620f32015-07-07 03:57:53 +000034static RValue AdjustObjCObjectType(CodeGenFunction &CGF,
35 QualType ET,
36 RValue Result);
John McCallf85e1932011-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 McCallf4ddf942015-09-08 08:05:57 +000040static llvm::Constant *getNullForVariable(Address addr) {
41 llvm::Type *type = addr.getElementType();
John McCallf85e1932011-06-15 23:02:42 +000042 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattner8fdf3282008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000047{
David Chisnall0d13f6f2010-01-23 02:40:42 +000048 llvm::Constant *C =
John McCallf4ddf942015-09-08 08:05:57 +000049 CGM.getObjCRuntime().GenerateConstantString(E->getString()).getPointer();
Daniel Dunbared7c6182008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000052}
53
Patrick Beardeb382ec2012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
Alex Denisov38490762015-06-26 05:28:36 +000056/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:],
57/// or [NSValue valueWithBytes:objCType:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000058///
Eric Christopher16098f32012-03-29 17:31:31 +000059llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Get the method.
Patrick Beardeb382ec2012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
Alex Denisov38490762015-06-26 05:28:36 +000064 const Expr *SubExpr = E->getSubExpr();
Patrick Beardeb382ec2012-04-19 00:25:12 +000065 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-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 Kremenekebcb57a2012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCallbd7370a2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian2a8f5082014-12-18 17:13:56 +000075
Ted Kremenekebcb57a2012-03-06 20:05:56 +000076 CallArgList Args;
Alex Denisov38490762015-06-26 05:28:36 +000077 const ParmVarDecl *ArgDecl = *BoxingMethod->param_begin();
78 QualType ArgQT = ArgDecl->getType().getUnqualifiedType();
79
80 // ObjCBoxedExpr supports boxing of structs and unions
81 // via [NSValue valueWithBytes:objCType:]
82 const QualType ValueType(SubExpr->getType().getCanonicalType());
83 if (ValueType->isObjCBoxableRecordType()) {
84 // Emit CodeGen for first parameter
85 // and cast value to correct type
John McCallf4ddf942015-09-08 08:05:57 +000086 Address Temporary = CreateMemTemp(SubExpr->getType());
Alex Denisov38490762015-06-26 05:28:36 +000087 EmitAnyExprToMem(SubExpr, Temporary, Qualifiers(), /*isInit*/ true);
John McCallf4ddf942015-09-08 08:05:57 +000088 Address BitCast = Builder.CreateBitCast(Temporary, ConvertType(ArgQT));
89 Args.add(RValue::get(BitCast.getPointer()), ArgQT);
Alex Denisov38490762015-06-26 05:28:36 +000090
91 // Create char array to store type encoding
92 std::string Str;
93 getContext().getObjCEncodingForType(ValueType, Str);
John McCallf4ddf942015-09-08 08:05:57 +000094 llvm::Constant *GV = CGM.GetAddrOfConstantCString(Str).getPointer();
Alex Denisov38490762015-06-26 05:28:36 +000095
96 // Cast type encoding to correct type
97 const ParmVarDecl *EncodingDecl = BoxingMethod->parameters()[1];
98 QualType EncodingQT = EncodingDecl->getType().getUnqualifiedType();
99 llvm::Value *Cast = Builder.CreateBitCast(GV, ConvertType(EncodingQT));
100
101 Args.add(RValue::get(Cast), EncodingQT);
102 } else {
103 Args.add(EmitAnyExpr(SubExpr), ArgQT);
104 }
Alp Toker37545f72014-01-25 16:55:45 +0000105
106 RValue result = Runtime.GenerateMessageSend(
107 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
108 Args, ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000109 return Builder.CreateBitCast(result.getScalarVal(),
110 ConvertType(E->getType()));
111}
112
113llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian951324d2014-10-28 18:28:16 +0000114 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000115 ASTContext &Context = CGM.getContext();
Craig Topperd1008e52014-05-21 05:09:00 +0000116 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000117 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
118 if (!ALE)
119 DLE = cast<ObjCDictionaryLiteral>(E);
Akira Hatanaka6b1aefd2017-04-15 06:42:00 +0000120
121 // Optimize empty collections by referencing constants, when available.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000122 uint64_t NumElements =
123 ALE ? ALE->getNumElements() : DLE->getNumElements();
Akira Hatanaka6b1aefd2017-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 Hatanaka9a22a282017-04-17 15:21:55 +0000129 LValue LV = MakeNaturalAlignAddrLValue(Constant, IdTy);
130 llvm::Value *Ptr = EmitLoadOfScalar(LV, E->getLocStart());
131 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 Hatanaka6b1aefd2017-04-15 06:42:00 +0000135 }
136
137 // Compute the type of the array we're initializing.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000138 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
139 NumElements);
140 QualType ElementType = Context.getObjCIdType().withConst();
141 QualType ElementArrayType
142 = Context.getConstantArrayType(ElementType, APNumElements,
143 ArrayType::Normal, /*IndexTypeQuals=*/0);
144
145 // Allocate the temporary array(s).
John McCallf4ddf942015-09-08 08:05:57 +0000146 Address Objects = CreateMemTemp(ElementArrayType, "objects");
147 Address Keys = Address::invalid();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000148 if (DLE)
149 Keys = CreateMemTemp(ElementArrayType, "keys");
150
John McCall527842f2013-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 Kremenekebcb57a2012-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 McCall527842f2013-04-04 00:20:38 +0000161 // Emit the element and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000162 const Expr *Rhs = ALE->getElement(i);
John McCallf4ddf942015-09-08 08:05:57 +0000163 LValue LV = MakeAddrLValue(
164 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarevbb7654d2017-10-10 09:39:32 +0000165 ElementType, AlignmentSource::Decl);
John McCall527842f2013-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 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000172 } else {
John McCall527842f2013-04-04 00:20:38 +0000173 // Emit the key and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000174 const Expr *Key = DLE->getKeyValueElement(i).Key;
John McCallf4ddf942015-09-08 08:05:57 +0000175 LValue KeyLV = MakeAddrLValue(
176 Builder.CreateConstArrayGEP(Keys, i, getPointerSize()),
Ivan A. Kosarevbb7654d2017-10-10 09:39:32 +0000177 ElementType, AlignmentSource::Decl);
John McCall527842f2013-04-04 00:20:38 +0000178 llvm::Value *keyValue = EmitScalarExpr(Key);
179 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000180
John McCall527842f2013-04-04 00:20:38 +0000181 // Emit the value and store it to the appropriate array slot.
David Blaikie43956992015-04-05 22:45:47 +0000182 const Expr *Value = DLE->getKeyValueElement(i).Value;
John McCallf4ddf942015-09-08 08:05:57 +0000183 LValue ValueLV = MakeAddrLValue(
184 Builder.CreateConstArrayGEP(Objects, i, getPointerSize()),
Ivan A. Kosarevbb7654d2017-10-10 09:39:32 +0000185 ElementType, AlignmentSource::Decl);
John McCall527842f2013-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 Kremenekebcb57a2012-03-06 20:05:56 +0000192 }
193 }
194
195 // Generate the argument list.
196 CallArgList Args;
197 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
198 const ParmVarDecl *argDecl = *PI++;
199 QualType ArgQT = argDecl->getType().getUnqualifiedType();
John McCallf4ddf942015-09-08 08:05:57 +0000200 Args.add(RValue::get(Objects.getPointer()), ArgQT);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000201 if (DLE) {
202 argDecl = *PI++;
203 ArgQT = argDecl->getType().getUnqualifiedType();
John McCallf4ddf942015-09-08 08:05:57 +0000204 Args.add(RValue::get(Keys.getPointer()), ArgQT);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000205 }
206 argDecl = *PI;
207 ArgQT = argDecl->getType().getUnqualifiedType();
208 llvm::Value *Count =
209 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();
217 ObjCInterfaceDecl *Class
218 = InterfacePointerType->getObjectType()->getInterface();
219 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +0000220 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000221
222 // Generate the message send.
Alp Toker37545f72014-01-25 16:55:45 +0000223 RValue result = Runtime.GenerateMessageSend(
224 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
225 Receiver, Args, Class, MethodWithObjects);
John McCall527842f2013-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
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000235 return Builder.CreateBitCast(result.getScalarVal(),
236 ConvertType(E->getType()));
237}
238
239llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian951324d2014-10-28 18:28:16 +0000240 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000241}
242
243llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
244 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian951324d2014-10-28 18:28:16 +0000245 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000246}
247
Chris Lattner8fdf3282008-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 McCallbd7370a2013-02-28 19:01:20 +0000254 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000255}
256
Daniel Dunbared7c6182008-08-20 00:28:19 +0000257llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
258 // FIXME: This should pass the Decl not the name.
John McCallbd7370a2013-02-28 19:01:20 +0000259 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbared7c6182008-08-20 00:28:19 +0000260}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000261
Douglas Gregora6620f32015-07-07 03:57:53 +0000262/// \brief Adjust the type of an Objective-C object that doesn't match up due
263/// 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 Gregor926df6c2011-06-11 01:09:30 +0000268 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000269
Douglas Gregora6620f32015-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 Gregor926df6c2011-06-11 01:09:30 +0000273 return Result;
Douglas Gregora6620f32015-07-07 03:57:53 +0000274
275 // We have applied a substitution. Cast the rvalue appropriately.
Douglas Gregor926df6c2011-06-11 01:09:30 +0000276 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Douglas Gregora6620f32015-07-07 03:57:53 +0000277 ExpLLVMTy));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000278}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000279
John McCalldc7c5ad2011-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 McCalle9341ab2015-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 McCalldc7c5ad2011-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 McCalle9341ab2015-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 McCalldc7c5ad2011-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 McCallabdd8242015-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
John McCallef072fd2010-05-22 01:48:05 +0000355RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
356 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000357 // Only the lookup mechanism and first two arguments of the method
358 // implementation vary between runtimes. We can get the receiver and
359 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000360
John McCallf85e1932011-06-15 23:02:42 +0000361 bool isDelegateInit = E->isDelegateInitCall();
362
John McCalldc7c5ad2011-07-22 08:53:00 +0000363 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000364
John McCallabdd8242015-10-22 18:38:17 +0000365 // If the method is -retain, and the receiver's being loaded from
366 // a __weak variable, peephole the entire operation to objc_loadWeakRetained.
367 if (method && E->getReceiverKind() == ObjCMessageExpr::Instance &&
368 method->getMethodFamily() == OMF_retain) {
369 if (auto lvalueExpr = findWeakLValue(E->getInstanceReceiver())) {
370 LValue lvalue = EmitLValue(lvalueExpr);
371 llvm::Value *result = EmitARCLoadWeakRetained(lvalue.getAddress());
372 return AdjustObjCObjectType(*this, E->getType(), RValue::get(result));
373 }
374 }
375
John McCallf85e1932011-06-15 23:02:42 +0000376 // We don't retain the receiver in delegate init calls, and this is
377 // safe because the receiver value is always loaded from 'self',
378 // which we zero out. We don't want to Block_copy block receivers,
379 // though.
380 bool retainSelf =
381 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000382 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000383 method &&
384 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000385
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000386 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000387 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000388 bool isClassMessage = false;
Craig Topperd1008e52014-05-21 05:09:00 +0000389 ObjCInterfaceDecl *OID = nullptr;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000390 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000391 QualType ReceiverType;
Craig Topperd1008e52014-05-21 05:09:00 +0000392 llvm::Value *Receiver = nullptr;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000393 switch (E->getReceiverKind()) {
394 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000395 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000396 if (retainSelf) {
397 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
398 E->getInstanceReceiver());
399 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000400 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000401 } else
402 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000403 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000404
Douglas Gregor04badcf2010-04-21 00:45:42 +0000405 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000406 ReceiverType = E->getClassReceiver();
407 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000408 assert(ObjTy && "Invalid Objective-C class message send");
409 OID = ObjTy->getInterface();
410 assert(OID && "Invalid Objective-C class message send");
John McCallbd7370a2013-02-28 19:01:20 +0000411 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000412 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000413 break;
414 }
415
416 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000417 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000418 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000419 isSuperMessage = true;
420 break;
421
422 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000423 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000424 Receiver = LoadObjCSelf();
425 isSuperMessage = true;
426 isClassMessage = true;
427 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000428 }
429
John McCalldc7c5ad2011-07-22 08:53:00 +0000430 if (retainSelf)
431 Receiver = EmitARCRetainNonBlock(Receiver);
432
433 // In ARC, we sometimes want to "extend the lifetime"
434 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
435 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000436 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000437 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
438 shouldExtendReceiverForInnerPointerMessage(E))
439 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
440
Alp Toker37545f72014-01-25 16:55:45 +0000441 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000442
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000443 CallArgList Args;
Vedant Kumara7325b02017-03-06 05:28:22 +0000444 EmitCallArgs(Args, method, E->arguments(), /*AC*/AbstractCallee(method));
Mike Stump1eb44332009-09-09 15:08:12 +0000445
John McCallf85e1932011-06-15 23:02:42 +0000446 // For delegate init calls in ARC, do an unsafe store of null into
447 // self. This represents the call taking direct ownership of that
448 // value. We have to do this after emitting the other call
449 // arguments because they might also reference self, but we don't
450 // have to worry about any of them modifying self because that would
451 // be an undefined read and write of an object in unordered
452 // expressions.
453 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000454 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000455 "delegate init calls should only be marked in ARC");
456
457 // Do an unsafe store of null into self.
John McCallf4ddf942015-09-08 08:05:57 +0000458 Address selfAddr =
459 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCallf85e1932011-06-15 23:02:42 +0000460 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
461 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000462
Douglas Gregor926df6c2011-06-11 01:09:30 +0000463 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000464 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000465 // super is only valid in an Objective-C method
466 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000467 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000468 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
469 E->getSelector(),
470 OMD->getClassInterface(),
471 isCategoryImpl,
472 Receiver,
473 isClassMessage,
474 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000475 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000476 } else {
Pete Cooper2a988fc2016-03-21 20:50:03 +0000477 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
478 E->getSelector(),
479 Receiver, Args, OID,
480 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000481 }
John McCallf85e1932011-06-15 23:02:42 +0000482
483 // For delegate init calls in ARC, implicitly store the result of
484 // the call back into self. This takes ownership of the value.
485 if (isDelegateInit) {
John McCallf4ddf942015-09-08 08:05:57 +0000486 Address selfAddr =
487 GetAddrOfLocalVar(cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl());
John McCallf85e1932011-06-15 23:02:42 +0000488 llvm::Value *newSelf = result.getScalarVal();
489
490 // The delegate return type isn't necessarily a matching type; in
491 // fact, it's quite likely to be 'id'.
John McCallf4ddf942015-09-08 08:05:57 +0000492 llvm::Type *selfTy = selfAddr.getElementType();
John McCallf85e1932011-06-15 23:02:42 +0000493 newSelf = Builder.CreateBitCast(newSelf, selfTy);
494
495 Builder.CreateStore(newSelf, selfAddr);
496 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000497
Douglas Gregora6620f32015-07-07 03:57:53 +0000498 return AdjustObjCObjectType(*this, E->getType(), result);
Anders Carlsson55085182007-08-21 17:43:55 +0000499}
500
John McCallf85e1932011-06-15 23:02:42 +0000501namespace {
David Blaikie673861a2015-08-18 22:40:54 +0000502struct FinishARCDealloc final : EHScopeStack::Cleanup {
Craig Topperf7bc4972014-03-12 06:41:41 +0000503 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +0000504 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000505
506 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000507 const ObjCInterfaceDecl *iface = impl->getClassInterface();
508 if (!iface->getSuperClass()) return;
509
John McCall799d34e2011-07-13 18:26:47 +0000510 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
511
John McCallf85e1932011-06-15 23:02:42 +0000512 // Call [super dealloc] if we have a superclass.
513 llvm::Value *self = CGF.LoadObjCSelf();
514
515 CallArgList args;
516 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
517 CGF.getContext().VoidTy,
518 method->getSelector(),
519 iface,
John McCall799d34e2011-07-13 18:26:47 +0000520 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000521 self,
522 /*is class msg*/ false,
523 args,
524 method);
525 }
526};
Alexander Kornienko8ca77052015-06-22 23:07:51 +0000527}
John McCallf85e1932011-06-15 23:02:42 +0000528
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000529/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
530/// the LLVM function and sets the other context used by
531/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000532void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikie5fe8dcb2015-01-14 00:04:42 +0000533 const ObjCContainerDecl *CD) {
534 SourceLocation StartLoc = OMD->getLocStart();
John McCalld26bc762011-03-09 04:27:21 +0000535 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000536 // Check if we should generate debug info for this method.
David Blaikiec3030bc2013-08-26 20:33:21 +0000537 if (OMD->hasAttr<NoDebugAttr>())
Craig Topperd1008e52014-05-21 05:09:00 +0000538 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patel4800ea62010-04-05 21:09:15 +0000539
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000540 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000541
John McCallde5d3c72012-02-17 03:33:10 +0000542 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000543 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000544
John McCalld26bc762011-03-09 04:27:21 +0000545 args.push_back(OMD->getSelfDecl());
546 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000547
Benjamin Kramer57772dc2015-02-17 16:48:30 +0000548 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner41110242008-06-17 18:05:57 +0000549
Peter Collingbourne14110472011-01-13 18:57:25 +0000550 CurGD = OMD;
David Blaikie57732cd2015-01-14 07:10:46 +0000551 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne14110472011-01-13 18:57:25 +0000552
Adrian Prantl9a7c2b42014-04-10 23:21:53 +0000553 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
554 OMD->getLocation(), StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000555
556 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000557 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000558 OMD->isInstanceMethod() &&
559 OMD->getSelector().isUnarySelector()) {
560 const IdentifierInfo *ident =
561 OMD->getSelector().getIdentifierInfoForSlot(0);
562 if (ident->isStr("dealloc"))
563 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
564 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000565}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000566
John McCallf85e1932011-06-15 23:02:42 +0000567static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
568 LValue lvalue, QualType type);
569
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000570/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000571/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000572void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikie5fe8dcb2015-01-14 00:04:42 +0000573 StartObjCMethod(OMD, OMD->getClassInterface());
Serge Pavlov3a6fcd92015-12-06 14:32:39 +0000574 PGO.assignRegionCounters(GlobalDecl(OMD), CurFn);
Adrian Prantleebee8f2014-01-07 22:05:55 +0000575 assert(isa<CompoundStmt>(OMD->getBody()));
Justin Bogneraa53a4f2015-04-23 23:06:47 +0000576 incrementProfileCounter(OMD->getBody());
Adrian Prantleebee8f2014-01-07 22:05:55 +0000577 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000578 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000579}
580
John McCall41bdde92011-09-12 23:06:44 +0000581/// emitStructGetterCall - Call the runtime function to load a property
582/// into the return value slot.
583static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
584 bool isAtomic, bool hasStrong) {
585 ASTContext &Context = CGF.getContext();
586
John McCallf4ddf942015-09-08 08:05:57 +0000587 Address src =
588 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(), ivar, 0)
589 .getAddress();
John McCall41bdde92011-09-12 23:06:44 +0000590
591 // objc_copyStruct (ReturnValue, &structIvar,
592 // sizeof (Type of Ivar), isAtomic, false);
593 CallArgList args;
594
John McCallf4ddf942015-09-08 08:05:57 +0000595 Address dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
596 args.add(RValue::get(dest.getPointer()), Context.VoidPtrTy);
John McCall41bdde92011-09-12 23:06:44 +0000597
598 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
John McCallf4ddf942015-09-08 08:05:57 +0000599 args.add(RValue::get(src.getPointer()), Context.VoidPtrTy);
John McCall41bdde92011-09-12 23:06:44 +0000600
601 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
602 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
603 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
604 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
605
John McCalla896e9a2016-10-26 23:46:34 +0000606 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
607 CGCallee callee = CGCallee::forDirect(fn);
John McCall5af07632016-03-11 04:30:31 +0000608 CGF.EmitCall(CGF.getTypes().arrangeBuiltinFunctionCall(Context.VoidTy, args),
John McCalla896e9a2016-10-26 23:46:34 +0000609 callee, ReturnValueSlot(), args);
John McCall41bdde92011-09-12 23:06:44 +0000610}
611
John McCall1e1f4872011-09-13 03:34:09 +0000612/// Determine whether the given architecture supports unaligned atomic
613/// accesses. They don't have to be fast, just faster than a function
614/// call and a mutex.
615static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000616 // FIXME: Allow unaligned atomic load/store on x86. (It is not
617 // currently supported by the backend.)
618 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000619}
620
621/// Return the maximum size that permits atomic accesses for the given
622/// architecture.
623static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
624 llvm::Triple::ArchType arch) {
625 // ARM has 8-byte atomic accesses, but it's not clear whether we
626 // want to rely on them here.
627
628 // In the default case, just assume that any size up to a pointer is
629 // fine given adequate alignment.
630 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
631}
632
633namespace {
634 class PropertyImplStrategy {
635 public:
636 enum StrategyKind {
637 /// The 'native' strategy is to use the architecture's provided
638 /// reads and writes.
639 Native,
640
641 /// Use objc_setProperty and objc_getProperty.
642 GetSetProperty,
643
644 /// Use objc_setProperty for the setter, but use expression
645 /// evaluation for the getter.
646 SetPropertyAndExpressionGet,
647
648 /// Use objc_copyStruct.
649 CopyStruct,
650
651 /// The 'expression' strategy is to emit normal assignment or
652 /// lvalue-to-rvalue expressions.
653 Expression
654 };
655
656 StrategyKind getKind() const { return StrategyKind(Kind); }
657
658 bool hasStrongMember() const { return HasStrong; }
659 bool isAtomic() const { return IsAtomic; }
660 bool isCopy() const { return IsCopy; }
661
662 CharUnits getIvarSize() const { return IvarSize; }
663 CharUnits getIvarAlignment() const { return IvarAlignment; }
664
665 PropertyImplStrategy(CodeGenModule &CGM,
666 const ObjCPropertyImplDecl *propImpl);
667
668 private:
669 unsigned Kind : 8;
670 unsigned IsAtomic : 1;
671 unsigned IsCopy : 1;
672 unsigned HasStrong : 1;
673
674 CharUnits IvarSize;
675 CharUnits IvarAlignment;
676 };
Alexander Kornienko8ca77052015-06-22 23:07:51 +0000677}
John McCall1e1f4872011-09-13 03:34:09 +0000678
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000679/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000680PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
681 const ObjCPropertyImplDecl *propImpl) {
682 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000683 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000684
John McCall265941b2011-09-13 18:31:23 +0000685 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
686 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000687 HasStrong = false; // doesn't matter here.
688
689 // Evaluate the ivar's size and alignment.
690 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
691 QualType ivarType = ivar->getType();
Benjamin Kramerba9fd9e2014-03-02 13:01:17 +0000692 std::tie(IvarSize, IvarAlignment) =
693 CGM.getContext().getTypeInfoInChars(ivarType);
John McCall1e1f4872011-09-13 03:34:09 +0000694
695 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000696 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000697 if (IsCopy) {
698 Kind = GetSetProperty;
699 return;
700 }
701
John McCall265941b2011-09-13 18:31:23 +0000702 // Handle retain.
703 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000704 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000705 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000706 // fallthrough
707
708 // In ARC, if the property is non-atomic, use expression emission,
709 // which translates to objc_storeStrong. This isn't required, but
710 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000711 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld64c2eb2012-08-20 23:36:59 +0000712 // Using standard expression emission for the setter is only
713 // acceptable if the ivar is __strong, which won't be true if
714 // the property is annotated with __attribute__((NSObject)).
715 // TODO: falling all the way back to objc_setProperty here is
716 // just laziness, though; we could still use objc_storeStrong
717 // if we hacked it right.
718 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
719 Kind = Expression;
720 else
721 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000722 return;
723
724 // Otherwise, we need to at least use setProperty. However, if
725 // the property isn't atomic, we can use normal expression
726 // emission for the getter.
727 } else if (!IsAtomic) {
728 Kind = SetPropertyAndExpressionGet;
729 return;
730
731 // Otherwise, we have to use both setProperty and getProperty.
732 } else {
733 Kind = GetSetProperty;
734 return;
735 }
736 }
737
738 // If we're not atomic, just use expression accesses.
739 if (!IsAtomic) {
740 Kind = Expression;
741 return;
742 }
743
John McCall5889c602011-09-13 05:36:29 +0000744 // Properties on bitfield ivars need to be emitted using expression
745 // accesses even if they're nominally atomic.
746 if (ivar->isBitField()) {
747 Kind = Expression;
748 return;
749 }
750
John McCall1e1f4872011-09-13 03:34:09 +0000751 // GC-qualified or ARC-qualified ivars need to be emitted as
752 // expressions. This actually works out to being atomic anyway,
753 // except for ARC __strong, but that should trigger the above code.
754 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000755 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000756 CGM.getContext().getObjCGCAttrKind(ivarType))) {
757 Kind = Expression;
758 return;
759 }
760
761 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000762 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000763 if (const RecordType *recordType = ivarType->getAs<RecordType>())
764 HasStrong = recordType->getDecl()->hasObjectMember();
765
766 // We can never access structs with object members with a native
767 // access, because we need to use write barriers. This is what
768 // objc_copyStruct is for.
769 if (HasStrong) {
770 Kind = CopyStruct;
771 return;
772 }
773
774 // Otherwise, this is target-dependent and based on the size and
775 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000776
777 // If the size of the ivar is not a power of two, give up. We don't
778 // want to get into the business of doing compare-and-swaps.
779 if (!IvarSize.isPowerOfTwo()) {
780 Kind = CopyStruct;
781 return;
782 }
783
John McCall1e1f4872011-09-13 03:34:09 +0000784 llvm::Triple::ArchType arch =
John McCall64aa4b32013-04-16 22:48:15 +0000785 CGM.getTarget().getTriple().getArch();
John McCall1e1f4872011-09-13 03:34:09 +0000786
787 // Most architectures require memory to fit within a single cache
788 // line, so the alignment has to be at least the size of the access.
789 // Otherwise we have to grab a lock.
790 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
791 Kind = CopyStruct;
792 return;
793 }
794
795 // If the ivar's size exceeds the architecture's maximum atomic
796 // access size, we have to use CopyStruct.
797 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
798 Kind = CopyStruct;
799 return;
800 }
801
802 // Otherwise, we can use native loads and stores.
803 Kind = Native;
804}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000805
James Dennett2ee5ba32012-06-15 22:10:14 +0000806/// \brief Generate an Objective-C property getter function.
807///
808/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000809/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000810void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
811 const ObjCPropertyImplDecl *PID) {
David Blaikie89fe0a62014-10-14 16:43:46 +0000812 llvm::Constant *AtomicHelperFn =
813 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000814 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
815 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
816 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikie5fe8dcb2015-01-14 00:04:42 +0000817 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump1eb44332009-09-09 15:08:12 +0000818
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000819 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000820
821 FinishFunction();
822}
823
John McCall6c11f0b2011-09-13 06:00:03 +0000824static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
825 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000826 if (!getter) return true;
827
828 // Sema only makes only of these when the ivar has a C++ class type,
829 // so the form is pretty constrained.
830
John McCall6c11f0b2011-09-13 06:00:03 +0000831 // If the property has a reference type, we might just be binding a
832 // reference, in which case the result will be a gl-value. We should
833 // treat this as a non-trivial operation.
834 if (getter->isGLValue())
835 return false;
836
John McCall1e1f4872011-09-13 03:34:09 +0000837 // If we selected a trivial copy-constructor, we're okay.
838 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
839 return (construct->getConstructor()->isTrivial());
840
841 // The constructor might require cleanups (in which case it's never
842 // trivial).
843 assert(isa<ExprWithCleanups>(getter));
844 return false;
845}
846
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000847/// emitCPPObjectAtomicGetterCall - Call the runtime function to
848/// copy the ivar into the resturn slot.
849static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
850 llvm::Value *returnAddr,
851 ObjCIvarDecl *ivar,
852 llvm::Constant *AtomicHelperFn) {
853 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
854 // AtomicHelperFn);
855 CallArgList args;
856
857 // The 1st argument is the return Slot.
858 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
859
860 // The 2nd argument is the address of the ivar.
861 llvm::Value *ivarAddr =
John McCallf4ddf942015-09-08 08:05:57 +0000862 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
863 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000864 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
865 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
866
867 // Third argument is the helper function.
868 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
869
John McCalla896e9a2016-10-26 23:46:34 +0000870 llvm::Constant *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +0000871 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCalla896e9a2016-10-26 23:46:34 +0000872 CGCallee callee = CGCallee::forDirect(copyCppAtomicObjectFn);
John McCall5af07632016-03-11 04:30:31 +0000873 CGF.EmitCall(
874 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCalla896e9a2016-10-26 23:46:34 +0000875 callee, ReturnValueSlot(), args);
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000876}
877
John McCall1e1f4872011-09-13 03:34:09 +0000878void
879CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000880 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000881 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000882 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000883 // If there's a non-trivial 'get' expression, we just have to emit that.
884 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000885 if (!AtomicHelperFn) {
886 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topperd1008e52014-05-21 05:09:00 +0000887 /*nrvo*/ nullptr);
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000888 EmitReturnStmt(ret);
889 }
890 else {
891 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCallf4ddf942015-09-08 08:05:57 +0000892 emitCPPObjectAtomicGetterCall(*this, ReturnValue.getPointer(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000893 ivar, AtomicHelperFn);
894 }
John McCall1e1f4872011-09-13 03:34:09 +0000895 return;
896 }
897
898 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
899 QualType propType = prop->getType();
900 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
901
902 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
903
904 // Pick an implementation strategy.
905 PropertyImplStrategy strategy(CGM, propImpl);
906 switch (strategy.getKind()) {
907 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +0000908 // We don't need to do anything for a zero-size struct.
909 if (strategy.getIvarSize().isZero())
910 return;
911
John McCall1e1f4872011-09-13 03:34:09 +0000912 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
913
914 // Currently, all atomic accesses have to be through integer
915 // types, so there's no point in trying to pick a prettier type.
Akira Hatanaka97937692016-05-26 00:37:30 +0000916 uint64_t ivarSize = getContext().toBits(strategy.getIvarSize());
917 llvm::Type *bitcastType = llvm::Type::getIntNTy(getLLVMContext(), ivarSize);
John McCall1e1f4872011-09-13 03:34:09 +0000918 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
919
920 // Perform an atomic load. This does not impose ordering constraints.
John McCallf4ddf942015-09-08 08:05:57 +0000921 Address ivarAddr = LV.getAddress();
John McCall1e1f4872011-09-13 03:34:09 +0000922 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
923 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
JF Bastiena84ed322016-04-06 17:26:42 +0000924 load->setAtomic(llvm::AtomicOrdering::Unordered);
John McCall1e1f4872011-09-13 03:34:09 +0000925
926 // Store that value into the return address. Doing this with a
927 // bitcast is likely to produce some pretty ugly IR, but it's not
928 // the *most* terrible thing in the world.
Akira Hatanaka97937692016-05-26 00:37:30 +0000929 llvm::Type *retTy = ConvertType(getterMethod->getReturnType());
930 uint64_t retTySize = CGM.getDataLayout().getTypeSizeInBits(retTy);
931 llvm::Value *ivarVal = load;
932 if (ivarSize > retTySize) {
933 llvm::Type *newTy = llvm::Type::getIntNTy(getLLVMContext(), retTySize);
934 ivarVal = Builder.CreateTrunc(load, newTy);
935 bitcastType = newTy->getPointerTo();
936 }
937 Builder.CreateStore(ivarVal,
938 Builder.CreateBitCast(ReturnValue, bitcastType));
John McCall1e1f4872011-09-13 03:34:09 +0000939
940 // Make sure we don't do an autorelease.
941 AutoreleaseResult = false;
942 return;
943 }
944
945 case PropertyImplStrategy::GetSetProperty: {
John McCalla896e9a2016-10-26 23:46:34 +0000946 llvm::Constant *getPropertyFn =
John McCall1e1f4872011-09-13 03:34:09 +0000947 CGM.getObjCRuntime().GetPropertyGetFunction();
948 if (!getPropertyFn) {
949 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000950 return;
951 }
John McCalla896e9a2016-10-26 23:46:34 +0000952 CGCallee callee = CGCallee::forDirect(getPropertyFn);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000953
954 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
955 // FIXME: Can't this be simpler? This might even be worse than the
956 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000957 llvm::Value *cmd =
John McCallf4ddf942015-09-08 08:05:57 +0000958 Builder.CreateLoad(GetAddrOfLocalVar(getterMethod->getCmdDecl()), "cmd");
John McCall1e1f4872011-09-13 03:34:09 +0000959 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
960 llvm::Value *ivarOffset =
961 EmitIvarOffset(classImpl->getClassInterface(), ivar);
962
963 CallArgList args;
964 args.add(RValue::get(self), getContext().getObjCIdType());
965 args.add(RValue::get(cmd), getContext().getObjCSelType());
966 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000967 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
968 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000969
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000970 // FIXME: We shouldn't need to get the function info here, the
971 // runtime already should have computed it to build the function.
Fariborz Jahanian8ed22552014-01-30 00:16:39 +0000972 llvm::Instruction *CallInstruction;
Samuel Antao0cb5f3a2015-11-23 22:04:44 +0000973 RValue RV = EmitCall(
John McCall5af07632016-03-11 04:30:31 +0000974 getTypes().arrangeBuiltinFunctionCall(propType, args),
John McCalla896e9a2016-10-26 23:46:34 +0000975 callee, ReturnValueSlot(), args, &CallInstruction);
Fariborz Jahanian8ed22552014-01-30 00:16:39 +0000976 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
977 call->setTailCall();
John McCall1e1f4872011-09-13 03:34:09 +0000978
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000979 // We need to fix the type here. Ivars with copy & retain are
980 // always objects so we don't need to worry about complex or
981 // aggregates.
Alp Toker37545f72014-01-25 16:55:45 +0000982 RV = RValue::get(Builder.CreateBitCast(
983 RV.getScalarVal(),
984 getTypes().ConvertType(getterMethod->getReturnType())));
John McCall1e1f4872011-09-13 03:34:09 +0000985
986 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000987
988 // objc_getProperty does an autorelease, so we should suppress ours.
989 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000990
John McCall1e1f4872011-09-13 03:34:09 +0000991 return;
992 }
993
994 case PropertyImplStrategy::CopyStruct:
995 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
996 strategy.hasStrongMember());
997 return;
998
999 case PropertyImplStrategy::Expression:
1000 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1001 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
1002
1003 QualType ivarType = ivar->getType();
John McCall9d232c82013-03-07 21:37:08 +00001004 switch (getEvaluationKind(ivarType)) {
1005 case TEK_Complex: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001006 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCallf4ddf942015-09-08 08:05:57 +00001007 EmitStoreOfComplex(pair, MakeAddrLValue(ReturnValue, ivarType),
John McCall9d232c82013-03-07 21:37:08 +00001008 /*init*/ true);
1009 return;
1010 }
1011 case TEK_Aggregate:
John McCall1e1f4872011-09-13 03:34:09 +00001012 // The return value slot is guaranteed to not be aliased, but
1013 // that's not necessarily the same as "on the stack", so
1014 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +00001015 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall9d232c82013-03-07 21:37:08 +00001016 return;
1017 case TEK_Scalar: {
John McCallba3dd902011-07-22 05:23:13 +00001018 llvm::Value *value;
1019 if (propType->isReferenceType()) {
John McCallf4ddf942015-09-08 08:05:57 +00001020 value = LV.getAddress().getPointer();
John McCallba3dd902011-07-22 05:23:13 +00001021 } else {
1022 // We want to load and autoreleaseReturnValue ARC __weak ivars.
1023 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallabdd8242015-10-22 18:38:17 +00001024 if (getLangOpts().ObjCAutoRefCount) {
1025 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
1026 } else {
1027 value = EmitARCLoadWeak(LV.getAddress());
1028 }
John McCallba3dd902011-07-22 05:23:13 +00001029
1030 // Otherwise we want to do a simple load, suppressing the
1031 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +00001032 } else {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001033 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCallba3dd902011-07-22 05:23:13 +00001034 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +00001035 }
John McCallf85e1932011-06-15 23:02:42 +00001036
Alp Toker37545f72014-01-25 16:55:45 +00001037 value = Builder.CreateBitCast(
1038 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCallba3dd902011-07-22 05:23:13 +00001039 }
1040
1041 EmitReturnOfRValue(RValue::get(value), propType);
John McCall9d232c82013-03-07 21:37:08 +00001042 return;
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +00001043 }
John McCall9d232c82013-03-07 21:37:08 +00001044 }
1045 llvm_unreachable("bad evaluation kind");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001046 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001047
John McCall1e1f4872011-09-13 03:34:09 +00001048 }
1049 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001050}
1051
John McCall41bdde92011-09-12 23:06:44 +00001052/// emitStructSetterCall - Call the runtime function to store the value
1053/// from the first formal parameter into the given ivar.
1054static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
1055 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +00001056 // objc_copyStruct (&structIvar, &Arg,
1057 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +00001058 CallArgList args;
1059
1060 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +00001061 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1062 CGF.LoadObjCSelf(), ivar, 0)
John McCallf4ddf942015-09-08 08:05:57 +00001063 .getPointer();
John McCall41bdde92011-09-12 23:06:44 +00001064 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1065 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +00001066
1067 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +00001068 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001069 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +00001070 VK_LValue, SourceLocation());
John McCallf4ddf942015-09-08 08:05:57 +00001071 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
John McCall41bdde92011-09-12 23:06:44 +00001072 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1073 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +00001074
1075 // The third argument is the sizeof the type.
1076 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +00001077 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
1078 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +00001079
John McCall41bdde92011-09-12 23:06:44 +00001080 // The fourth argument is the 'isAtomic' flag.
1081 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +00001082
John McCall41bdde92011-09-12 23:06:44 +00001083 // The fifth argument is the 'hasStrong' flag.
1084 // FIXME: should this really always be false?
1085 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1086
John McCalla896e9a2016-10-26 23:46:34 +00001087 llvm::Constant *fn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
1088 CGCallee callee = CGCallee::forDirect(fn);
John McCall5af07632016-03-11 04:30:31 +00001089 CGF.EmitCall(
1090 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCalla896e9a2016-10-26 23:46:34 +00001091 callee, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +00001092}
1093
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001094/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1095/// the value from the first formal parameter into the given ivar, using
1096/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1097static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1098 ObjCMethodDecl *OMD,
1099 ObjCIvarDecl *ivar,
1100 llvm::Constant *AtomicHelperFn) {
1101 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1102 // AtomicHelperFn);
1103 CallArgList args;
1104
1105 // The first argument is the address of the ivar.
1106 llvm::Value *ivarAddr =
1107 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
John McCallf4ddf942015-09-08 08:05:57 +00001108 CGF.LoadObjCSelf(), ivar, 0).getPointer();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001109 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1110 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1111
1112 // The second argument is the address of the parameter variable.
1113 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001114 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001115 VK_LValue, SourceLocation());
John McCallf4ddf942015-09-08 08:05:57 +00001116 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getPointer();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001117 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1118 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1119
1120 // Third argument is the helper function.
1121 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1122
John McCalla896e9a2016-10-26 23:46:34 +00001123 llvm::Constant *fn =
David Chisnalld397cfe2012-12-17 18:54:24 +00001124 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCalla896e9a2016-10-26 23:46:34 +00001125 CGCallee callee = CGCallee::forDirect(fn);
John McCall5af07632016-03-11 04:30:31 +00001126 CGF.EmitCall(
1127 CGF.getTypes().arrangeBuiltinFunctionCall(CGF.getContext().VoidTy, args),
John McCalla896e9a2016-10-26 23:46:34 +00001128 callee, ReturnValueSlot(), args);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001129}
1130
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001131
John McCall1e1f4872011-09-13 03:34:09 +00001132static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1133 Expr *setter = PID->getSetterCXXAssignment();
1134 if (!setter) return true;
1135
1136 // Sema only makes only of these when the ivar has a C++ class type,
1137 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001138
1139 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001140 // This also implies that there's nothing non-trivial going on with
1141 // the arguments, because operator= can only be trivial if it's a
1142 // synthesized assignment operator and therefore both parameters are
1143 // references.
1144 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001145 if (const FunctionDecl *callee
1146 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1147 if (callee->isTrivial())
1148 return true;
1149 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001150 }
John McCall71c758d2011-09-10 09:17:20 +00001151
John McCall1e1f4872011-09-13 03:34:09 +00001152 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001153 return false;
1154}
1155
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001156static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001157 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001158 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001159 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001160}
1161
John McCall71c758d2011-09-10 09:17:20 +00001162void
1163CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001164 const ObjCPropertyImplDecl *propImpl,
1165 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001166 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001167 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001168 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001169
1170 // Just use the setter expression if Sema gave us one and it's
1171 // non-trivial.
1172 if (!hasTrivialSetExpr(propImpl)) {
1173 if (!AtomicHelperFn)
1174 // If non-atomic, assignment is called directly.
1175 EmitStmt(propImpl->getSetterCXXAssignment());
1176 else
1177 // If atomic, assignment is called via a locking api.
1178 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1179 AtomicHelperFn);
1180 return;
1181 }
John McCall71c758d2011-09-10 09:17:20 +00001182
John McCall1e1f4872011-09-13 03:34:09 +00001183 PropertyImplStrategy strategy(CGM, propImpl);
1184 switch (strategy.getKind()) {
1185 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +00001186 // We don't need to do anything for a zero-size struct.
1187 if (strategy.getIvarSize().isZero())
1188 return;
1189
John McCallf4ddf942015-09-08 08:05:57 +00001190 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
John McCall71c758d2011-09-10 09:17:20 +00001191
John McCall1e1f4872011-09-13 03:34:09 +00001192 LValue ivarLValue =
1193 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
John McCallf4ddf942015-09-08 08:05:57 +00001194 Address ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001195
John McCall1e1f4872011-09-13 03:34:09 +00001196 // Currently, all atomic accesses have to be through integer
1197 // types, so there's no point in trying to pick a prettier type.
1198 llvm::Type *bitcastType =
1199 llvm::Type::getIntNTy(getLLVMContext(),
1200 getContext().toBits(strategy.getIvarSize()));
John McCall1e1f4872011-09-13 03:34:09 +00001201
1202 // Cast both arguments to the chosen operation type.
John McCallf4ddf942015-09-08 08:05:57 +00001203 argAddr = Builder.CreateElementBitCast(argAddr, bitcastType);
1204 ivarAddr = Builder.CreateElementBitCast(ivarAddr, bitcastType);
John McCall1e1f4872011-09-13 03:34:09 +00001205
1206 // This bitcast load is likely to cause some nasty IR.
1207 llvm::Value *load = Builder.CreateLoad(argAddr);
1208
1209 // Perform an atomic store. There are no memory ordering requirements.
1210 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
JF Bastiena84ed322016-04-06 17:26:42 +00001211 store->setAtomic(llvm::AtomicOrdering::Unordered);
John McCall1e1f4872011-09-13 03:34:09 +00001212 return;
1213 }
1214
1215 case PropertyImplStrategy::GetSetProperty:
1216 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topperd1008e52014-05-21 05:09:00 +00001217
John McCalla896e9a2016-10-26 23:46:34 +00001218 llvm::Constant *setOptimizedPropertyFn = nullptr;
1219 llvm::Constant *setPropertyFn = nullptr;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001220 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001221 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001222 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001223 CGM.getObjCRuntime()
1224 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1225 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001226 if (!setOptimizedPropertyFn) {
1227 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1228 return;
1229 }
John McCall71c758d2011-09-10 09:17:20 +00001230 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001231 else {
1232 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1233 if (!setPropertyFn) {
1234 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1235 return;
1236 }
1237 }
1238
John McCall71c758d2011-09-10 09:17:20 +00001239 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1240 // <is-atomic>, <is-copy>).
1241 llvm::Value *cmd =
John McCallf4ddf942015-09-08 08:05:57 +00001242 Builder.CreateLoad(GetAddrOfLocalVar(setterMethod->getCmdDecl()));
John McCall71c758d2011-09-10 09:17:20 +00001243 llvm::Value *self =
1244 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1245 llvm::Value *ivarOffset =
1246 EmitIvarOffset(classImpl->getClassInterface(), ivar);
John McCallf4ddf942015-09-08 08:05:57 +00001247 Address argAddr = GetAddrOfLocalVar(*setterMethod->param_begin());
1248 llvm::Value *arg = Builder.CreateLoad(argAddr, "arg");
1249 arg = Builder.CreateBitCast(arg, VoidPtrTy);
John McCall71c758d2011-09-10 09:17:20 +00001250
1251 CallArgList args;
1252 args.add(RValue::get(self), getContext().getObjCIdType());
1253 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001254 if (setOptimizedPropertyFn) {
1255 args.add(RValue::get(arg), getContext().getObjCIdType());
1256 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCalla896e9a2016-10-26 23:46:34 +00001257 CGCallee callee = CGCallee::forDirect(setOptimizedPropertyFn);
John McCall5af07632016-03-11 04:30:31 +00001258 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCalla896e9a2016-10-26 23:46:34 +00001259 callee, ReturnValueSlot(), args);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001260 } else {
1261 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1262 args.add(RValue::get(arg), getContext().getObjCIdType());
1263 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1264 getContext().BoolTy);
1265 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1266 getContext().BoolTy);
1267 // FIXME: We shouldn't need to get the function info here, the runtime
1268 // already should have computed it to build the function.
John McCalla896e9a2016-10-26 23:46:34 +00001269 CGCallee callee = CGCallee::forDirect(setPropertyFn);
John McCall5af07632016-03-11 04:30:31 +00001270 EmitCall(getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, args),
John McCalla896e9a2016-10-26 23:46:34 +00001271 callee, ReturnValueSlot(), args);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001272 }
1273
John McCall71c758d2011-09-10 09:17:20 +00001274 return;
1275 }
1276
John McCall1e1f4872011-09-13 03:34:09 +00001277 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001278 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001279 return;
John McCall1e1f4872011-09-13 03:34:09 +00001280
1281 case PropertyImplStrategy::Expression:
1282 break;
John McCall71c758d2011-09-10 09:17:20 +00001283 }
1284
1285 // Otherwise, fake up some ASTs and emit a normal assignment.
1286 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001287 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1288 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001289 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1290 selfDecl->getType(), CK_LValueToRValue, &self,
1291 VK_RValue);
1292 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001293 SourceLocation(), SourceLocation(),
1294 &selfLoad, true, true);
John McCall71c758d2011-09-10 09:17:20 +00001295
1296 ParmVarDecl *argDecl = *setterMethod->param_begin();
1297 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001298 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001299 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1300 argType.getUnqualifiedType(), CK_LValueToRValue,
1301 &arg, VK_RValue);
1302
1303 // The property type can differ from the ivar type in some situations with
1304 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1305 // The following absurdity is just to ensure well-formed IR.
1306 CastKind argCK = CK_NoOp;
1307 if (ivarRef.getType()->isObjCObjectPointerType()) {
1308 if (argLoad.getType()->isObjCObjectPointerType())
1309 argCK = CK_BitCast;
1310 else if (argLoad.getType()->isBlockPointerType())
1311 argCK = CK_BlockPointerToObjCPointerCast;
1312 else
1313 argCK = CK_CPointerToObjCPointerCast;
1314 } else if (ivarRef.getType()->isBlockPointerType()) {
1315 if (argLoad.getType()->isBlockPointerType())
1316 argCK = CK_BitCast;
1317 else
1318 argCK = CK_AnyPointerToBlockPointerCast;
1319 } else if (ivarRef.getType()->isPointerType()) {
1320 argCK = CK_BitCast;
1321 }
1322 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1323 ivarRef.getType(), argCK, &argLoad,
1324 VK_RValue);
1325 Expr *finalArg = &argLoad;
1326 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1327 argLoad.getType()))
1328 finalArg = &argCast;
1329
1330
1331 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1332 ivarRef.getType(), VK_RValue, OK_Ordinary,
Adam Nemeteec6cbf2017-03-27 19:17:25 +00001333 SourceLocation(), FPOptions());
John McCall71c758d2011-09-10 09:17:20 +00001334 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001335}
1336
James Dennett2ee5ba32012-06-15 22:10:14 +00001337/// \brief Generate an Objective-C property setter function.
1338///
1339/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001340/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001341void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1342 const ObjCPropertyImplDecl *PID) {
David Blaikie89fe0a62014-10-14 16:43:46 +00001343 llvm::Constant *AtomicHelperFn =
1344 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001345 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1346 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1347 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikie5fe8dcb2015-01-14 00:04:42 +00001348 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001349
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001350 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001351
1352 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001353}
1354
John McCalle81ac692011-03-22 07:05:39 +00001355namespace {
David Blaikie673861a2015-08-18 22:40:54 +00001356 struct DestroyIvar final : EHScopeStack::Cleanup {
John McCall9928c482011-07-12 16:41:08 +00001357 private:
1358 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001359 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001360 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001361 bool useEHCleanupForArray;
1362 public:
1363 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1364 CodeGenFunction::Destroyer *destroyer,
1365 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001366 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001367 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001368
Craig Topperf7bc4972014-03-12 06:41:41 +00001369 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall9928c482011-07-12 16:41:08 +00001370 LValue lvalue
1371 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1372 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001373 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001374 }
1375 };
Alexander Kornienko8ca77052015-06-22 23:07:51 +00001376}
John McCalle81ac692011-03-22 07:05:39 +00001377
John McCall9928c482011-07-12 16:41:08 +00001378/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1379static void destroyARCStrongWithStore(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00001380 Address addr,
John McCall9928c482011-07-12 16:41:08 +00001381 QualType type) {
1382 llvm::Value *null = getNullForVariable(addr);
1383 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1384}
John McCallf85e1932011-06-15 23:02:42 +00001385
John McCalle81ac692011-03-22 07:05:39 +00001386static void emitCXXDestructMethod(CodeGenFunction &CGF,
1387 ObjCImplementationDecl *impl) {
1388 CodeGenFunction::RunCleanupsScope scope(CGF);
1389
1390 llvm::Value *self = CGF.LoadObjCSelf();
1391
Jordy Rosedb8264e2011-07-22 02:08:32 +00001392 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1393 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001394 ivar; ivar = ivar->getNextIvar()) {
1395 QualType type = ivar->getType();
1396
John McCalle81ac692011-03-22 07:05:39 +00001397 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001398 QualType::DestructionKind dtorKind = type.isDestructedType();
1399 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001400
Craig Topperd1008e52014-05-21 05:09:00 +00001401 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCalle81ac692011-03-22 07:05:39 +00001402
John McCall9928c482011-07-12 16:41:08 +00001403 // Use a call to objc_storeStrong to destroy strong ivars, for the
1404 // general benefit of the tools.
1405 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001406 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001407
John McCall9928c482011-07-12 16:41:08 +00001408 // Otherwise use the default for the destruction kind.
1409 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001410 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001411 }
John McCall9928c482011-07-12 16:41:08 +00001412
1413 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1414
1415 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1416 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001417 }
1418
1419 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1420}
1421
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001422void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1423 ObjCMethodDecl *MD,
1424 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001425 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikie5fe8dcb2015-01-14 00:04:42 +00001426 StartObjCMethod(MD, IMP->getClassInterface());
John McCalle81ac692011-03-22 07:05:39 +00001427
1428 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001429 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001430 // Suppress the final autorelease in ARC.
1431 AutoreleaseResult = false;
1432
Aaron Ballmane9e159f2014-03-13 17:35:02 +00001433 for (const auto *IvarInit : IMP->inits()) {
Francois Pichet00eb3f92010-12-04 09:14:42 +00001434 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballmane9e159f2014-03-13 17:35:02 +00001435 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001436 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1437 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001438 EmitAggExpr(IvarInit->getInit(),
1439 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001440 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001441 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001442 }
1443 // constructor returns 'self'.
1444 CodeGenTypes &Types = CGM.getTypes();
1445 QualType IdTy(CGM.getContext().getObjCIdType());
1446 llvm::Value *SelfAsId =
1447 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1448 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001449
1450 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001451 } else {
John McCalle81ac692011-03-22 07:05:39 +00001452 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001453 }
1454 FinishFunction();
1455}
1456
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001457llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCallf5ebf9b2013-05-03 07:33:41 +00001458 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1459 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1460 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001461 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner41110242008-06-17 18:05:57 +00001462}
1463
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001464QualType CodeGenFunction::TypeOfSelfObject() {
1465 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1466 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001467 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1468 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001469 return PTy->getPointeeType();
1470}
1471
Chris Lattner74391b42009-03-22 21:03:39 +00001472void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
John McCalla896e9a2016-10-26 23:46:34 +00001473 llvm::Constant *EnumerationMutationFnPtr =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001474 CGM.getObjCRuntime().EnumerationMutationFunction();
John McCalla896e9a2016-10-26 23:46:34 +00001475 if (!EnumerationMutationFnPtr) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001476 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1477 return;
1478 }
John McCalla896e9a2016-10-26 23:46:34 +00001479 CGCallee EnumerationMutationFn =
1480 CGCallee::forDirect(EnumerationMutationFnPtr);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001481
Devang Patelbcbd03a2011-01-19 01:36:36 +00001482 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001483 if (DI)
1484 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001485
Kuba Mracekc4587fe2017-04-14 16:53:25 +00001486 RunCleanupsScope ForScope(*this);
1487
Kuba Mracek9dca7432017-04-14 01:00:03 +00001488 // The local variable comes into scope immediately.
1489 AutoVarEmission variable = AutoVarEmission::invalid();
1490 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1491 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1492
John McCalld88687f2011-01-07 01:49:06 +00001493 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Anders Carlssonf484c312008-08-31 02:33:12 +00001495 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001496 QualType StateTy = CGM.getObjCFastEnumerationStateType();
John McCallf4ddf942015-09-08 08:05:57 +00001497 Address StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001498 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Anders Carlssonf484c312008-08-31 02:33:12 +00001500 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001501 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001502
John McCalld88687f2011-01-07 01:49:06 +00001503 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001504 IdentifierInfo *II[] = {
1505 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1506 &CGM.getContext().Idents.get("objects"),
1507 &CGM.getContext().Idents.get("count")
1508 };
1509 Selector FastEnumSel =
1510 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001511
1512 QualType ItemsTy =
1513 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001514 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001515 ArrayType::Normal, 0);
John McCallf4ddf942015-09-08 08:05:57 +00001516 Address ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001517
John McCall990567c2011-07-27 01:07:15 +00001518 // Emit the collection pointer. In ARC, we do a retain.
1519 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001520 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001521 Collection = EmitARCRetainScalarExpr(S.getCollection());
1522
1523 // Enter a cleanup to do the release.
1524 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1525 } else {
1526 Collection = EmitScalarExpr(S.getCollection());
1527 }
Mike Stump1eb44332009-09-09 15:08:12 +00001528
John McCall4b302d32011-08-05 00:14:38 +00001529 // The 'continue' label needs to appear within the cleanup for the
1530 // collection object.
1531 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1532
John McCalld88687f2011-01-07 01:49:06 +00001533 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001534 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001535
1536 // The first argument is a temporary of the enumeration-state type.
John McCallf4ddf942015-09-08 08:05:57 +00001537 Args.add(RValue::get(StatePtr.getPointer()),
1538 getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001539
John McCalld88687f2011-01-07 01:49:06 +00001540 // The second argument is a temporary array with space for NumItems
1541 // pointers. We'll actually be loading elements from the array
1542 // pointer written into the control state; this buffer is so that
1543 // collections that *aren't* backed by arrays can still queue up
1544 // batches of elements.
John McCallf4ddf942015-09-08 08:05:57 +00001545 Args.add(RValue::get(ItemsPtr.getPointer()),
1546 getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001547
John McCalld88687f2011-01-07 01:49:06 +00001548 // The third argument is the capacity of that temporary array.
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001549 llvm::Type *NSUIntegerTy = ConvertType(getContext().getNSUIntegerType());
1550 llvm::Constant *Count = llvm::ConstantInt::get(NSUIntegerTy, NumItems);
1551 Args.add(RValue::get(Count), getContext().getNSUIntegerType());
Mike Stump1eb44332009-09-09 15:08:12 +00001552
John McCalld88687f2011-01-07 01:49:06 +00001553 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001554 RValue CountRV =
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001555 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1556 getContext().getNSUIntegerType(),
1557 FastEnumSel, Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001558
John McCalld88687f2011-01-07 01:49:06 +00001559 // The initial number of objects that were returned in the buffer.
1560 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001561
John McCalld88687f2011-01-07 01:49:06 +00001562 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1563 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001564
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001565 llvm::Value *zero = llvm::Constant::getNullValue(NSUIntegerTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001566
John McCalld88687f2011-01-07 01:49:06 +00001567 // If the limit pointer was zero to begin with, the collection is
Bob Wilson70f12c62014-03-25 23:26:31 +00001568 // empty; skip all this. Set the branch weight assuming this has the same
1569 // probability of exiting the loop as any other loop exit.
Justin Bogneraa53a4f2015-04-23 23:06:47 +00001570 uint64_t EntryCount = getCurrentProfileCount();
1571 Builder.CreateCondBr(
1572 Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"), EmptyBB,
1573 LoopInitBB,
Justin Bogner6cd4b9e2015-05-02 05:00:55 +00001574 createProfileWeights(EntryCount, getProfileCount(S.getBody())));
Anders Carlssonf484c312008-08-31 02:33:12 +00001575
John McCalld88687f2011-01-07 01:49:06 +00001576 // Otherwise, initialize the loop.
1577 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001578
John McCalld88687f2011-01-07 01:49:06 +00001579 // Save the initial mutations value. This is the value at an
1580 // address that was written into the state object by
1581 // countByEnumeratingWithState:objects:count:.
John McCallf4ddf942015-09-08 08:05:57 +00001582 Address StateMutationsPtrPtr = Builder.CreateStructGEP(
1583 StatePtr, 2, 2 * getPointerSize(), "mutationsptr.ptr");
1584 llvm::Value *StateMutationsPtr
1585 = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001586
John McCalld88687f2011-01-07 01:49:06 +00001587 llvm::Value *initialMutations =
John McCallf4ddf942015-09-08 08:05:57 +00001588 Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1589 "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001590
John McCalld88687f2011-01-07 01:49:06 +00001591 // Start looping. This is the point we return to whenever we have a
1592 // fresh, non-empty batch of objects.
1593 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1594 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001595
John McCalld88687f2011-01-07 01:49:06 +00001596 // The current index into the buffer.
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001597 llvm::PHINode *index = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001598 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001599
John McCalld88687f2011-01-07 01:49:06 +00001600 // The current buffer size.
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001601 llvm::PHINode *count = Builder.CreatePHI(NSUIntegerTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001602 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Justin Bogneraa53a4f2015-04-23 23:06:47 +00001604 incrementProfileCounter(&S);
Bob Wilsonbe421292014-02-24 01:13:09 +00001605
John McCalld88687f2011-01-07 01:49:06 +00001606 // Check whether the mutations value has changed from where it was
1607 // at start. StateMutationsPtr should actually be invariant between
1608 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001609 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001610 llvm::Value *currentMutations
John McCallf4ddf942015-09-08 08:05:57 +00001611 = Builder.CreateAlignedLoad(StateMutationsPtr, getPointerAlign(),
1612 "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001613
John McCalld88687f2011-01-07 01:49:06 +00001614 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001615 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001616
John McCalld88687f2011-01-07 01:49:06 +00001617 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1618 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001619
John McCalld88687f2011-01-07 01:49:06 +00001620 // If so, call the enumeration-mutation function.
1621 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001622 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001623 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001624 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001625 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001626 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001627 // FIXME: We shouldn't need to get the function info here, the runtime already
1628 // should have computed it to build the function.
John McCall5af07632016-03-11 04:30:31 +00001629 EmitCall(
1630 CGM.getTypes().arrangeBuiltinFunctionCall(getContext().VoidTy, Args2),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001631 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001632
John McCalld88687f2011-01-07 01:49:06 +00001633 // Otherwise, or if the mutation function returns, just continue.
1634 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
John McCalld88687f2011-01-07 01:49:06 +00001636 // Initialize the element variable.
1637 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001638 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001639 LValue elementLValue;
1640 QualType elementType;
1641 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001642 // Initialize the variable, in case it's a __block variable or something.
1643 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001644
John McCall57b3b6a2011-02-22 07:16:58 +00001645 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001646 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001647 VK_LValue, SourceLocation());
1648 elementLValue = EmitLValue(&tempDRE);
1649 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001650 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001651
1652 if (D->isARCPseudoStrong())
1653 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001654 } else {
1655 elementLValue = LValue(); // suppress warning
1656 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001657 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001658 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001659 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001660
1661 // Fetch the buffer out of the enumeration state.
1662 // TODO: this pointer should actually be invariant between
1663 // refreshes, which would help us do certain loop optimizations.
John McCallf4ddf942015-09-08 08:05:57 +00001664 Address StateItemsPtr = Builder.CreateStructGEP(
1665 StatePtr, 1, getPointerSize(), "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001666 llvm::Value *EnumStateItems =
1667 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001668
John McCalld88687f2011-01-07 01:49:06 +00001669 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001670 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001671 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
John McCallf4ddf942015-09-08 08:05:57 +00001672 llvm::Value *CurrentItem =
1673 Builder.CreateAlignedLoad(CurrentItemPtr, getPointerAlign());
Mike Stump1eb44332009-09-09 15:08:12 +00001674
John McCalld88687f2011-01-07 01:49:06 +00001675 // Cast that value to the right type.
1676 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1677 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001678
John McCalld88687f2011-01-07 01:49:06 +00001679 // Make sure we have an l-value. Yes, this gets evaluated every
1680 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001681 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001682 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001683 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001684 } else {
Akira Hatanakad698b922016-10-18 19:05:41 +00001685 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue,
1686 /*isInit*/ true);
John McCall7acddac2011-06-17 06:42:21 +00001687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
John McCall57b3b6a2011-02-22 07:16:58 +00001689 // If we do have an element variable, this assignment is the end of
1690 // its initialization.
1691 if (elementIsVariable)
1692 EmitAutoVarCleanups(variable);
1693
John McCalld88687f2011-01-07 01:49:06 +00001694 // Perform the loop body, setting up break and continue labels.
Bob Wilsonac14efa2014-02-17 19:21:09 +00001695 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001696 {
1697 RunCleanupsScope Scope(*this);
1698 EmitStmt(S.getBody());
1699 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001700 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001701
John McCalld88687f2011-01-07 01:49:06 +00001702 // Destroy the element variable now.
1703 elementVariableScope.ForceCleanup();
1704
1705 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001706 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001707
John McCalld88687f2011-01-07 01:49:06 +00001708 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001709
John McCalld88687f2011-01-07 01:49:06 +00001710 // First we check in the local buffer.
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001711 llvm::Value *indexPlusOne =
1712 Builder.CreateAdd(index, llvm::ConstantInt::get(NSUIntegerTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001713
John McCalld88687f2011-01-07 01:49:06 +00001714 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson70f12c62014-03-25 23:26:31 +00001715 // Set the branch weights based on the simplifying assumption that this is
1716 // like a while-loop, i.e., ignoring that the false branch fetches more
1717 // elements and then returns to the loop.
Justin Bogneraa53a4f2015-04-23 23:06:47 +00001718 Builder.CreateCondBr(
1719 Builder.CreateICmpULT(indexPlusOne, count), LoopBodyBB, FetchMoreBB,
Justin Bogner6cd4b9e2015-05-02 05:00:55 +00001720 createProfileWeights(getProfileCount(S.getBody()), EntryCount));
John McCalld88687f2011-01-07 01:49:06 +00001721
1722 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1723 count->addIncoming(count, AfterBody.getBlock());
1724
1725 // Otherwise, we have to fetch more elements.
1726 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001727
1728 CountRV =
Saleem Abdulrasool5c4cc682017-09-08 23:41:17 +00001729 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1730 getContext().getNSUIntegerType(),
1731 FastEnumSel, Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001732
John McCalld88687f2011-01-07 01:49:06 +00001733 // If we got a zero count, we're done.
1734 llvm::Value *refetchCount = CountRV.getScalarVal();
1735
1736 // (note that the message send might split FetchMoreBB)
1737 index->addIncoming(zero, Builder.GetInsertBlock());
1738 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1739
1740 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1741 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Anders Carlssonf484c312008-08-31 02:33:12 +00001743 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001744 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001745
John McCall57b3b6a2011-02-22 07:16:58 +00001746 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001747 // If the element was not a declaration, set it to be null.
1748
John McCalld88687f2011-01-07 01:49:06 +00001749 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1750 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001751 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001752 }
1753
Eric Christopher73fb3502011-10-13 21:45:18 +00001754 if (DI)
1755 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001756
Akira Hatanaka179aac02016-04-12 23:10:58 +00001757 ForScope.ForceCleanup();
John McCallff8e1152010-07-23 21:56:41 +00001758 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001759}
1760
Mike Stump1eb44332009-09-09 15:08:12 +00001761void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001762 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001763}
1764
Mike Stump1eb44332009-09-09 15:08:12 +00001765void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001766 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1767}
1768
Chris Lattner10cac6f2008-11-15 21:26:17 +00001769void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001770 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001771 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001772}
1773
John McCallf85e1932011-06-15 23:02:42 +00001774namespace {
David Blaikie673861a2015-08-18 22:40:54 +00001775 struct CallObjCRelease final : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001776 CallObjCRelease(llvm::Value *object) : object(object) {}
1777 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001778
Craig Topperf7bc4972014-03-12 06:41:41 +00001779 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall5b07e802013-03-13 03:10:54 +00001780 // Releases at the end of the full-expression are imprecise.
1781 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001782 }
1783 };
Alexander Kornienko8ca77052015-06-22 23:07:51 +00001784}
John McCallf85e1932011-06-15 23:02:42 +00001785
John McCall33e56f32011-09-10 06:18:15 +00001786/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001787/// release at the end of the full-expression.
1788llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1789 llvm::Value *object) {
1790 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001791 // conditional.
1792 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001793 return object;
1794}
1795
1796llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1797 llvm::Value *value) {
1798 return EmitARCRetainAutorelease(type, value);
1799}
1800
John McCallb6a60792013-03-23 02:35:54 +00001801/// Given a number of pointers, inform the optimizer that they're
1802/// being intrinsically used up until this point in the program.
1803void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
John McCallf36e93a2015-10-21 18:06:43 +00001804 llvm::Constant *&fn = CGM.getObjCEntrypoints().clang_arc_use;
John McCallb6a60792013-03-23 02:35:54 +00001805 if (!fn) {
1806 llvm::FunctionType *fnType =
Craig Topperbbac8402014-08-27 06:28:36 +00001807 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCallb6a60792013-03-23 02:35:54 +00001808 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1809 }
1810
1811 // This isn't really a "runtime" function, but as an intrinsic it
1812 // doesn't really matter as long as we align things up.
1813 EmitNounwindRuntimeCall(fn, values);
1814}
1815
John McCallf85e1932011-06-15 23:02:42 +00001816
Saleem Abdulrasoola92ce662017-02-11 21:34:18 +00001817static bool IsForwarding(StringRef Name) {
1818 return llvm::StringSwitch<bool>(Name)
1819 .Cases("objc_autoreleaseReturnValue", // ARCInstKind::AutoreleaseRV
1820 "objc_autorelease", // ARCInstKind::Autorelease
1821 "objc_retainAutoreleaseReturnValue", // ARCInstKind::FusedRetainAutoreleaseRV
1822 "objc_retainAutoreleasedReturnValue", // ARCInstKind::RetainRV
1823 "objc_retainAutorelease", // ARCInstKind::FusedRetainAutorelease
1824 "objc_retainedObject", // ARCInstKind::NoopCast
1825 "objc_retain", // ARCInstKind::Retain
1826 "objc_unretainedObject", // ARCInstKind::NoopCast
1827 "objc_unretainedPointer", // ARCInstKind::NoopCast
1828 "objc_unsafeClaimAutoreleasedReturnValue", // ARCInstKind::ClaimRV
1829 true)
1830 .Default(false);
1831}
1832
John McCallf85e1932011-06-15 23:02:42 +00001833static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Saleem Abdulrasool370ec932017-02-11 17:24:07 +00001834 llvm::FunctionType *FTy,
1835 StringRef Name) {
1836 llvm::Constant *RTF = CGM.CreateRuntimeFunction(FTy, Name);
John McCallf85e1932011-06-15 23:02:42 +00001837
Saleem Abdulrasool370ec932017-02-11 17:24:07 +00001838 if (auto *F = dyn_cast<llvm::Function>(RTF)) {
Michael Gottesmancfe18a12013-02-02 01:05:06 +00001839 // If the target runtime doesn't naturally support ARC, emit weak
1840 // references to the runtime support library. We don't really
1841 // permit this to fail, but we need a particular relocation style.
Saleem Abdulrasoole13e0e42016-12-15 06:59:05 +00001842 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC() &&
1843 !CGM.getTriple().isOSBinFormatCOFF()) {
Saleem Abdulrasool370ec932017-02-11 17:24:07 +00001844 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1845 } else if (Name == "objc_retain" || Name == "objc_release") {
Michael Gottesman554b07d2013-02-02 00:57:44 +00001846 // If we have Native ARC, set nonlazybind attribute for these APIs for
1847 // performance.
Saleem Abdulrasool370ec932017-02-11 17:24:07 +00001848 F->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmandb99e8b2013-02-02 01:03:01 +00001849 }
Saleem Abdulrasoola92ce662017-02-11 21:34:18 +00001850
Reid Klecknerbfb79c82017-04-19 17:28:52 +00001851 if (IsForwarding(Name))
1852 F->arg_begin()->addAttr(llvm::Attribute::Returned);
Michael Gottesman554b07d2013-02-02 00:57:44 +00001853 }
John McCallf85e1932011-06-15 23:02:42 +00001854
Saleem Abdulrasool370ec932017-02-11 17:24:07 +00001855 return RTF;
John McCallf85e1932011-06-15 23:02:42 +00001856}
1857
1858/// Perform an operation having the signature
1859/// i8* (i8*)
1860/// where a null input causes a no-op and returns null.
1861static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1862 llvm::Value *value,
1863 llvm::Constant *&fn,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001864 StringRef fnName,
1865 bool isTailCall = false) {
Saleem Abdulrasool370ec932017-02-11 17:24:07 +00001866 if (isa<llvm::ConstantPointerNull>(value))
1867 return value;
John McCallf85e1932011-06-15 23:02:42 +00001868
1869 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001870 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001871 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001872 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1873 }
1874
1875 // Cast the argument to 'id'.
Pete Cooper2a988fc2016-03-21 20:50:03 +00001876 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001877 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1878
1879 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001880 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001881 if (isTailCall)
1882 call->setTailCall();
John McCallf85e1932011-06-15 23:02:42 +00001883
1884 // Cast the result back to the original type.
1885 return CGF.Builder.CreateBitCast(call, origType);
1886}
1887
1888/// Perform an operation having the following signature:
1889/// i8* (i8**)
1890static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00001891 Address addr,
John McCallf85e1932011-06-15 23:02:42 +00001892 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001893 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001894 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001895 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001896 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001897 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1898 }
1899
1900 // Cast the argument to 'id*'.
John McCallf4ddf942015-09-08 08:05:57 +00001901 llvm::Type *origType = addr.getElementType();
John McCallf85e1932011-06-15 23:02:42 +00001902 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1903
1904 // Call the function.
John McCallf4ddf942015-09-08 08:05:57 +00001905 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCallf85e1932011-06-15 23:02:42 +00001906
1907 // Cast the result back to a dereference of the original type.
John McCallf4ddf942015-09-08 08:05:57 +00001908 if (origType != CGF.Int8PtrTy)
1909 result = CGF.Builder.CreateBitCast(result, origType);
John McCallf85e1932011-06-15 23:02:42 +00001910
1911 return result;
1912}
1913
1914/// Perform an operation having the following signature:
1915/// i8* (i8**, i8*)
1916static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00001917 Address addr,
John McCallf85e1932011-06-15 23:02:42 +00001918 llvm::Value *value,
1919 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001920 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001921 bool ignored) {
John McCallf4ddf942015-09-08 08:05:57 +00001922 assert(addr.getElementType() == value->getType());
John McCallf85e1932011-06-15 23:02:42 +00001923
1924 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001925 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001926
Chris Lattner2acc6e32011-07-18 04:24:23 +00001927 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001928 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1929 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1930 }
1931
Chris Lattner2acc6e32011-07-18 04:24:23 +00001932 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001933
John McCallbd7370a2013-02-28 19:01:20 +00001934 llvm::Value *args[] = {
John McCallf4ddf942015-09-08 08:05:57 +00001935 CGF.Builder.CreateBitCast(addr.getPointer(), CGF.Int8PtrPtrTy),
John McCallbd7370a2013-02-28 19:01:20 +00001936 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1937 };
1938 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001939
Craig Topperd1008e52014-05-21 05:09:00 +00001940 if (ignored) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00001941
1942 return CGF.Builder.CreateBitCast(result, origType);
1943}
1944
1945/// Perform an operation having the following signature:
1946/// void (i8**, i8**)
1947static void emitARCCopyOperation(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00001948 Address dst,
1949 Address src,
John McCallf85e1932011-06-15 23:02:42 +00001950 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001951 StringRef fnName) {
John McCallf4ddf942015-09-08 08:05:57 +00001952 assert(dst.getType() == src.getType());
John McCallf85e1932011-06-15 23:02:42 +00001953
1954 if (!fn) {
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001955 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1956
Chris Lattner2acc6e32011-07-18 04:24:23 +00001957 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001958 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1959 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1960 }
1961
John McCallbd7370a2013-02-28 19:01:20 +00001962 llvm::Value *args[] = {
John McCallf4ddf942015-09-08 08:05:57 +00001963 CGF.Builder.CreateBitCast(dst.getPointer(), CGF.Int8PtrPtrTy),
1964 CGF.Builder.CreateBitCast(src.getPointer(), CGF.Int8PtrPtrTy)
John McCallbd7370a2013-02-28 19:01:20 +00001965 };
1966 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001967}
1968
1969/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001970/// call i8* \@objc_retain(i8* %value)
1971/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001972llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1973 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001974 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001975 else
1976 return EmitARCRetainNonBlock(value);
1977}
1978
1979/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001980/// call i8* \@objc_retain(i8* %value)
Pete Cooper2a988fc2016-03-21 20:50:03 +00001981llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1982 return emitARCValueOperation(*this, value,
John McCallf36e93a2015-10-21 18:06:43 +00001983 CGM.getObjCEntrypoints().objc_retain,
John McCallf85e1932011-06-15 23:02:42 +00001984 "objc_retain");
1985}
1986
1987/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001988/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001989///
1990/// \param mandatory - If false, emit the call with metadata
1991/// indicating that it's okay for the optimizer to eliminate this call
1992/// if it can prove that the block never escapes except down the stack.
1993llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1994 bool mandatory) {
1995 llvm::Value *result
Pete Cooper2a988fc2016-03-21 20:50:03 +00001996 = emitARCValueOperation(*this, value,
John McCallf36e93a2015-10-21 18:06:43 +00001997 CGM.getObjCEntrypoints().objc_retainBlock,
John McCall348f16f2011-10-04 06:23:45 +00001998 "objc_retainBlock");
1999
2000 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
2001 // tell the optimizer that it doesn't need to do this copy if the
2002 // block doesn't escape, where being passed as an argument doesn't
2003 // count as escaping.
2004 if (!mandatory && isa<llvm::Instruction>(result)) {
2005 llvm::CallInst *call
2006 = cast<llvm::CallInst>(result->stripPointerCasts());
John McCallf36e93a2015-10-21 18:06:43 +00002007 assert(call->getCalledValue() == CGM.getObjCEntrypoints().objc_retainBlock);
John McCall348f16f2011-10-04 06:23:45 +00002008
John McCall348f16f2011-10-04 06:23:45 +00002009 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithc7376722014-12-09 18:39:32 +00002010 llvm::MDNode::get(Builder.getContext(), None));
John McCall348f16f2011-10-04 06:23:45 +00002011 }
2012
2013 return result;
John McCallf85e1932011-06-15 23:02:42 +00002014}
2015
John McCall7164cef2016-01-27 18:32:30 +00002016static void emitAutoreleasedReturnValueMarker(CodeGenFunction &CGF) {
John McCallf85e1932011-06-15 23:02:42 +00002017 // Fetch the void(void) inline asm which marks that we're going to
John McCall7164cef2016-01-27 18:32:30 +00002018 // do something with the autoreleased return value.
John McCallf85e1932011-06-15 23:02:42 +00002019 llvm::InlineAsm *&marker
John McCall7164cef2016-01-27 18:32:30 +00002020 = CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker;
John McCallf85e1932011-06-15 23:02:42 +00002021 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002022 StringRef assembly
John McCall7164cef2016-01-27 18:32:30 +00002023 = CGF.CGM.getTargetCodeGenInfo()
John McCallf85e1932011-06-15 23:02:42 +00002024 .getARCRetainAutoreleasedReturnValueMarker();
2025
2026 // If we have an empty assembly string, there's nothing to do.
2027 if (assembly.empty()) {
2028
2029 // Otherwise, at -O0, build an inline asm that we're going to call
2030 // in a moment.
John McCall7164cef2016-01-27 18:32:30 +00002031 } else if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCallf85e1932011-06-15 23:02:42 +00002032 llvm::FunctionType *type =
John McCall7164cef2016-01-27 18:32:30 +00002033 llvm::FunctionType::get(CGF.VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00002034
2035 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
2036
2037 // If we're at -O1 and above, we don't want to litter the code
2038 // with this marker yet, so leave a breadcrumb for the ARC
2039 // optimizer to pick up.
2040 } else {
2041 llvm::NamedMDNode *metadata =
John McCall7164cef2016-01-27 18:32:30 +00002042 CGF.CGM.getModule().getOrInsertNamedMetadata(
John McCallf85e1932011-06-15 23:02:42 +00002043 "clang.arc.retainAutoreleasedReturnValueMarker");
2044 assert(metadata->getNumOperands() <= 1);
2045 if (metadata->getNumOperands() == 0) {
John McCall7164cef2016-01-27 18:32:30 +00002046 auto &ctx = CGF.getLLVMContext();
2047 metadata->addOperand(llvm::MDNode::get(ctx,
2048 llvm::MDString::get(ctx, assembly)));
John McCallf85e1932011-06-15 23:02:42 +00002049 }
2050 }
2051 }
2052
2053 // Call the marker asm if we made one, which we do only at -O0.
David Blaikie34ef52a2015-05-18 22:14:03 +00002054 if (marker)
John McCall7164cef2016-01-27 18:32:30 +00002055 CGF.Builder.CreateCall(marker);
2056}
John McCallf85e1932011-06-15 23:02:42 +00002057
John McCall7164cef2016-01-27 18:32:30 +00002058/// Retain the given object which is the result of a function call.
2059/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
2060///
2061/// Yes, this function name is one character away from a different
2062/// call with completely different semantics.
2063llvm::Value *
2064CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
2065 emitAutoreleasedReturnValueMarker(*this);
Pete Cooper2a988fc2016-03-21 20:50:03 +00002066 return emitARCValueOperation(*this, value,
John McCall7164cef2016-01-27 18:32:30 +00002067 CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue,
John McCallf85e1932011-06-15 23:02:42 +00002068 "objc_retainAutoreleasedReturnValue");
2069}
2070
John McCall7164cef2016-01-27 18:32:30 +00002071/// Claim a possibly-autoreleased return value at +0. This is only
2072/// valid to do in contexts which do not rely on the retain to keep
2073/// the object valid for for all of its uses; for example, when
2074/// the value is ignored, or when it is being assigned to an
2075/// __unsafe_unretained variable.
2076///
2077/// call i8* \@objc_unsafeClaimAutoreleasedReturnValue(i8* %value)
2078llvm::Value *
2079CodeGenFunction::EmitARCUnsafeClaimAutoreleasedReturnValue(llvm::Value *value) {
2080 emitAutoreleasedReturnValueMarker(*this);
Pete Cooper2a988fc2016-03-21 20:50:03 +00002081 return emitARCValueOperation(*this, value,
John McCall7164cef2016-01-27 18:32:30 +00002082 CGM.getObjCEntrypoints().objc_unsafeClaimAutoreleasedReturnValue,
2083 "objc_unsafeClaimAutoreleasedReturnValue");
2084}
2085
John McCallf85e1932011-06-15 23:02:42 +00002086/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002087/// call void \@objc_release(i8* %value)
John McCall5b07e802013-03-13 03:10:54 +00002088void CodeGenFunction::EmitARCRelease(llvm::Value *value,
2089 ARCPreciseLifetime_t precise) {
John McCallf85e1932011-06-15 23:02:42 +00002090 if (isa<llvm::ConstantPointerNull>(value)) return;
2091
John McCallf36e93a2015-10-21 18:06:43 +00002092 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_release;
John McCallf85e1932011-06-15 23:02:42 +00002093 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002094 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002095 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002096 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2097 }
2098
2099 // Cast the argument to 'id'.
2100 value = Builder.CreateBitCast(value, Int8PtrTy);
2101
2102 // Call objc_release.
John McCallbd7370a2013-02-28 19:01:20 +00002103 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002104
John McCall5b07e802013-03-13 03:10:54 +00002105 if (precise == ARCImpreciseLifetime) {
John McCallf85e1932011-06-15 23:02:42 +00002106 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithc7376722014-12-09 18:39:32 +00002107 llvm::MDNode::get(Builder.getContext(), None));
John McCallf85e1932011-06-15 23:02:42 +00002108 }
2109}
2110
John McCall015f33b2012-10-17 02:28:37 +00002111/// Destroy a __strong variable.
2112///
2113/// At -O0, emit a call to store 'null' into the address;
2114/// instrumenting tools prefer this because the address is exposed,
2115/// but it's relatively cumbersome to optimize.
2116///
2117/// At -O1 and above, just load and call objc_release.
2118///
2119/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCallf4ddf942015-09-08 08:05:57 +00002120void CodeGenFunction::EmitARCDestroyStrong(Address addr,
John McCall5b07e802013-03-13 03:10:54 +00002121 ARCPreciseLifetime_t precise) {
John McCall015f33b2012-10-17 02:28:37 +00002122 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
John McCallf4ddf942015-09-08 08:05:57 +00002123 llvm::Value *null = getNullForVariable(addr);
John McCall015f33b2012-10-17 02:28:37 +00002124 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2125 return;
2126 }
2127
2128 llvm::Value *value = Builder.CreateLoad(addr);
2129 EmitARCRelease(value, precise);
2130}
2131
John McCallf85e1932011-06-15 23:02:42 +00002132/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002133/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf4ddf942015-09-08 08:05:57 +00002134llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(Address addr,
John McCallf85e1932011-06-15 23:02:42 +00002135 llvm::Value *value,
2136 bool ignored) {
John McCallf4ddf942015-09-08 08:05:57 +00002137 assert(addr.getElementType() == value->getType());
John McCallf85e1932011-06-15 23:02:42 +00002138
John McCallf36e93a2015-10-21 18:06:43 +00002139 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_storeStrong;
John McCallf85e1932011-06-15 23:02:42 +00002140 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002141 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00002142 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00002143 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2144 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2145 }
2146
John McCallbd7370a2013-02-28 19:01:20 +00002147 llvm::Value *args[] = {
John McCallf4ddf942015-09-08 08:05:57 +00002148 Builder.CreateBitCast(addr.getPointer(), Int8PtrPtrTy),
John McCallbd7370a2013-02-28 19:01:20 +00002149 Builder.CreateBitCast(value, Int8PtrTy)
2150 };
2151 EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00002152
Craig Topperd1008e52014-05-21 05:09:00 +00002153 if (ignored) return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00002154 return value;
2155}
2156
2157/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002158/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002159/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00002160llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00002161 llvm::Value *newValue,
2162 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00002163 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00002164 bool isBlock = type->isBlockPointerType();
2165
2166 // Use a store barrier at -O0 unless this is a block type or the
2167 // lvalue is inadequately aligned.
2168 if (shouldUseFusedARCCalls() &&
2169 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00002170 (dst.getAlignment().isZero() ||
2171 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00002172 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2173 }
2174
2175 // Otherwise, split it out.
2176
2177 // Retain the new value.
2178 newValue = EmitARCRetain(type, newValue);
2179
2180 // Read the old value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002181 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00002182
2183 // Store. We do this before the release so that any deallocs won't
2184 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002185 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002186
2187 // Finally, release the old value.
John McCall5b07e802013-03-13 03:10:54 +00002188 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002189
2190 return newValue;
2191}
2192
2193/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002194/// call i8* \@objc_autorelease(i8* %value)
Pete Cooper2a988fc2016-03-21 20:50:03 +00002195llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2196 return emitARCValueOperation(*this, value,
John McCallf36e93a2015-10-21 18:06:43 +00002197 CGM.getObjCEntrypoints().objc_autorelease,
John McCallf85e1932011-06-15 23:02:42 +00002198 "objc_autorelease");
2199}
2200
2201/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002202/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002203llvm::Value *
2204CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
Pete Cooper2a988fc2016-03-21 20:50:03 +00002205 return emitARCValueOperation(*this, value,
John McCallf36e93a2015-10-21 18:06:43 +00002206 CGM.getObjCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002207 "objc_autoreleaseReturnValue",
2208 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002209}
2210
2211/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002212/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002213llvm::Value *
2214CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
Pete Cooper2a988fc2016-03-21 20:50:03 +00002215 return emitARCValueOperation(*this, value,
John McCallf36e93a2015-10-21 18:06:43 +00002216 CGM.getObjCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002217 "objc_retainAutoreleaseReturnValue",
2218 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002219}
2220
2221/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002222/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002223/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002224/// %retain = call i8* \@objc_retainBlock(i8* %value)
2225/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002226llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2227 llvm::Value *value) {
2228 if (!type->isBlockPointerType())
2229 return EmitARCRetainAutoreleaseNonBlock(value);
2230
2231 if (isa<llvm::ConstantPointerNull>(value)) return value;
2232
Chris Lattner2acc6e32011-07-18 04:24:23 +00002233 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002234 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002235 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002236 value = EmitARCAutorelease(value);
2237 return Builder.CreateBitCast(value, origType);
2238}
2239
2240/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002241/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002242llvm::Value *
2243CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
Pete Cooper2a988fc2016-03-21 20:50:03 +00002244 return emitARCValueOperation(*this, value,
John McCallf36e93a2015-10-21 18:06:43 +00002245 CGM.getObjCEntrypoints().objc_retainAutorelease,
John McCallf85e1932011-06-15 23:02:42 +00002246 "objc_retainAutorelease");
2247}
2248
John McCallf36e93a2015-10-21 18:06:43 +00002249/// i8* \@objc_loadWeak(i8** %addr)
2250/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2251llvm::Value *CodeGenFunction::EmitARCLoadWeak(Address addr) {
2252 return emitARCLoadOperation(*this, addr,
2253 CGM.getObjCEntrypoints().objc_loadWeak,
2254 "objc_loadWeak");
2255}
2256
James Dennett9d96e9c2012-06-22 05:41:30 +00002257/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf4ddf942015-09-08 08:05:57 +00002258llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(Address addr) {
John McCallf85e1932011-06-15 23:02:42 +00002259 return emitARCLoadOperation(*this, addr,
John McCallf36e93a2015-10-21 18:06:43 +00002260 CGM.getObjCEntrypoints().objc_loadWeakRetained,
John McCallf85e1932011-06-15 23:02:42 +00002261 "objc_loadWeakRetained");
2262}
2263
James Dennett9d96e9c2012-06-22 05:41:30 +00002264/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002265/// Returns %value.
John McCallf4ddf942015-09-08 08:05:57 +00002266llvm::Value *CodeGenFunction::EmitARCStoreWeak(Address addr,
John McCallf85e1932011-06-15 23:02:42 +00002267 llvm::Value *value,
2268 bool ignored) {
2269 return emitARCStoreOperation(*this, addr, value,
John McCallf36e93a2015-10-21 18:06:43 +00002270 CGM.getObjCEntrypoints().objc_storeWeak,
John McCallf85e1932011-06-15 23:02:42 +00002271 "objc_storeWeak", ignored);
2272}
2273
James Dennett9d96e9c2012-06-22 05:41:30 +00002274/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002275/// Returns %value. %addr is known to not have a current weak entry.
2276/// Essentially equivalent to:
2277/// *addr = nil; objc_storeWeak(addr, value);
John McCallf4ddf942015-09-08 08:05:57 +00002278void CodeGenFunction::EmitARCInitWeak(Address addr, llvm::Value *value) {
John McCallf85e1932011-06-15 23:02:42 +00002279 // If we're initializing to null, just write null to memory; no need
2280 // to get the runtime involved. But don't do this if optimization
2281 // is enabled, because accounting for this would make the optimizer
2282 // much more complicated.
2283 if (isa<llvm::ConstantPointerNull>(value) &&
2284 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2285 Builder.CreateStore(value, addr);
2286 return;
2287 }
2288
2289 emitARCStoreOperation(*this, addr, value,
John McCallf36e93a2015-10-21 18:06:43 +00002290 CGM.getObjCEntrypoints().objc_initWeak,
John McCallf85e1932011-06-15 23:02:42 +00002291 "objc_initWeak", /*ignored*/ true);
2292}
2293
James Dennett9d96e9c2012-06-22 05:41:30 +00002294/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002295/// Essentially objc_storeWeak(addr, nil).
John McCallf4ddf942015-09-08 08:05:57 +00002296void CodeGenFunction::EmitARCDestroyWeak(Address addr) {
John McCallf36e93a2015-10-21 18:06:43 +00002297 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_destroyWeak;
John McCallf85e1932011-06-15 23:02:42 +00002298 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002299 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002300 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002301 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2302 }
2303
2304 // Cast the argument to 'id*'.
2305 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2306
John McCallf4ddf942015-09-08 08:05:57 +00002307 EmitNounwindRuntimeCall(fn, addr.getPointer());
John McCallf85e1932011-06-15 23:02:42 +00002308}
2309
James Dennett9d96e9c2012-06-22 05:41:30 +00002310/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002311/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2312/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
John McCallf4ddf942015-09-08 08:05:57 +00002313void CodeGenFunction::EmitARCMoveWeak(Address dst, Address src) {
John McCallf85e1932011-06-15 23:02:42 +00002314 emitARCCopyOperation(*this, dst, src,
John McCallf36e93a2015-10-21 18:06:43 +00002315 CGM.getObjCEntrypoints().objc_moveWeak,
John McCallf85e1932011-06-15 23:02:42 +00002316 "objc_moveWeak");
2317}
2318
James Dennett9d96e9c2012-06-22 05:41:30 +00002319/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002320/// Disregards the current value in %dest. Essentially
2321/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
John McCallf4ddf942015-09-08 08:05:57 +00002322void CodeGenFunction::EmitARCCopyWeak(Address dst, Address src) {
John McCallf85e1932011-06-15 23:02:42 +00002323 emitARCCopyOperation(*this, dst, src,
John McCallf36e93a2015-10-21 18:06:43 +00002324 CGM.getObjCEntrypoints().objc_copyWeak,
John McCallf85e1932011-06-15 23:02:42 +00002325 "objc_copyWeak");
2326}
2327
2328/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002329/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002330llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
John McCallf36e93a2015-10-21 18:06:43 +00002331 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPush;
John McCallf85e1932011-06-15 23:02:42 +00002332 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002333 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002334 llvm::FunctionType::get(Int8PtrTy, false);
2335 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2336 }
2337
John McCallbd7370a2013-02-28 19:01:20 +00002338 return EmitNounwindRuntimeCall(fn);
John McCallf85e1932011-06-15 23:02:42 +00002339}
2340
2341/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002342/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002343void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2344 assert(value->getType() == Int8PtrTy);
2345
John McCallf36e93a2015-10-21 18:06:43 +00002346 llvm::Constant *&fn = CGM.getObjCEntrypoints().objc_autoreleasePoolPop;
John McCallf85e1932011-06-15 23:02:42 +00002347 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002348 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002349 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002350
2351 // We don't want to use a weak import here; instead we should not
2352 // fall into this path.
2353 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2354 }
2355
John McCallb57f6b32013-04-16 21:29:40 +00002356 // objc_autoreleasePoolPop can throw.
2357 EmitRuntimeCallOrInvoke(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002358}
2359
2360/// Produce the code to do an MRR version objc_autoreleasepool_push.
2361/// Which is: [[NSAutoreleasePool alloc] init];
2362/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2363/// init is declared as: - (id) init; in its NSObject super class.
2364///
2365llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2366 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +00002367 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCallf85e1932011-06-15 23:02:42 +00002368 // [NSAutoreleasePool alloc]
2369 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2370 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2371 CallArgList Args;
2372 RValue AllocRV =
2373 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2374 getContext().getObjCIdType(),
2375 AllocSel, Receiver, Args);
2376
2377 // [Receiver init]
2378 Receiver = AllocRV.getScalarVal();
2379 II = &CGM.getContext().Idents.get("init");
2380 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2381 RValue InitRV =
2382 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2383 getContext().getObjCIdType(),
2384 InitSel, Receiver, Args);
2385 return InitRV.getScalarVal();
2386}
2387
2388/// Produce the code to do a primitive release.
2389/// [tmp drain];
2390void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2391 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2392 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2393 CallArgList Args;
2394 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2395 getContext().VoidTy, DrainSel, Arg, Args);
2396}
2397
John McCallbdc4d802011-07-09 01:37:26 +00002398void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00002399 Address addr,
John McCallbdc4d802011-07-09 01:37:26 +00002400 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002401 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002402}
2403
2404void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00002405 Address addr,
John McCallbdc4d802011-07-09 01:37:26 +00002406 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002407 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002408}
2409
2410void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
John McCallf4ddf942015-09-08 08:05:57 +00002411 Address addr,
John McCallbdc4d802011-07-09 01:37:26 +00002412 QualType type) {
2413 CGF.EmitARCDestroyWeak(addr);
2414}
2415
Akira Hatanaka9a231ff2017-04-28 18:50:57 +00002416void CodeGenFunction::emitARCIntrinsicUse(CodeGenFunction &CGF, Address addr,
2417 QualType type) {
2418 llvm::Value *value = CGF.Builder.CreateLoad(addr);
2419 CGF.EmitARCIntrinsicUse(value);
2420}
2421
John McCallf85e1932011-06-15 23:02:42 +00002422namespace {
David Blaikie673861a2015-08-18 22:40:54 +00002423 struct CallObjCAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCallf85e1932011-06-15 23:02:42 +00002424 llvm::Value *Token;
2425
2426 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2427
Craig Topperf7bc4972014-03-12 06:41:41 +00002428 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002429 CGF.EmitObjCAutoreleasePoolPop(Token);
2430 }
2431 };
David Blaikie673861a2015-08-18 22:40:54 +00002432 struct CallObjCMRRAutoreleasePoolObject final : EHScopeStack::Cleanup {
John McCallf85e1932011-06-15 23:02:42 +00002433 llvm::Value *Token;
2434
2435 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2436
Craig Topperf7bc4972014-03-12 06:41:41 +00002437 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf85e1932011-06-15 23:02:42 +00002438 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2439 }
2440 };
Alexander Kornienko8ca77052015-06-22 23:07:51 +00002441}
John McCallf85e1932011-06-15 23:02:42 +00002442
2443void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002444 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002445 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2446 else
2447 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2448}
2449
John McCallf85e1932011-06-15 23:02:42 +00002450static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2451 LValue lvalue,
2452 QualType type) {
2453 switch (type.getObjCLifetime()) {
2454 case Qualifiers::OCL_None:
2455 case Qualifiers::OCL_ExplicitNone:
2456 case Qualifiers::OCL_Strong:
2457 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002458 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2459 SourceLocation()).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002460 false);
2461
2462 case Qualifiers::OCL_Weak:
2463 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2464 true);
2465 }
2466
2467 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002468}
2469
2470static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2471 const Expr *e) {
2472 e = e->IgnoreParens();
2473 QualType type = e->getType();
2474
John McCall21480112011-08-30 00:57:29 +00002475 // If we're loading retained from a __strong xvalue, we can avoid
2476 // an extra retain/release pair by zeroing out the source of this
2477 // "move" operation.
2478 if (e->isXValue() &&
2479 !type.isConstQualified() &&
2480 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2481 // Emit the lvalue.
2482 LValue lv = CGF.EmitLValue(e);
2483
2484 // Load the object pointer.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002485 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2486 SourceLocation()).getScalarVal();
John McCall21480112011-08-30 00:57:29 +00002487
2488 // Set the source pointer to NULL.
2489 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2490
2491 return TryEmitResult(result, true);
2492 }
2493
John McCallf85e1932011-06-15 23:02:42 +00002494 // As a very special optimization, in ARC++, if the l-value is the
2495 // result of a non-volatile assignment, do a simple retain of the
2496 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002497 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002498 !type.isVolatileQualified() &&
2499 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2500 isa<BinaryOperator>(e) &&
2501 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2502 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2503
2504 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2505}
2506
John McCall7164cef2016-01-27 18:32:30 +00002507typedef llvm::function_ref<llvm::Value *(CodeGenFunction &CGF,
2508 llvm::Value *value)>
2509 ValueTransform;
John McCallf85e1932011-06-15 23:02:42 +00002510
John McCall7164cef2016-01-27 18:32:30 +00002511/// Insert code immediately after a call.
2512static llvm::Value *emitARCOperationAfterCall(CodeGenFunction &CGF,
2513 llvm::Value *value,
2514 ValueTransform doAfterCall,
2515 ValueTransform doFallback) {
John McCallf85e1932011-06-15 23:02:42 +00002516 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2517 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2518
2519 // Place the retain immediately following the call.
2520 CGF.Builder.SetInsertPoint(call->getParent(),
2521 ++llvm::BasicBlock::iterator(call));
John McCall7164cef2016-01-27 18:32:30 +00002522 value = doAfterCall(CGF, value);
John McCallf85e1932011-06-15 23:02:42 +00002523
2524 CGF.Builder.restoreIP(ip);
2525 return value;
2526 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2527 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2528
2529 // Place the retain at the beginning of the normal destination block.
2530 llvm::BasicBlock *BB = invoke->getNormalDest();
2531 CGF.Builder.SetInsertPoint(BB, BB->begin());
John McCall7164cef2016-01-27 18:32:30 +00002532 value = doAfterCall(CGF, value);
John McCallf85e1932011-06-15 23:02:42 +00002533
2534 CGF.Builder.restoreIP(ip);
2535 return value;
2536
2537 // Bitcasts can arise because of related-result returns. Rewrite
2538 // the operand.
2539 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2540 llvm::Value *operand = bitcast->getOperand(0);
John McCall7164cef2016-01-27 18:32:30 +00002541 operand = emitARCOperationAfterCall(CGF, operand, doAfterCall, doFallback);
John McCallf85e1932011-06-15 23:02:42 +00002542 bitcast->setOperand(0, operand);
2543 return bitcast;
2544
2545 // Generic fall-back case.
2546 } else {
2547 // Retain using the non-block variant: we never need to do a copy
2548 // of a block that's been returned to us.
John McCall7164cef2016-01-27 18:32:30 +00002549 return doFallback(CGF, value);
2550 }
2551}
2552
2553/// Given that the given expression is some sort of call (which does
2554/// not return retained), emit a retain following it.
2555static llvm::Value *emitARCRetainCallResult(CodeGenFunction &CGF,
2556 const Expr *e) {
2557 llvm::Value *value = CGF.EmitScalarExpr(e);
2558 return emitARCOperationAfterCall(CGF, value,
2559 [](CodeGenFunction &CGF, llvm::Value *value) {
2560 return CGF.EmitARCRetainAutoreleasedReturnValue(value);
2561 },
2562 [](CodeGenFunction &CGF, llvm::Value *value) {
2563 return CGF.EmitARCRetainNonBlock(value);
2564 });
2565}
2566
2567/// Given that the given expression is some sort of call (which does
2568/// not return retained), perform an unsafeClaim following it.
2569static llvm::Value *emitARCUnsafeClaimCallResult(CodeGenFunction &CGF,
2570 const Expr *e) {
2571 llvm::Value *value = CGF.EmitScalarExpr(e);
2572 return emitARCOperationAfterCall(CGF, value,
2573 [](CodeGenFunction &CGF, llvm::Value *value) {
2574 return CGF.EmitARCUnsafeClaimAutoreleasedReturnValue(value);
2575 },
2576 [](CodeGenFunction &CGF, llvm::Value *value) {
2577 return value;
2578 });
2579}
2580
2581llvm::Value *CodeGenFunction::EmitARCReclaimReturnedObject(const Expr *E,
2582 bool allowUnsafeClaim) {
2583 if (allowUnsafeClaim &&
2584 CGM.getLangOpts().ObjCRuntime.hasARCUnsafeClaimAutoreleasedReturnValue()) {
2585 return emitARCUnsafeClaimCallResult(*this, E);
2586 } else {
2587 llvm::Value *value = emitARCRetainCallResult(*this, E);
2588 return EmitObjCConsumeObject(E->getType(), value);
John McCallf85e1932011-06-15 23:02:42 +00002589 }
2590}
2591
John McCalldc05b112011-09-10 01:16:55 +00002592/// Determine whether it might be important to emit a separate
2593/// objc_retain_block on the result of the given expression, or
2594/// whether it's okay to just emit it in a +1 context.
2595static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2596 assert(e->getType()->isBlockPointerType());
2597 e = e->IgnoreParens();
2598
2599 // For future goodness, emit block expressions directly in +1
2600 // contexts if we can.
2601 if (isa<BlockExpr>(e))
2602 return false;
2603
2604 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2605 switch (cast->getCastKind()) {
2606 // Emitting these operations in +1 contexts is goodness.
2607 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002608 case CK_ARCReclaimReturnedObject:
2609 case CK_ARCConsumeObject:
2610 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002611 return false;
2612
2613 // These operations preserve a block type.
2614 case CK_NoOp:
2615 case CK_BitCast:
2616 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2617
2618 // These operations are known to be bad (or haven't been considered).
2619 case CK_AnyPointerToBlockPointerCast:
2620 default:
2621 return true;
2622 }
2623 }
2624
2625 return true;
2626}
2627
John McCall7164cef2016-01-27 18:32:30 +00002628namespace {
2629/// A CRTP base class for emitting expressions of retainable object
2630/// pointer type in ARC.
2631template <typename Impl, typename Result> class ARCExprEmitter {
2632protected:
2633 CodeGenFunction &CGF;
2634 Impl &asImpl() { return *static_cast<Impl*>(this); }
2635
2636 ARCExprEmitter(CodeGenFunction &CGF) : CGF(CGF) {}
2637
2638public:
2639 Result visit(const Expr *e);
2640 Result visitCastExpr(const CastExpr *e);
2641 Result visitPseudoObjectExpr(const PseudoObjectExpr *e);
2642 Result visitBinaryOperator(const BinaryOperator *e);
2643 Result visitBinAssign(const BinaryOperator *e);
2644 Result visitBinAssignUnsafeUnretained(const BinaryOperator *e);
2645 Result visitBinAssignAutoreleasing(const BinaryOperator *e);
2646 Result visitBinAssignWeak(const BinaryOperator *e);
2647 Result visitBinAssignStrong(const BinaryOperator *e);
2648
2649 // Minimal implementation:
2650 // Result visitLValueToRValue(const Expr *e)
2651 // Result visitConsumeObject(const Expr *e)
2652 // Result visitExtendBlockObject(const Expr *e)
2653 // Result visitReclaimReturnedObject(const Expr *e)
2654 // Result visitCall(const Expr *e)
2655 // Result visitExpr(const Expr *e)
2656 //
2657 // Result emitBitCast(Result result, llvm::Type *resultType)
2658 // llvm::Value *getValueOfResult(Result result)
2659};
2660}
2661
2662/// Try to emit a PseudoObjectExpr under special ARC rules.
John McCall4b9c2d22011-11-06 09:01:30 +00002663///
2664/// This massively duplicates emitPseudoObjectRValue.
John McCall7164cef2016-01-27 18:32:30 +00002665template <typename Impl, typename Result>
2666Result
2667ARCExprEmitter<Impl,Result>::visitPseudoObjectExpr(const PseudoObjectExpr *E) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002668 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCall4b9c2d22011-11-06 09:01:30 +00002669
2670 // Find the result expression.
2671 const Expr *resultExpr = E->getResultExpr();
2672 assert(resultExpr);
John McCall7164cef2016-01-27 18:32:30 +00002673 Result result;
John McCall4b9c2d22011-11-06 09:01:30 +00002674
2675 for (PseudoObjectExpr::const_semantics_iterator
2676 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2677 const Expr *semantic = *i;
2678
2679 // If this semantic expression is an opaque value, bind it
2680 // to the result of its source expression.
2681 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2682 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2683 OVMA opaqueData;
2684
2685 // If this semantic is the result of the pseudo-object
2686 // expression, try to evaluate the source as +1.
2687 if (ov == resultExpr) {
2688 assert(!OVMA::shouldBindAsLValue(ov));
John McCall7164cef2016-01-27 18:32:30 +00002689 result = asImpl().visit(ov->getSourceExpr());
2690 opaqueData = OVMA::bind(CGF, ov,
2691 RValue::get(asImpl().getValueOfResult(result)));
John McCall4b9c2d22011-11-06 09:01:30 +00002692
2693 // Otherwise, just bind it.
2694 } else {
2695 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2696 }
2697 opaques.push_back(opaqueData);
2698
2699 // Otherwise, if the expression is the result, evaluate it
2700 // and remember the result.
2701 } else if (semantic == resultExpr) {
John McCall7164cef2016-01-27 18:32:30 +00002702 result = asImpl().visit(semantic);
John McCall4b9c2d22011-11-06 09:01:30 +00002703
2704 // Otherwise, evaluate the expression in an ignored context.
2705 } else {
2706 CGF.EmitIgnoredExpr(semantic);
2707 }
2708 }
2709
2710 // Unbind all the opaques now.
2711 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2712 opaques[i].unbind(CGF);
2713
2714 return result;
2715}
2716
John McCall7164cef2016-01-27 18:32:30 +00002717template <typename Impl, typename Result>
2718Result ARCExprEmitter<Impl,Result>::visitCastExpr(const CastExpr *e) {
2719 switch (e->getCastKind()) {
John McCall990567c2011-07-27 01:07:15 +00002720
John McCall7164cef2016-01-27 18:32:30 +00002721 // No-op casts don't change the type, so we just ignore them.
2722 case CK_NoOp:
2723 return asImpl().visit(e->getSubExpr());
John McCallf85e1932011-06-15 23:02:42 +00002724
John McCall7164cef2016-01-27 18:32:30 +00002725 // These casts can change the type.
2726 case CK_CPointerToObjCPointerCast:
2727 case CK_BlockPointerToObjCPointerCast:
2728 case CK_AnyPointerToBlockPointerCast:
2729 case CK_BitCast: {
2730 llvm::Type *resultType = CGF.ConvertType(e->getType());
2731 assert(e->getSubExpr()->getType()->hasPointerRepresentation());
2732 Result result = asImpl().visit(e->getSubExpr());
2733 return asImpl().emitBitCast(result, resultType);
John McCallf85e1932011-06-15 23:02:42 +00002734 }
2735
John McCall7164cef2016-01-27 18:32:30 +00002736 // Handle some casts specially.
2737 case CK_LValueToRValue:
2738 return asImpl().visitLValueToRValue(e->getSubExpr());
2739 case CK_ARCConsumeObject:
2740 return asImpl().visitConsumeObject(e->getSubExpr());
2741 case CK_ARCExtendBlockObject:
2742 return asImpl().visitExtendBlockObject(e->getSubExpr());
2743 case CK_ARCReclaimReturnedObject:
2744 return asImpl().visitReclaimReturnedObject(e->getSubExpr());
2745
2746 // Otherwise, use the default logic.
2747 default:
2748 return asImpl().visitExpr(e);
2749 }
2750}
2751
2752template <typename Impl, typename Result>
2753Result
2754ARCExprEmitter<Impl,Result>::visitBinaryOperator(const BinaryOperator *e) {
2755 switch (e->getOpcode()) {
2756 case BO_Comma:
2757 CGF.EmitIgnoredExpr(e->getLHS());
2758 CGF.EnsureInsertPoint();
2759 return asImpl().visit(e->getRHS());
2760
2761 case BO_Assign:
2762 return asImpl().visitBinAssign(e);
2763
2764 default:
2765 return asImpl().visitExpr(e);
2766 }
2767}
2768
2769template <typename Impl, typename Result>
2770Result ARCExprEmitter<Impl,Result>::visitBinAssign(const BinaryOperator *e) {
2771 switch (e->getLHS()->getType().getObjCLifetime()) {
2772 case Qualifiers::OCL_ExplicitNone:
2773 return asImpl().visitBinAssignUnsafeUnretained(e);
2774
2775 case Qualifiers::OCL_Weak:
2776 return asImpl().visitBinAssignWeak(e);
2777
2778 case Qualifiers::OCL_Autoreleasing:
2779 return asImpl().visitBinAssignAutoreleasing(e);
2780
2781 case Qualifiers::OCL_Strong:
2782 return asImpl().visitBinAssignStrong(e);
2783
2784 case Qualifiers::OCL_None:
2785 return asImpl().visitExpr(e);
2786 }
2787 llvm_unreachable("bad ObjC ownership qualifier");
2788}
2789
2790/// The default rule for __unsafe_unretained emits the RHS recursively,
2791/// stores into the unsafe variable, and propagates the result outward.
2792template <typename Impl, typename Result>
2793Result ARCExprEmitter<Impl,Result>::
2794 visitBinAssignUnsafeUnretained(const BinaryOperator *e) {
2795 // Recursively emit the RHS.
2796 // For __block safety, do this before emitting the LHS.
2797 Result result = asImpl().visit(e->getRHS());
2798
2799 // Perform the store.
2800 LValue lvalue =
2801 CGF.EmitCheckedLValue(e->getLHS(), CodeGenFunction::TCK_Store);
2802 CGF.EmitStoreThroughLValue(RValue::get(asImpl().getValueOfResult(result)),
2803 lvalue);
2804
2805 return result;
2806}
2807
2808template <typename Impl, typename Result>
2809Result
2810ARCExprEmitter<Impl,Result>::visitBinAssignAutoreleasing(const BinaryOperator *e) {
2811 return asImpl().visitExpr(e);
2812}
2813
2814template <typename Impl, typename Result>
2815Result
2816ARCExprEmitter<Impl,Result>::visitBinAssignWeak(const BinaryOperator *e) {
2817 return asImpl().visitExpr(e);
2818}
2819
2820template <typename Impl, typename Result>
2821Result
2822ARCExprEmitter<Impl,Result>::visitBinAssignStrong(const BinaryOperator *e) {
2823 return asImpl().visitExpr(e);
2824}
2825
2826/// The general expression-emission logic.
2827template <typename Impl, typename Result>
2828Result ARCExprEmitter<Impl,Result>::visit(const Expr *e) {
2829 // We should *never* see a nested full-expression here, because if
2830 // we fail to emit at +1, our caller must not retain after we close
2831 // out the full-expression. This isn't as important in the unsafe
2832 // emitter.
2833 assert(!isa<ExprWithCleanups>(e));
2834
2835 // Look through parens, __extension__, generic selection, etc.
2836 e = e->IgnoreParens();
2837
2838 // Handle certain kinds of casts.
2839 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2840 return asImpl().visitCastExpr(ce);
2841
2842 // Handle the comma operator.
2843 } else if (auto op = dyn_cast<BinaryOperator>(e)) {
2844 return asImpl().visitBinaryOperator(op);
2845
2846 // TODO: handle conditional operators here
2847
2848 // For calls and message sends, use the retained-call logic.
2849 // Delegate inits are a special case in that they're the only
2850 // returns-retained expression that *isn't* surrounded by
2851 // a consume.
2852 } else if (isa<CallExpr>(e) ||
2853 (isa<ObjCMessageExpr>(e) &&
2854 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2855 return asImpl().visitCall(e);
2856
2857 // Look through pseudo-object expressions.
2858 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2859 return asImpl().visitPseudoObjectExpr(pseudo);
2860 }
2861
2862 return asImpl().visitExpr(e);
2863}
2864
2865namespace {
2866
2867/// An emitter for +1 results.
2868struct ARCRetainExprEmitter :
2869 public ARCExprEmitter<ARCRetainExprEmitter, TryEmitResult> {
2870
2871 ARCRetainExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
2872
2873 llvm::Value *getValueOfResult(TryEmitResult result) {
2874 return result.getPointer();
2875 }
2876
2877 TryEmitResult emitBitCast(TryEmitResult result, llvm::Type *resultType) {
2878 llvm::Value *value = result.getPointer();
2879 value = CGF.Builder.CreateBitCast(value, resultType);
2880 result.setPointer(value);
2881 return result;
2882 }
2883
2884 TryEmitResult visitLValueToRValue(const Expr *e) {
2885 return tryEmitARCRetainLoadOfScalar(CGF, e);
2886 }
2887
2888 /// For consumptions, just emit the subexpression and thus elide
2889 /// the retain/release pair.
2890 TryEmitResult visitConsumeObject(const Expr *e) {
2891 llvm::Value *result = CGF.EmitScalarExpr(e);
2892 return TryEmitResult(result, true);
2893 }
2894
2895 /// Block extends are net +0. Naively, we could just recurse on
2896 /// the subexpression, but actually we need to ensure that the
2897 /// value is copied as a block, so there's a little filter here.
2898 TryEmitResult visitExtendBlockObject(const Expr *e) {
2899 llvm::Value *result; // will be a +0 value
2900
2901 // If we can't safely assume the sub-expression will produce a
2902 // block-copied value, emit the sub-expression at +0.
2903 if (shouldEmitSeparateBlockRetain(e)) {
2904 result = CGF.EmitScalarExpr(e);
2905
2906 // Otherwise, try to emit the sub-expression at +1 recursively.
2907 } else {
2908 TryEmitResult subresult = asImpl().visit(e);
2909
2910 // If that produced a retained value, just use that.
2911 if (subresult.getInt()) {
2912 return subresult;
2913 }
2914
2915 // Otherwise it's +0.
2916 result = subresult.getPointer();
2917 }
2918
2919 // Retain the object as a block.
2920 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2921 return TryEmitResult(result, true);
2922 }
2923
2924 /// For reclaims, emit the subexpression as a retained call and
2925 /// skip the consumption.
2926 TryEmitResult visitReclaimReturnedObject(const Expr *e) {
2927 llvm::Value *result = emitARCRetainCallResult(CGF, e);
2928 return TryEmitResult(result, true);
2929 }
2930
2931 /// When we have an undecorated call, retroactively do a claim.
2932 TryEmitResult visitCall(const Expr *e) {
2933 llvm::Value *result = emitARCRetainCallResult(CGF, e);
2934 return TryEmitResult(result, true);
2935 }
2936
2937 // TODO: maybe special-case visitBinAssignWeak?
2938
2939 TryEmitResult visitExpr(const Expr *e) {
2940 // We didn't find an obvious production, so emit what we've got and
2941 // tell the caller that we didn't manage to retain.
2942 llvm::Value *result = CGF.EmitScalarExpr(e);
2943 return TryEmitResult(result, false);
2944 }
2945};
2946}
2947
2948static TryEmitResult
2949tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2950 return ARCRetainExprEmitter(CGF).visit(e);
John McCallf85e1932011-06-15 23:02:42 +00002951}
2952
2953static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2954 LValue lvalue,
2955 QualType type) {
2956 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2957 llvm::Value *value = result.getPointer();
2958 if (!result.getInt())
2959 value = CGF.EmitARCRetain(type, value);
2960 return value;
2961}
2962
2963/// EmitARCRetainScalarExpr - Semantically equivalent to
2964/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2965/// best-effort attempt to peephole expressions that naturally produce
2966/// retained objects.
2967llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002968 // The retain needs to happen within the full-expression.
2969 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2970 enterFullExpression(cleanups);
2971 RunCleanupsScope scope(*this);
2972 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2973 }
2974
John McCallf85e1932011-06-15 23:02:42 +00002975 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2976 llvm::Value *value = result.getPointer();
2977 if (!result.getInt())
2978 value = EmitARCRetain(e->getType(), value);
2979 return value;
2980}
2981
2982llvm::Value *
2983CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002984 // The retain needs to happen within the full-expression.
2985 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2986 enterFullExpression(cleanups);
2987 RunCleanupsScope scope(*this);
2988 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2989 }
2990
John McCallf85e1932011-06-15 23:02:42 +00002991 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2992 llvm::Value *value = result.getPointer();
2993 if (result.getInt())
2994 value = EmitARCAutorelease(value);
2995 else
2996 value = EmitARCRetainAutorelease(e->getType(), value);
2997 return value;
2998}
2999
John McCall348f16f2011-10-04 06:23:45 +00003000llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
3001 llvm::Value *result;
3002 bool doRetain;
3003
3004 if (shouldEmitSeparateBlockRetain(e)) {
3005 result = EmitScalarExpr(e);
3006 doRetain = true;
3007 } else {
3008 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
3009 result = subresult.getPointer();
3010 doRetain = !subresult.getInt();
3011 }
3012
3013 if (doRetain)
3014 result = EmitARCRetainBlock(result, /*mandatory*/ true);
3015 return EmitObjCConsumeObject(e->getType(), result);
3016}
3017
John McCall2b014d62011-10-01 10:32:24 +00003018llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
3019 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00003020 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00003021 // Do so before running any cleanups for the full-expression.
John McCall72dcecc2013-02-12 00:25:08 +00003022 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall2b014d62011-10-01 10:32:24 +00003023 return EmitARCRetainAutoreleaseScalarExpr(expr);
3024 }
3025
3026 // Otherwise, use the normal scalar-expression emission. The
3027 // exception machinery doesn't do anything special with the
3028 // exception like retaining it, so there's no safety associated with
3029 // only running cleanups after the throw has started, and when it
3030 // matters it tends to be substantially inferior code.
3031 return EmitScalarExpr(expr);
3032}
3033
John McCall7164cef2016-01-27 18:32:30 +00003034namespace {
3035
3036/// An emitter for assigning into an __unsafe_unretained context.
3037struct ARCUnsafeUnretainedExprEmitter :
3038 public ARCExprEmitter<ARCUnsafeUnretainedExprEmitter, llvm::Value*> {
3039
3040 ARCUnsafeUnretainedExprEmitter(CodeGenFunction &CGF) : ARCExprEmitter(CGF) {}
3041
3042 llvm::Value *getValueOfResult(llvm::Value *value) {
3043 return value;
3044 }
3045
3046 llvm::Value *emitBitCast(llvm::Value *value, llvm::Type *resultType) {
3047 return CGF.Builder.CreateBitCast(value, resultType);
3048 }
3049
3050 llvm::Value *visitLValueToRValue(const Expr *e) {
3051 return CGF.EmitScalarExpr(e);
3052 }
3053
3054 /// For consumptions, just emit the subexpression and perform the
3055 /// consumption like normal.
3056 llvm::Value *visitConsumeObject(const Expr *e) {
3057 llvm::Value *value = CGF.EmitScalarExpr(e);
3058 return CGF.EmitObjCConsumeObject(e->getType(), value);
3059 }
3060
3061 /// No special logic for block extensions. (This probably can't
3062 /// actually happen in this emitter, though.)
3063 llvm::Value *visitExtendBlockObject(const Expr *e) {
3064 return CGF.EmitARCExtendBlockObject(e);
3065 }
3066
3067 /// For reclaims, perform an unsafeClaim if that's enabled.
3068 llvm::Value *visitReclaimReturnedObject(const Expr *e) {
3069 return CGF.EmitARCReclaimReturnedObject(e, /*unsafe*/ true);
3070 }
3071
3072 /// When we have an undecorated call, just emit it without adding
3073 /// the unsafeClaim.
3074 llvm::Value *visitCall(const Expr *e) {
3075 return CGF.EmitScalarExpr(e);
3076 }
3077
3078 /// Just do normal scalar emission in the default case.
3079 llvm::Value *visitExpr(const Expr *e) {
3080 return CGF.EmitScalarExpr(e);
3081 }
3082};
3083}
3084
3085static llvm::Value *emitARCUnsafeUnretainedScalarExpr(CodeGenFunction &CGF,
3086 const Expr *e) {
3087 return ARCUnsafeUnretainedExprEmitter(CGF).visit(e);
3088}
3089
3090/// EmitARCUnsafeUnretainedScalarExpr - Semantically equivalent to
3091/// immediately releasing the resut of EmitARCRetainScalarExpr, but
3092/// avoiding any spurious retains, including by performing reclaims
3093/// with objc_unsafeClaimAutoreleasedReturnValue.
3094llvm::Value *CodeGenFunction::EmitARCUnsafeUnretainedScalarExpr(const Expr *e) {
3095 // Look through full-expressions.
3096 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
3097 enterFullExpression(cleanups);
3098 RunCleanupsScope scope(*this);
3099 return emitARCUnsafeUnretainedScalarExpr(*this, cleanups->getSubExpr());
3100 }
3101
3102 return emitARCUnsafeUnretainedScalarExpr(*this, e);
3103}
3104
3105std::pair<LValue,llvm::Value*>
3106CodeGenFunction::EmitARCStoreUnsafeUnretained(const BinaryOperator *e,
3107 bool ignored) {
3108 // Evaluate the RHS first. If we're ignoring the result, assume
3109 // that we can emit at an unsafe +0.
3110 llvm::Value *value;
3111 if (ignored) {
3112 value = EmitARCUnsafeUnretainedScalarExpr(e->getRHS());
3113 } else {
3114 value = EmitScalarExpr(e->getRHS());
3115 }
3116
3117 // Emit the LHS and perform the store.
3118 LValue lvalue = EmitLValue(e->getLHS());
3119 EmitStoreOfScalar(value, lvalue);
3120
3121 return std::pair<LValue,llvm::Value*>(std::move(lvalue), value);
3122}
3123
John McCallf85e1932011-06-15 23:02:42 +00003124std::pair<LValue,llvm::Value*>
3125CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
3126 bool ignored) {
3127 // Evaluate the RHS first.
3128 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
3129 llvm::Value *value = result.getPointer();
3130
John McCallfb720812011-07-28 07:23:35 +00003131 bool hasImmediateRetain = result.getInt();
3132
3133 // If we didn't emit a retained object, and the l-value is of block
3134 // type, then we need to emit the block-retain immediately in case
3135 // it invalidates the l-value.
3136 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00003137 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00003138 hasImmediateRetain = true;
3139 }
3140
John McCallf85e1932011-06-15 23:02:42 +00003141 LValue lvalue = EmitLValue(e->getLHS());
3142
3143 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00003144 if (hasImmediateRetain) {
Nick Lewyckyc53143c2013-10-02 02:33:11 +00003145 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedman6da2c712011-12-03 04:14:32 +00003146 EmitStoreOfScalar(value, lvalue);
John McCall5b07e802013-03-13 03:10:54 +00003147 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00003148 } else {
John McCall545d9962011-06-25 02:11:03 +00003149 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00003150 }
3151
3152 return std::pair<LValue,llvm::Value*>(lvalue, value);
3153}
3154
3155std::pair<LValue,llvm::Value*>
3156CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
3157 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
3158 LValue lvalue = EmitLValue(e->getLHS());
3159
Eli Friedman6da2c712011-12-03 04:14:32 +00003160 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00003161
3162 return std::pair<LValue,llvm::Value*>(lvalue, value);
3163}
3164
3165void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00003166 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00003167 const Stmt *subStmt = ARPS.getSubStmt();
3168 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
3169
3170 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00003171 if (DI)
3172 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00003173
3174 // Keep track of the current cleanup stack depth.
3175 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00003176 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00003177 llvm::Value *token = EmitObjCAutoreleasePoolPush();
3178 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
3179 } else {
3180 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
3181 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
3182 }
3183
Aaron Ballmanbcbb92d2014-03-17 14:19:37 +00003184 for (const auto *I : S.body())
3185 EmitStmt(I);
John McCallf85e1932011-06-15 23:02:42 +00003186
Eric Christopher73fb3502011-10-13 21:45:18 +00003187 if (DI)
3188 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00003189}
John McCall0c24c802011-06-24 23:21:27 +00003190
3191/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
3192/// make sure it survives garbage collection until this point.
3193void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
3194 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00003195 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00003196 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00003197 llvm::Value *extender
3198 = llvm::InlineAsm::get(extenderType,
3199 /* assembly */ "",
3200 /* constraints */ "r",
3201 /* side effects */ true);
3202
3203 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00003204 EmitNounwindRuntimeCall(extender, object);
John McCall0c24c802011-06-24 23:21:27 +00003205}
3206
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003207/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003208/// non-trivial copy assignment function, produce following helper function.
3209/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
3210///
3211llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003212CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
3213 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00003214 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00003215 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topperd1008e52014-05-21 05:09:00 +00003216 return nullptr;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003217 QualType Ty = PID->getPropertyIvarDecl()->getType();
3218 if (!Ty->isRecordType())
Craig Topperd1008e52014-05-21 05:09:00 +00003219 return nullptr;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003220 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003221 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topperd1008e52014-05-21 05:09:00 +00003222 return nullptr;
3223 llvm::Constant *HelperFn = nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003224 if (hasTrivialSetExpr(PID))
Craig Topperd1008e52014-05-21 05:09:00 +00003225 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003226 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
3227 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
3228 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003229
3230 ASTContext &C = getContext();
3231 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003232 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003233 FunctionDecl *FD = FunctionDecl::Create(C,
3234 C.getTranslationUnitDecl(),
3235 SourceLocation(),
Craig Topperd1008e52014-05-21 05:09:00 +00003236 SourceLocation(), II, C.VoidTy,
3237 nullptr, SC_Static,
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003238 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00003239 false);
Craig Topperd1008e52014-05-21 05:09:00 +00003240
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003241 QualType DestTy = C.getPointerType(Ty);
3242 QualType SrcTy = Ty;
3243 SrcTy.addConst();
3244 SrcTy = C.getPointerType(SrcTy);
3245
3246 FunctionArgList args;
Alexey Bataev94b44182017-06-09 13:40:18 +00003247 ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3248 DestTy, ImplicitParamDecl::Other);
3249 args.push_back(&DstDecl);
3250 ImplicitParamDecl SrcDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3251 SrcTy, ImplicitParamDecl::Other);
3252 args.push_back(&SrcDecl);
Reid Klecknere6a99032014-01-31 22:54:50 +00003253
John McCall5af07632016-03-11 04:30:31 +00003254 const CGFunctionInfo &FI =
3255 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Reid Klecknere6a99032014-01-31 22:54:50 +00003256
John McCallde5d3c72012-02-17 03:33:10 +00003257 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003258
3259 llvm::Function *Fn =
3260 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00003261 "__assign_helper_atomic_property_",
3262 &CGM.getModule());
Akira Hatanakabbd65ed2015-10-28 02:30:47 +00003263
3264 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3265
Adrian Prantl94d470b2014-04-11 01:13:04 +00003266 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003267
Alexey Bataev94b44182017-06-09 13:40:18 +00003268 DeclRefExpr DstExpr(&DstDecl, false, DestTy,
John McCallf4b88a42012-03-10 09:33:50 +00003269 VK_RValue, SourceLocation());
3270 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
3271 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003272
Alexey Bataev94b44182017-06-09 13:40:18 +00003273 DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy,
John McCallf4b88a42012-03-10 09:33:50 +00003274 VK_RValue, SourceLocation());
3275 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3276 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003277
John McCallf4b88a42012-03-10 09:33:50 +00003278 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003279 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00003280 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003281 Args, DestTy->getPointeeType(),
Adam Nemeteec6cbf2017-03-27 19:17:25 +00003282 VK_LValue, SourceLocation(), FPOptions());
John McCallf4b88a42012-03-10 09:33:50 +00003283
3284 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003285
3286 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00003287 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003288 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00003289 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003290}
3291
3292llvm::Constant *
3293CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
3294 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00003295 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00003296 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topperd1008e52014-05-21 05:09:00 +00003297 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003298 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
3299 QualType Ty = PD->getType();
3300 if (!Ty->isRecordType())
Craig Topperd1008e52014-05-21 05:09:00 +00003301 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003302 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topperd1008e52014-05-21 05:09:00 +00003303 return nullptr;
3304 llvm::Constant *HelperFn = nullptr;
3305
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003306 if (hasTrivialGetExpr(PID))
Craig Topperd1008e52014-05-21 05:09:00 +00003307 return nullptr;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003308 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
3309 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
3310 return HelperFn;
3311
3312
3313 ASTContext &C = getContext();
3314 IdentifierInfo *II
3315 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
3316 FunctionDecl *FD = FunctionDecl::Create(C,
3317 C.getTranslationUnitDecl(),
3318 SourceLocation(),
Craig Topperd1008e52014-05-21 05:09:00 +00003319 SourceLocation(), II, C.VoidTy,
3320 nullptr, SC_Static,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003321 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00003322 false);
Craig Topperd1008e52014-05-21 05:09:00 +00003323
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003324 QualType DestTy = C.getPointerType(Ty);
3325 QualType SrcTy = Ty;
3326 SrcTy.addConst();
3327 SrcTy = C.getPointerType(SrcTy);
3328
3329 FunctionArgList args;
Alexey Bataev94b44182017-06-09 13:40:18 +00003330 ImplicitParamDecl DstDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3331 DestTy, ImplicitParamDecl::Other);
3332 args.push_back(&DstDecl);
3333 ImplicitParamDecl SrcDecl(getContext(), FD, SourceLocation(), /*Id=*/nullptr,
3334 SrcTy, ImplicitParamDecl::Other);
3335 args.push_back(&SrcDecl);
Reid Klecknere6a99032014-01-31 22:54:50 +00003336
John McCall5af07632016-03-11 04:30:31 +00003337 const CGFunctionInfo &FI =
3338 CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, args);
Reid Klecknere6a99032014-01-31 22:54:50 +00003339
John McCallde5d3c72012-02-17 03:33:10 +00003340 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003341
3342 llvm::Function *Fn =
3343 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
3344 "__copy_helper_atomic_property_", &CGM.getModule());
3345
Akira Hatanakabbd65ed2015-10-28 02:30:47 +00003346 CGM.SetInternalFunctionAttributes(nullptr, Fn, FI);
3347
Adrian Prantl94d470b2014-04-11 01:13:04 +00003348 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003349
Alexey Bataev94b44182017-06-09 13:40:18 +00003350 DeclRefExpr SrcExpr(&SrcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003351 VK_RValue, SourceLocation());
3352
John McCallf4b88a42012-03-10 09:33:50 +00003353 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
3354 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003355
3356 CXXConstructExpr *CXXConstExpr =
3357 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
3358
3359 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00003360 ConstructorArgs.push_back(&SRC);
Benjamin Kramerffa220b2015-06-12 15:31:50 +00003361 ConstructorArgs.append(std::next(CXXConstExpr->arg_begin()),
3362 CXXConstExpr->arg_end());
3363
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003364 CXXConstructExpr *TheCXXConstructExpr =
3365 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3366 CXXConstExpr->getConstructor(),
3367 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003368 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003369 CXXConstExpr->hadMultipleCandidates(),
3370 CXXConstExpr->isListInitialization(),
Richard Smith01ee2dc2014-07-17 05:12:35 +00003371 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003372 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00003373 CXXConstExpr->getConstructionKind(),
3374 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003375
Alexey Bataev94b44182017-06-09 13:40:18 +00003376 DeclRefExpr DstExpr(&DstDecl, false, DestTy,
John McCallf4b88a42012-03-10 09:33:50 +00003377 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003378
John McCallf4b88a42012-03-10 09:33:50 +00003379 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00003380 CharUnits Alignment
3381 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003382 EmitAggExpr(TheCXXConstructExpr,
John McCallf4ddf942015-09-08 08:05:57 +00003383 AggValueSlot::forAddr(Address(DV.getScalarVal(), Alignment),
3384 Qualifiers(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003385 AggValueSlot::IsDestructed,
3386 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00003387 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003388
3389 FinishFunction();
3390 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3391 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3392 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003393}
3394
Eli Friedmancae40c42012-02-28 01:08:45 +00003395llvm::Value *
3396CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3397 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003398 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3399 Selector CopySelector =
3400 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00003401 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3402 Selector AutoreleaseSelector =
3403 getContext().Selectors.getNullarySelector(AutoreleaseID);
3404
3405 // Emit calls to retain/autorelease.
3406 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3407 llvm::Value *Val = Block;
3408 RValue Result;
3409 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003410 Ty, CopySelector,
Craig Topperd1008e52014-05-21 05:09:00 +00003411 Val, CallArgList(), nullptr, nullptr);
Eli Friedmancae40c42012-02-28 01:08:45 +00003412 Val = Result.getScalarVal();
3413 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3414 Ty, AutoreleaseSelector,
Craig Topperd1008e52014-05-21 05:09:00 +00003415 Val, CallArgList(), nullptr, nullptr);
Eli Friedmancae40c42012-02-28 01:08:45 +00003416 Val = Result.getScalarVal();
3417 return Val;
3418}
3419
Erik Pilkington11e74072017-02-23 21:08:08 +00003420llvm::Value *
3421CodeGenFunction::EmitBuiltinAvailable(ArrayRef<llvm::Value *> Args) {
3422 assert(Args.size() == 3 && "Expected 3 argument here!");
3423
3424 if (!CGM.IsOSVersionAtLeastFn) {
3425 llvm::FunctionType *FTy =
3426 llvm::FunctionType::get(Int32Ty, {Int32Ty, Int32Ty, Int32Ty}, false);
3427 CGM.IsOSVersionAtLeastFn =
3428 CGM.CreateRuntimeFunction(FTy, "__isOSVersionAtLeast");
3429 }
3430
3431 llvm::Value *CallRes =
3432 EmitNounwindRuntimeCall(CGM.IsOSVersionAtLeastFn, Args);
3433
3434 return Builder.CreateICmpNE(CallRes, llvm::Constant::getNullValue(Int32Ty));
3435}
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003436
Alex Lorenz50a59092017-03-23 11:14:27 +00003437void CodeGenModule::emitAtAvailableLinkGuard() {
3438 if (!IsOSVersionAtLeastFn)
3439 return;
3440 // @available requires CoreFoundation only on Darwin.
3441 if (!Target.getTriple().isOSDarwin())
3442 return;
3443 // Add -framework CoreFoundation to the linker commands. We still want to
3444 // emit the core foundation reference down below because otherwise if
3445 // CoreFoundation is not used in the code, the linker won't link the
3446 // framework.
3447 auto &Context = getLLVMContext();
3448 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"),
3449 llvm::MDString::get(Context, "CoreFoundation")};
3450 LinkerOptionsMetadata.push_back(llvm::MDNode::get(Context, Args));
3451 // Emit a reference to a symbol from CoreFoundation to ensure that
3452 // CoreFoundation is linked into the final binary.
3453 llvm::FunctionType *FTy =
3454 llvm::FunctionType::get(Int32Ty, {VoidPtrTy}, false);
3455 llvm::Constant *CFFunc =
3456 CreateRuntimeFunction(FTy, "CFBundleGetVersionNumber");
3457
3458 llvm::FunctionType *CheckFTy = llvm::FunctionType::get(VoidTy, {}, false);
3459 llvm::Function *CFLinkCheckFunc = cast<llvm::Function>(CreateBuiltinFunction(
3460 CheckFTy, "__clang_at_available_requires_core_foundation_framework"));
3461 CFLinkCheckFunc->setLinkage(llvm::GlobalValue::LinkOnceAnyLinkage);
3462 CFLinkCheckFunc->setVisibility(llvm::GlobalValue::HiddenVisibility);
3463 CodeGenFunction CGF(*this);
3464 CGF.Builder.SetInsertPoint(CGF.createBasicBlock("", CFLinkCheckFunc));
3465 CGF.EmitNounwindRuntimeCall(CFFunc, llvm::Constant::getNullValue(VoidPtrTy));
3466 CGF.Builder.CreateUnreachable();
3467 addCompilerUsedGlobal(CFLinkCheckFunc);
3468}
3469
Angel Garcia Gomezd1620352015-10-20 13:23:58 +00003470CGObjCRuntime::~CGObjCRuntime() {}