blob: 94bad921809d876451044aeb74a2ab98439def4a [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
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"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000036 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattner8fdf3282008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000043{
David Chisnall0d13f6f2010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000057}
58
Daniel Dunbared7c6182008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattner8fdf3282008-06-24 17:04:18 +000063
Douglas Gregor926df6c2011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCallf85e1932011-06-15 23:02:42 +000072
Douglas Gregor926df6c2011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattner8fdf3282008-06-24 17:04:18 +000082
John McCalldc7c5ad2011-07-22 08:53:00 +000083/// Decide whether to extend the lifetime of the receiver of a
84/// returns-inner-pointer message.
85static bool
86shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
87 switch (message->getReceiverKind()) {
88
89 // For a normal instance message, we should extend unless the
90 // receiver is loaded from a variable with precise lifetime.
91 case ObjCMessageExpr::Instance: {
92 const Expr *receiver = message->getInstanceReceiver();
93 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
94 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
95 receiver = ice->getSubExpr()->IgnoreParens();
96
97 // Only __strong variables.
98 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
99 return true;
100
101 // All ivars and fields have precise lifetime.
102 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
103 return false;
104
105 // Otherwise, check for variables.
106 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
107 if (!declRef) return true;
108 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
109 if (!var) return true;
110
111 // All variables have precise lifetime except local variables with
112 // automatic storage duration that aren't specially marked.
113 return (var->hasLocalStorage() &&
114 !var->hasAttr<ObjCPreciseLifetimeAttr>());
115 }
116
117 case ObjCMessageExpr::Class:
118 case ObjCMessageExpr::SuperClass:
119 // It's never necessary for class objects.
120 return false;
121
122 case ObjCMessageExpr::SuperInstance:
123 // We generally assume that 'self' lives throughout a method call.
124 return false;
125 }
126
127 llvm_unreachable("invalid receiver kind");
128}
129
John McCallef072fd2010-05-22 01:48:05 +0000130RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000132 // Only the lookup mechanism and first two arguments of the method
133 // implementation vary between runtimes. We can get the receiver and
134 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000135
John McCallf85e1932011-06-15 23:02:42 +0000136 bool isDelegateInit = E->isDelegateInitCall();
137
John McCalldc7c5ad2011-07-22 08:53:00 +0000138 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000139
John McCallf85e1932011-06-15 23:02:42 +0000140 // We don't retain the receiver in delegate init calls, and this is
141 // safe because the receiver value is always loaded from 'self',
142 // which we zero out. We don't want to Block_copy block receivers,
143 // though.
144 bool retainSelf =
145 (!isDelegateInit &&
146 CGM.getLangOptions().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000147 method &&
148 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000149
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000150 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000151 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000152 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000153 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000154 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000155 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000156 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000157 switch (E->getReceiverKind()) {
158 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000159 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000160 if (retainSelf) {
161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162 E->getInstanceReceiver());
163 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000164 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000165 } else
166 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000167 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000168
Douglas Gregor04badcf2010-04-21 00:45:42 +0000169 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000170 ReceiverType = E->getClassReceiver();
171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000172 assert(ObjTy && "Invalid Objective-C class message send");
173 OID = ObjTy->getInterface();
174 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000175 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000176 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000177 break;
178 }
179
180 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000181 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000182 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000183 isSuperMessage = true;
184 break;
185
186 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000187 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000188 Receiver = LoadObjCSelf();
189 isSuperMessage = true;
190 isClassMessage = true;
191 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000192 }
193
John McCalldc7c5ad2011-07-22 08:53:00 +0000194 if (retainSelf)
195 Receiver = EmitARCRetainNonBlock(Receiver);
196
197 // In ARC, we sometimes want to "extend the lifetime"
198 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
199 // messages.
200 if (getLangOptions().ObjCAutoRefCount && method &&
201 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
202 shouldExtendReceiverForInnerPointerMessage(E))
203 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
204
John McCallf85e1932011-06-15 23:02:42 +0000205 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000206 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000207
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000208 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000209 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000210
John McCallf85e1932011-06-15 23:02:42 +0000211 // For delegate init calls in ARC, do an unsafe store of null into
212 // self. This represents the call taking direct ownership of that
213 // value. We have to do this after emitting the other call
214 // arguments because they might also reference self, but we don't
215 // have to worry about any of them modifying self because that would
216 // be an undefined read and write of an object in unordered
217 // expressions.
218 if (isDelegateInit) {
219 assert(getLangOptions().ObjCAutoRefCount &&
220 "delegate init calls should only be marked in ARC");
221
222 // Do an unsafe store of null into self.
223 llvm::Value *selfAddr =
224 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
225 assert(selfAddr && "no self entry for a delegate init call?");
226
227 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
228 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000229
Douglas Gregor926df6c2011-06-11 01:09:30 +0000230 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000231 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000232 // super is only valid in an Objective-C method
233 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000234 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000235 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
236 E->getSelector(),
237 OMD->getClassInterface(),
238 isCategoryImpl,
239 Receiver,
240 isClassMessage,
241 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000242 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000243 } else {
244 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
245 E->getSelector(),
246 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000247 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000248 }
John McCallf85e1932011-06-15 23:02:42 +0000249
250 // For delegate init calls in ARC, implicitly store the result of
251 // the call back into self. This takes ownership of the value.
252 if (isDelegateInit) {
253 llvm::Value *selfAddr =
254 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
255 llvm::Value *newSelf = result.getScalarVal();
256
257 // The delegate return type isn't necessarily a matching type; in
258 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000259 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000260 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
261 newSelf = Builder.CreateBitCast(newSelf, selfTy);
262
263 Builder.CreateStore(newSelf, selfAddr);
264 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000265
266 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000267}
268
John McCallf85e1932011-06-15 23:02:42 +0000269namespace {
270struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000271 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000272 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000273
274 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000275 const ObjCInterfaceDecl *iface = impl->getClassInterface();
276 if (!iface->getSuperClass()) return;
277
John McCall799d34e2011-07-13 18:26:47 +0000278 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
279
John McCallf85e1932011-06-15 23:02:42 +0000280 // Call [super dealloc] if we have a superclass.
281 llvm::Value *self = CGF.LoadObjCSelf();
282
283 CallArgList args;
284 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
285 CGF.getContext().VoidTy,
286 method->getSelector(),
287 iface,
John McCall799d34e2011-07-13 18:26:47 +0000288 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000289 self,
290 /*is class msg*/ false,
291 args,
292 method);
293 }
294};
295}
296
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000297/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
298/// the LLVM function and sets the other context used by
299/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000300void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000301 const ObjCContainerDecl *CD,
302 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000303 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000304 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000305 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
306 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000307
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000308 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000309
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000310 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
311 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000312
John McCalld26bc762011-03-09 04:27:21 +0000313 args.push_back(OMD->getSelfDecl());
314 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000315
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000316 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Chris Lattner89951a82009-02-20 18:43:26 +0000317 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000318 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000319
Peter Collingbourne14110472011-01-13 18:57:25 +0000320 CurGD = OMD;
321
Devang Patel8d3f8972011-05-19 23:37:41 +0000322 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000323
324 // In ARC, certain methods get an extra cleanup.
325 if (CGM.getLangOptions().ObjCAutoRefCount &&
326 OMD->isInstanceMethod() &&
327 OMD->getSelector().isUnarySelector()) {
328 const IdentifierInfo *ident =
329 OMD->getSelector().getIdentifierInfoForSlot(0);
330 if (ident->isStr("dealloc"))
331 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
332 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000333}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000334
John McCallf85e1932011-06-15 23:02:42 +0000335static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
336 LValue lvalue, QualType type);
337
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000338/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000339/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000340void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000341 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000342 EmitStmt(OMD->getBody());
343 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000344}
345
John McCall41bdde92011-09-12 23:06:44 +0000346/// emitStructGetterCall - Call the runtime function to load a property
347/// into the return value slot.
348static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
349 bool isAtomic, bool hasStrong) {
350 ASTContext &Context = CGF.getContext();
351
352 llvm::Value *src =
353 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
354 ivar, 0).getAddress();
355
356 // objc_copyStruct (ReturnValue, &structIvar,
357 // sizeof (Type of Ivar), isAtomic, false);
358 CallArgList args;
359
360 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
361 args.add(RValue::get(dest), Context.VoidPtrTy);
362
363 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
364 args.add(RValue::get(src), Context.VoidPtrTy);
365
366 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
367 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
368 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
369 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
370
371 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
372 CGF.EmitCall(CGF.getTypes().getFunctionInfo(Context.VoidTy, args,
373 FunctionType::ExtInfo()),
374 fn, ReturnValueSlot(), args);
375}
376
John McCall1e1f4872011-09-13 03:34:09 +0000377/// Determine whether the given architecture supports unaligned atomic
378/// accesses. They don't have to be fast, just faster than a function
379/// call and a mutex.
380static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000381 // FIXME: Allow unaligned atomic load/store on x86. (It is not
382 // currently supported by the backend.)
383 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000384}
385
386/// Return the maximum size that permits atomic accesses for the given
387/// architecture.
388static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
389 llvm::Triple::ArchType arch) {
390 // ARM has 8-byte atomic accesses, but it's not clear whether we
391 // want to rely on them here.
392
393 // In the default case, just assume that any size up to a pointer is
394 // fine given adequate alignment.
395 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
396}
397
398namespace {
399 class PropertyImplStrategy {
400 public:
401 enum StrategyKind {
402 /// The 'native' strategy is to use the architecture's provided
403 /// reads and writes.
404 Native,
405
406 /// Use objc_setProperty and objc_getProperty.
407 GetSetProperty,
408
409 /// Use objc_setProperty for the setter, but use expression
410 /// evaluation for the getter.
411 SetPropertyAndExpressionGet,
412
413 /// Use objc_copyStruct.
414 CopyStruct,
415
416 /// The 'expression' strategy is to emit normal assignment or
417 /// lvalue-to-rvalue expressions.
418 Expression
419 };
420
421 StrategyKind getKind() const { return StrategyKind(Kind); }
422
423 bool hasStrongMember() const { return HasStrong; }
424 bool isAtomic() const { return IsAtomic; }
425 bool isCopy() const { return IsCopy; }
426
427 CharUnits getIvarSize() const { return IvarSize; }
428 CharUnits getIvarAlignment() const { return IvarAlignment; }
429
430 PropertyImplStrategy(CodeGenModule &CGM,
431 const ObjCPropertyImplDecl *propImpl);
432
433 private:
434 unsigned Kind : 8;
435 unsigned IsAtomic : 1;
436 unsigned IsCopy : 1;
437 unsigned HasStrong : 1;
438
439 CharUnits IvarSize;
440 CharUnits IvarAlignment;
441 };
442}
443
444/// Pick an implementation strategy for the the given property synthesis.
445PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
446 const ObjCPropertyImplDecl *propImpl) {
447 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000448 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000449
John McCall265941b2011-09-13 18:31:23 +0000450 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
451 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000452 HasStrong = false; // doesn't matter here.
453
454 // Evaluate the ivar's size and alignment.
455 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
456 QualType ivarType = ivar->getType();
457 llvm::tie(IvarSize, IvarAlignment)
458 = CGM.getContext().getTypeInfoInChars(ivarType);
459
460 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000461 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000462 if (IsCopy) {
463 Kind = GetSetProperty;
464 return;
465 }
466
John McCall265941b2011-09-13 18:31:23 +0000467 // Handle retain.
468 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000469 // In GC-only, there's nothing special that needs to be done.
Douglas Gregore289d812011-09-13 17:21:33 +0000470 if (CGM.getLangOptions().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000471 // fallthrough
472
473 // In ARC, if the property is non-atomic, use expression emission,
474 // which translates to objc_storeStrong. This isn't required, but
475 // it's slightly nicer.
476 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
477 Kind = Expression;
478 return;
479
480 // Otherwise, we need to at least use setProperty. However, if
481 // the property isn't atomic, we can use normal expression
482 // emission for the getter.
483 } else if (!IsAtomic) {
484 Kind = SetPropertyAndExpressionGet;
485 return;
486
487 // Otherwise, we have to use both setProperty and getProperty.
488 } else {
489 Kind = GetSetProperty;
490 return;
491 }
492 }
493
494 // If we're not atomic, just use expression accesses.
495 if (!IsAtomic) {
496 Kind = Expression;
497 return;
498 }
499
John McCall5889c602011-09-13 05:36:29 +0000500 // Properties on bitfield ivars need to be emitted using expression
501 // accesses even if they're nominally atomic.
502 if (ivar->isBitField()) {
503 Kind = Expression;
504 return;
505 }
506
John McCall1e1f4872011-09-13 03:34:09 +0000507 // GC-qualified or ARC-qualified ivars need to be emitted as
508 // expressions. This actually works out to being atomic anyway,
509 // except for ARC __strong, but that should trigger the above code.
510 if (ivarType.hasNonTrivialObjCLifetime() ||
Douglas Gregore289d812011-09-13 17:21:33 +0000511 (CGM.getLangOptions().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000512 CGM.getContext().getObjCGCAttrKind(ivarType))) {
513 Kind = Expression;
514 return;
515 }
516
517 // Compute whether the ivar has strong members.
Douglas Gregore289d812011-09-13 17:21:33 +0000518 if (CGM.getLangOptions().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000519 if (const RecordType *recordType = ivarType->getAs<RecordType>())
520 HasStrong = recordType->getDecl()->hasObjectMember();
521
522 // We can never access structs with object members with a native
523 // access, because we need to use write barriers. This is what
524 // objc_copyStruct is for.
525 if (HasStrong) {
526 Kind = CopyStruct;
527 return;
528 }
529
530 // Otherwise, this is target-dependent and based on the size and
531 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000532
533 // If the size of the ivar is not a power of two, give up. We don't
534 // want to get into the business of doing compare-and-swaps.
535 if (!IvarSize.isPowerOfTwo()) {
536 Kind = CopyStruct;
537 return;
538 }
539
John McCall1e1f4872011-09-13 03:34:09 +0000540 llvm::Triple::ArchType arch =
541 CGM.getContext().getTargetInfo().getTriple().getArch();
542
543 // Most architectures require memory to fit within a single cache
544 // line, so the alignment has to be at least the size of the access.
545 // Otherwise we have to grab a lock.
546 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
547 Kind = CopyStruct;
548 return;
549 }
550
551 // If the ivar's size exceeds the architecture's maximum atomic
552 // access size, we have to use CopyStruct.
553 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
554 Kind = CopyStruct;
555 return;
556 }
557
558 // Otherwise, we can use native loads and stores.
559 Kind = Native;
560}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000561
562/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000563/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
564/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000565void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
566 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000567 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000568 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000569 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
570 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
571 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000572 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000574 generateObjCGetterBody(IMP, PID, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000575
576 FinishFunction();
577}
578
John McCall6c11f0b2011-09-13 06:00:03 +0000579static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
580 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000581 if (!getter) return true;
582
583 // Sema only makes only of these when the ivar has a C++ class type,
584 // so the form is pretty constrained.
585
John McCall6c11f0b2011-09-13 06:00:03 +0000586 // If the property has a reference type, we might just be binding a
587 // reference, in which case the result will be a gl-value. We should
588 // treat this as a non-trivial operation.
589 if (getter->isGLValue())
590 return false;
591
John McCall1e1f4872011-09-13 03:34:09 +0000592 // If we selected a trivial copy-constructor, we're okay.
593 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
594 return (construct->getConstructor()->isTrivial());
595
596 // The constructor might require cleanups (in which case it's never
597 // trivial).
598 assert(isa<ExprWithCleanups>(getter));
599 return false;
600}
601
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000602/// emitCPPObjectAtomicGetterCall - Call the runtime function to
603/// copy the ivar into the resturn slot.
604static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
605 llvm::Value *returnAddr,
606 ObjCIvarDecl *ivar,
607 llvm::Constant *AtomicHelperFn) {
608 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
609 // AtomicHelperFn);
610 CallArgList args;
611
612 // The 1st argument is the return Slot.
613 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
614
615 // The 2nd argument is the address of the ivar.
616 llvm::Value *ivarAddr =
617 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
618 CGF.LoadObjCSelf(), ivar, 0).getAddress();
619 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
620 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
621
622 // Third argument is the helper function.
623 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
624
625 llvm::Value *copyCppAtomicObjectFn =
626 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
627 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
628 FunctionType::ExtInfo()),
629 copyCppAtomicObjectFn, ReturnValueSlot(), args);
630}
631
John McCall1e1f4872011-09-13 03:34:09 +0000632void
633CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000634 const ObjCPropertyImplDecl *propImpl,
635 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000636 // If there's a non-trivial 'get' expression, we just have to emit that.
637 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000638 if (!AtomicHelperFn) {
639 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
640 /*nrvo*/ 0);
641 EmitReturnStmt(ret);
642 }
643 else {
644 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
645 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
646 ivar, AtomicHelperFn);
647 }
John McCall1e1f4872011-09-13 03:34:09 +0000648 return;
649 }
650
651 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
652 QualType propType = prop->getType();
653 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
654
655 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
656
657 // Pick an implementation strategy.
658 PropertyImplStrategy strategy(CGM, propImpl);
659 switch (strategy.getKind()) {
660 case PropertyImplStrategy::Native: {
661 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
662
663 // Currently, all atomic accesses have to be through integer
664 // types, so there's no point in trying to pick a prettier type.
665 llvm::Type *bitcastType =
666 llvm::Type::getIntNTy(getLLVMContext(),
667 getContext().toBits(strategy.getIvarSize()));
668 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
669
670 // Perform an atomic load. This does not impose ordering constraints.
671 llvm::Value *ivarAddr = LV.getAddress();
672 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
673 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
674 load->setAlignment(strategy.getIvarAlignment().getQuantity());
675 load->setAtomic(llvm::Unordered);
676
677 // Store that value into the return address. Doing this with a
678 // bitcast is likely to produce some pretty ugly IR, but it's not
679 // the *most* terrible thing in the world.
680 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
681
682 // Make sure we don't do an autorelease.
683 AutoreleaseResult = false;
684 return;
685 }
686
687 case PropertyImplStrategy::GetSetProperty: {
688 llvm::Value *getPropertyFn =
689 CGM.getObjCRuntime().GetPropertyGetFunction();
690 if (!getPropertyFn) {
691 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000692 return;
693 }
694
695 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
696 // FIXME: Can't this be simpler? This might even be worse than the
697 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000698 llvm::Value *cmd =
699 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
700 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
701 llvm::Value *ivarOffset =
702 EmitIvarOffset(classImpl->getClassInterface(), ivar);
703
704 CallArgList args;
705 args.add(RValue::get(self), getContext().getObjCIdType());
706 args.add(RValue::get(cmd), getContext().getObjCSelType());
707 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000708 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
709 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000710
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000711 // FIXME: We shouldn't need to get the function info here, the
712 // runtime already should have computed it to build the function.
John McCall1e1f4872011-09-13 03:34:09 +0000713 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCall41bdde92011-09-12 23:06:44 +0000714 FunctionType::ExtInfo()),
John McCall1e1f4872011-09-13 03:34:09 +0000715 getPropertyFn, ReturnValueSlot(), args);
716
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000717 // We need to fix the type here. Ivars with copy & retain are
718 // always objects so we don't need to worry about complex or
719 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000720 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000721 getTypes().ConvertType(propType)));
722
723 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000724
725 // objc_getProperty does an autorelease, so we should suppress ours.
726 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000727
John McCall1e1f4872011-09-13 03:34:09 +0000728 return;
729 }
730
731 case PropertyImplStrategy::CopyStruct:
732 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
733 strategy.hasStrongMember());
734 return;
735
736 case PropertyImplStrategy::Expression:
737 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
738 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
739
740 QualType ivarType = ivar->getType();
741 if (ivarType->isAnyComplexType()) {
742 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
743 LV.isVolatileQualified());
744 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
745 } else if (hasAggregateLLVMType(ivarType)) {
746 // The return value slot is guaranteed to not be aliased, but
747 // that's not necessarily the same as "on the stack", so
748 // we still potentially need objc_memmove_collectable.
749 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
750 } else {
John McCallba3dd902011-07-22 05:23:13 +0000751 llvm::Value *value;
752 if (propType->isReferenceType()) {
753 value = LV.getAddress();
754 } else {
755 // We want to load and autoreleaseReturnValue ARC __weak ivars.
756 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000757 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000758
759 // Otherwise we want to do a simple load, suppressing the
760 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000761 } else {
John McCallba3dd902011-07-22 05:23:13 +0000762 value = EmitLoadOfLValue(LV).getScalarVal();
763 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000764 }
John McCallf85e1932011-06-15 23:02:42 +0000765
John McCallba3dd902011-07-22 05:23:13 +0000766 value = Builder.CreateBitCast(value, ConvertType(propType));
767 }
768
769 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000770 }
John McCall1e1f4872011-09-13 03:34:09 +0000771 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000772 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000773
John McCall1e1f4872011-09-13 03:34:09 +0000774 }
775 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000776}
777
John McCall41bdde92011-09-12 23:06:44 +0000778/// emitStructSetterCall - Call the runtime function to store the value
779/// from the first formal parameter into the given ivar.
780static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
781 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000782 // objc_copyStruct (&structIvar, &Arg,
783 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000784 CallArgList args;
785
786 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000787 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
788 CGF.LoadObjCSelf(), ivar, 0)
789 .getAddress();
790 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
791 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000792
793 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000794 ParmVarDecl *argVar = *OMD->param_begin();
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000795 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
796 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000797 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
798 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
799 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000800
801 // The third argument is the sizeof the type.
802 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000803 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
804 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000805
John McCall41bdde92011-09-12 23:06:44 +0000806 // The fourth argument is the 'isAtomic' flag.
807 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000808
John McCall41bdde92011-09-12 23:06:44 +0000809 // The fifth argument is the 'hasStrong' flag.
810 // FIXME: should this really always be false?
811 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
812
813 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
814 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
815 FunctionType::ExtInfo()),
816 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000817}
818
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000819/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
820/// the value from the first formal parameter into the given ivar, using
821/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
822static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
823 ObjCMethodDecl *OMD,
824 ObjCIvarDecl *ivar,
825 llvm::Constant *AtomicHelperFn) {
826 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
827 // AtomicHelperFn);
828 CallArgList args;
829
830 // The first argument is the address of the ivar.
831 llvm::Value *ivarAddr =
832 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
833 CGF.LoadObjCSelf(), ivar, 0).getAddress();
834 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
835 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
836
837 // The second argument is the address of the parameter variable.
838 ParmVarDecl *argVar = *OMD->param_begin();
839 DeclRefExpr argRef(argVar, argVar->getType().getNonReferenceType(),
840 VK_LValue, SourceLocation());
841 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
842 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
843 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
844
845 // Third argument is the helper function.
846 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
847
848 llvm::Value *copyCppAtomicObjectFn =
849 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
850 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
851 FunctionType::ExtInfo()),
852 copyCppAtomicObjectFn, ReturnValueSlot(), args);
853
854
855}
856
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000857
John McCall1e1f4872011-09-13 03:34:09 +0000858static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
859 Expr *setter = PID->getSetterCXXAssignment();
860 if (!setter) return true;
861
862 // Sema only makes only of these when the ivar has a C++ class type,
863 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +0000864
865 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +0000866 // This also implies that there's nothing non-trivial going on with
867 // the arguments, because operator= can only be trivial if it's a
868 // synthesized assignment operator and therefore both parameters are
869 // references.
870 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +0000871 if (const FunctionDecl *callee
872 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
873 if (callee->isTrivial())
874 return true;
875 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000876 }
John McCall71c758d2011-09-10 09:17:20 +0000877
John McCall1e1f4872011-09-13 03:34:09 +0000878 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +0000879 return false;
880}
881
John McCall71c758d2011-09-10 09:17:20 +0000882void
883CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000884 const ObjCPropertyImplDecl *propImpl,
885 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +0000886 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +0000887 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +0000888 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000889
890 // Just use the setter expression if Sema gave us one and it's
891 // non-trivial.
892 if (!hasTrivialSetExpr(propImpl)) {
893 if (!AtomicHelperFn)
894 // If non-atomic, assignment is called directly.
895 EmitStmt(propImpl->getSetterCXXAssignment());
896 else
897 // If atomic, assignment is called via a locking api.
898 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
899 AtomicHelperFn);
900 return;
901 }
John McCall71c758d2011-09-10 09:17:20 +0000902
John McCall1e1f4872011-09-13 03:34:09 +0000903 PropertyImplStrategy strategy(CGM, propImpl);
904 switch (strategy.getKind()) {
905 case PropertyImplStrategy::Native: {
906 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +0000907
John McCall1e1f4872011-09-13 03:34:09 +0000908 LValue ivarLValue =
909 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
910 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +0000911
John McCall1e1f4872011-09-13 03:34:09 +0000912 // Currently, all atomic accesses have to be through integer
913 // types, so there's no point in trying to pick a prettier type.
914 llvm::Type *bitcastType =
915 llvm::Type::getIntNTy(getLLVMContext(),
916 getContext().toBits(strategy.getIvarSize()));
917 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
918
919 // Cast both arguments to the chosen operation type.
920 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
921 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
922
923 // This bitcast load is likely to cause some nasty IR.
924 llvm::Value *load = Builder.CreateLoad(argAddr);
925
926 // Perform an atomic store. There are no memory ordering requirements.
927 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
928 store->setAlignment(strategy.getIvarAlignment().getQuantity());
929 store->setAtomic(llvm::Unordered);
930 return;
931 }
932
933 case PropertyImplStrategy::GetSetProperty:
934 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall71c758d2011-09-10 09:17:20 +0000935 llvm::Value *setPropertyFn =
936 CGM.getObjCRuntime().GetPropertySetFunction();
937 if (!setPropertyFn) {
938 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
939 return;
940 }
941
942 // Emit objc_setProperty((id) self, _cmd, offset, arg,
943 // <is-atomic>, <is-copy>).
944 llvm::Value *cmd =
945 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
946 llvm::Value *self =
947 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
948 llvm::Value *ivarOffset =
949 EmitIvarOffset(classImpl->getClassInterface(), ivar);
950 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
951 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
952
953 CallArgList args;
954 args.add(RValue::get(self), getContext().getObjCIdType());
955 args.add(RValue::get(cmd), getContext().getObjCSelType());
956 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
957 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCall1e1f4872011-09-13 03:34:09 +0000958 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
959 getContext().BoolTy);
960 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
961 getContext().BoolTy);
John McCall71c758d2011-09-10 09:17:20 +0000962 // FIXME: We shouldn't need to get the function info here, the runtime
963 // already should have computed it to build the function.
964 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
965 FunctionType::ExtInfo()),
966 setPropertyFn, ReturnValueSlot(), args);
967 return;
968 }
969
John McCall1e1f4872011-09-13 03:34:09 +0000970 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +0000971 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +0000972 return;
John McCall1e1f4872011-09-13 03:34:09 +0000973
974 case PropertyImplStrategy::Expression:
975 break;
John McCall71c758d2011-09-10 09:17:20 +0000976 }
977
978 // Otherwise, fake up some ASTs and emit a normal assignment.
979 ValueDecl *selfDecl = setterMethod->getSelfDecl();
980 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
981 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
982 selfDecl->getType(), CK_LValueToRValue, &self,
983 VK_RValue);
984 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
985 SourceLocation(), &selfLoad, true, true);
986
987 ParmVarDecl *argDecl = *setterMethod->param_begin();
988 QualType argType = argDecl->getType().getNonReferenceType();
989 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
990 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
991 argType.getUnqualifiedType(), CK_LValueToRValue,
992 &arg, VK_RValue);
993
994 // The property type can differ from the ivar type in some situations with
995 // Objective-C pointer types, we can always bit cast the RHS in these cases.
996 // The following absurdity is just to ensure well-formed IR.
997 CastKind argCK = CK_NoOp;
998 if (ivarRef.getType()->isObjCObjectPointerType()) {
999 if (argLoad.getType()->isObjCObjectPointerType())
1000 argCK = CK_BitCast;
1001 else if (argLoad.getType()->isBlockPointerType())
1002 argCK = CK_BlockPointerToObjCPointerCast;
1003 else
1004 argCK = CK_CPointerToObjCPointerCast;
1005 } else if (ivarRef.getType()->isBlockPointerType()) {
1006 if (argLoad.getType()->isBlockPointerType())
1007 argCK = CK_BitCast;
1008 else
1009 argCK = CK_AnyPointerToBlockPointerCast;
1010 } else if (ivarRef.getType()->isPointerType()) {
1011 argCK = CK_BitCast;
1012 }
1013 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1014 ivarRef.getType(), argCK, &argLoad,
1015 VK_RValue);
1016 Expr *finalArg = &argLoad;
1017 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1018 argLoad.getType()))
1019 finalArg = &argCast;
1020
1021
1022 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1023 ivarRef.getType(), VK_RValue, OK_Ordinary,
1024 SourceLocation());
1025 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001026}
1027
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001028/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +00001029/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
1030/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001031void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1032 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001033 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001034 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001035 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1036 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1037 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +00001038 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001039
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001040 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001041
1042 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001043}
1044
John McCalle81ac692011-03-22 07:05:39 +00001045namespace {
John McCall9928c482011-07-12 16:41:08 +00001046 struct DestroyIvar : EHScopeStack::Cleanup {
1047 private:
1048 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001049 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001050 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001051 bool useEHCleanupForArray;
1052 public:
1053 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1054 CodeGenFunction::Destroyer *destroyer,
1055 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001056 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001057 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001058
John McCallad346f42011-07-12 20:27:29 +00001059 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001060 LValue lvalue
1061 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1062 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001063 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001064 }
1065 };
1066}
1067
John McCall9928c482011-07-12 16:41:08 +00001068/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1069static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1070 llvm::Value *addr,
1071 QualType type) {
1072 llvm::Value *null = getNullForVariable(addr);
1073 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1074}
John McCallf85e1932011-06-15 23:02:42 +00001075
John McCalle81ac692011-03-22 07:05:39 +00001076static void emitCXXDestructMethod(CodeGenFunction &CGF,
1077 ObjCImplementationDecl *impl) {
1078 CodeGenFunction::RunCleanupsScope scope(CGF);
1079
1080 llvm::Value *self = CGF.LoadObjCSelf();
1081
Jordy Rosedb8264e2011-07-22 02:08:32 +00001082 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1083 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001084 ivar; ivar = ivar->getNextIvar()) {
1085 QualType type = ivar->getType();
1086
John McCalle81ac692011-03-22 07:05:39 +00001087 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001088 QualType::DestructionKind dtorKind = type.isDestructedType();
1089 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001090
John McCall9928c482011-07-12 16:41:08 +00001091 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001092
John McCall9928c482011-07-12 16:41:08 +00001093 // Use a call to objc_storeStrong to destroy strong ivars, for the
1094 // general benefit of the tools.
1095 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001096 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001097
John McCall9928c482011-07-12 16:41:08 +00001098 // Otherwise use the default for the destruction kind.
1099 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001100 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001101 }
John McCall9928c482011-07-12 16:41:08 +00001102
1103 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1104
1105 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1106 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001107 }
1108
1109 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1110}
1111
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001112void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1113 ObjCMethodDecl *MD,
1114 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001115 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001116 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001117
1118 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001119 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001120 // Suppress the final autorelease in ARC.
1121 AutoreleaseResult = false;
1122
Chris Lattner5f9e2722011-07-23 10:55:15 +00001123 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001124 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1125 E = IMP->init_end(); B != E; ++B) {
1126 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001127 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001128 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001129 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1130 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001131 EmitAggExpr(IvarInit->getInit(),
1132 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001133 AggValueSlot::DoesNotNeedGCBarriers,
1134 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001135 }
1136 // constructor returns 'self'.
1137 CodeGenTypes &Types = CGM.getTypes();
1138 QualType IdTy(CGM.getContext().getObjCIdType());
1139 llvm::Value *SelfAsId =
1140 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1141 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001142
1143 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001144 } else {
John McCalle81ac692011-03-22 07:05:39 +00001145 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001146 }
1147 FinishFunction();
1148}
1149
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001150bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1151 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1152 it++; it++;
1153 const ABIArgInfo &AI = it->info;
1154 // FIXME. Is this sufficient check?
1155 return (AI.getKind() == ABIArgInfo::Indirect);
1156}
1157
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001158bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
Douglas Gregore289d812011-09-13 17:21:33 +00001159 if (CGM.getLangOptions().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001160 return false;
1161 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1162 return FDTTy->getDecl()->hasObjectMember();
1163 return false;
1164}
1165
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001166llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001167 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1168 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001169}
1170
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001171QualType CodeGenFunction::TypeOfSelfObject() {
1172 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1173 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001174 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1175 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001176 return PTy->getPointeeType();
1177}
1178
Chris Lattner74391b42009-03-22 21:03:39 +00001179void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001180 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001181 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001183 if (!EnumerationMutationFn) {
1184 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1185 return;
1186 }
1187
Devang Patelbcbd03a2011-01-19 01:36:36 +00001188 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001189 if (DI)
1190 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001191
Devang Patel9d99f2d2011-06-13 23:15:32 +00001192 // The local variable comes into scope immediately.
1193 AutoVarEmission variable = AutoVarEmission::invalid();
1194 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1195 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1196
John McCalld88687f2011-01-07 01:49:06 +00001197 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Anders Carlssonf484c312008-08-31 02:33:12 +00001199 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001200 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001201 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001202 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Anders Carlssonf484c312008-08-31 02:33:12 +00001204 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001205 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001206
John McCalld88687f2011-01-07 01:49:06 +00001207 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001208 IdentifierInfo *II[] = {
1209 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1210 &CGM.getContext().Idents.get("objects"),
1211 &CGM.getContext().Idents.get("count")
1212 };
1213 Selector FastEnumSel =
1214 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001215
1216 QualType ItemsTy =
1217 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001218 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001219 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001220 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001221
John McCall990567c2011-07-27 01:07:15 +00001222 // Emit the collection pointer. In ARC, we do a retain.
1223 llvm::Value *Collection;
1224 if (getLangOptions().ObjCAutoRefCount) {
1225 Collection = EmitARCRetainScalarExpr(S.getCollection());
1226
1227 // Enter a cleanup to do the release.
1228 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1229 } else {
1230 Collection = EmitScalarExpr(S.getCollection());
1231 }
Mike Stump1eb44332009-09-09 15:08:12 +00001232
John McCall4b302d32011-08-05 00:14:38 +00001233 // The 'continue' label needs to appear within the cleanup for the
1234 // collection object.
1235 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1236
John McCalld88687f2011-01-07 01:49:06 +00001237 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001238 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001239
1240 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001241 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCalld88687f2011-01-07 01:49:06 +00001243 // The second argument is a temporary array with space for NumItems
1244 // pointers. We'll actually be loading elements from the array
1245 // pointer written into the control state; this buffer is so that
1246 // collections that *aren't* backed by arrays can still queue up
1247 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001248 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001249
John McCalld88687f2011-01-07 01:49:06 +00001250 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001251 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001252 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001253 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001254
John McCalld88687f2011-01-07 01:49:06 +00001255 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001256 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001257 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001258 getContext().UnsignedLongTy,
1259 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001260 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001261
John McCalld88687f2011-01-07 01:49:06 +00001262 // The initial number of objects that were returned in the buffer.
1263 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001264
John McCalld88687f2011-01-07 01:49:06 +00001265 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1266 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001267
John McCalld88687f2011-01-07 01:49:06 +00001268 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001269
John McCalld88687f2011-01-07 01:49:06 +00001270 // If the limit pointer was zero to begin with, the collection is
1271 // empty; skip all this.
1272 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1273 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001274
John McCalld88687f2011-01-07 01:49:06 +00001275 // Otherwise, initialize the loop.
1276 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
John McCalld88687f2011-01-07 01:49:06 +00001278 // Save the initial mutations value. This is the value at an
1279 // address that was written into the state object by
1280 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001281 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001282 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001283 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001284 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001285
John McCalld88687f2011-01-07 01:49:06 +00001286 llvm::Value *initialMutations =
1287 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001288
John McCalld88687f2011-01-07 01:49:06 +00001289 // Start looping. This is the point we return to whenever we have a
1290 // fresh, non-empty batch of objects.
1291 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1292 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001293
John McCalld88687f2011-01-07 01:49:06 +00001294 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001295 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001296 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001297
John McCalld88687f2011-01-07 01:49:06 +00001298 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001299 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001300 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001301
John McCalld88687f2011-01-07 01:49:06 +00001302 // Check whether the mutations value has changed from where it was
1303 // at start. StateMutationsPtr should actually be invariant between
1304 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001305 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001306 llvm::Value *currentMutations
1307 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001308
John McCalld88687f2011-01-07 01:49:06 +00001309 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001310 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001311
John McCalld88687f2011-01-07 01:49:06 +00001312 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1313 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
John McCalld88687f2011-01-07 01:49:06 +00001315 // If so, call the enumeration-mutation function.
1316 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001317 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001318 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001319 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001320 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001321 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001322 // FIXME: We shouldn't need to get the function info here, the runtime already
1323 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001324 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001325 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001326 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001327
John McCalld88687f2011-01-07 01:49:06 +00001328 // Otherwise, or if the mutation function returns, just continue.
1329 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
John McCalld88687f2011-01-07 01:49:06 +00001331 // Initialize the element variable.
1332 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001333 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001334 LValue elementLValue;
1335 QualType elementType;
1336 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001337 // Initialize the variable, in case it's a __block variable or something.
1338 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001339
John McCall57b3b6a2011-02-22 07:16:58 +00001340 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001341 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1342 VK_LValue, SourceLocation());
1343 elementLValue = EmitLValue(&tempDRE);
1344 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001345 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001346
1347 if (D->isARCPseudoStrong())
1348 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001349 } else {
1350 elementLValue = LValue(); // suppress warning
1351 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001352 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001353 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001354 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001355
1356 // Fetch the buffer out of the enumeration state.
1357 // TODO: this pointer should actually be invariant between
1358 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001359 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001360 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001361 llvm::Value *EnumStateItems =
1362 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001363
John McCalld88687f2011-01-07 01:49:06 +00001364 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001365 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001366 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1367 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001368
John McCalld88687f2011-01-07 01:49:06 +00001369 // Cast that value to the right type.
1370 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1371 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001372
John McCalld88687f2011-01-07 01:49:06 +00001373 // Make sure we have an l-value. Yes, this gets evaluated every
1374 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001375 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001376 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001377 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001378 } else {
1379 EmitScalarInit(CurrentItem, elementLValue);
1380 }
Mike Stump1eb44332009-09-09 15:08:12 +00001381
John McCall57b3b6a2011-02-22 07:16:58 +00001382 // If we do have an element variable, this assignment is the end of
1383 // its initialization.
1384 if (elementIsVariable)
1385 EmitAutoVarCleanups(variable);
1386
John McCalld88687f2011-01-07 01:49:06 +00001387 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001388 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001389 {
1390 RunCleanupsScope Scope(*this);
1391 EmitStmt(S.getBody());
1392 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001393 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001394
John McCalld88687f2011-01-07 01:49:06 +00001395 // Destroy the element variable now.
1396 elementVariableScope.ForceCleanup();
1397
1398 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001399 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001400
John McCalld88687f2011-01-07 01:49:06 +00001401 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001402
John McCalld88687f2011-01-07 01:49:06 +00001403 // First we check in the local buffer.
1404 llvm::Value *indexPlusOne
1405 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001406
John McCalld88687f2011-01-07 01:49:06 +00001407 // If we haven't overrun the buffer yet, we can continue.
1408 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1409 LoopBodyBB, FetchMoreBB);
1410
1411 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1412 count->addIncoming(count, AfterBody.getBlock());
1413
1414 // Otherwise, we have to fetch more elements.
1415 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001416
1417 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001418 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001419 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001420 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001421 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001422
John McCalld88687f2011-01-07 01:49:06 +00001423 // If we got a zero count, we're done.
1424 llvm::Value *refetchCount = CountRV.getScalarVal();
1425
1426 // (note that the message send might split FetchMoreBB)
1427 index->addIncoming(zero, Builder.GetInsertBlock());
1428 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1429
1430 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1431 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Anders Carlssonf484c312008-08-31 02:33:12 +00001433 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001434 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001435
John McCall57b3b6a2011-02-22 07:16:58 +00001436 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001437 // If the element was not a declaration, set it to be null.
1438
John McCalld88687f2011-01-07 01:49:06 +00001439 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1440 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001441 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001442 }
1443
Eric Christopher73fb3502011-10-13 21:45:18 +00001444 if (DI)
1445 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001446
John McCall990567c2011-07-27 01:07:15 +00001447 // Leave the cleanup we entered in ARC.
1448 if (getLangOptions().ObjCAutoRefCount)
1449 PopCleanupBlock();
1450
John McCallff8e1152010-07-23 21:56:41 +00001451 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001452}
1453
Mike Stump1eb44332009-09-09 15:08:12 +00001454void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001455 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001456}
1457
Mike Stump1eb44332009-09-09 15:08:12 +00001458void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001459 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1460}
1461
Chris Lattner10cac6f2008-11-15 21:26:17 +00001462void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001463 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001464 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001465}
1466
John McCall33e56f32011-09-10 06:18:15 +00001467/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001468/// primitive retain.
1469llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1470 llvm::Value *value) {
1471 return EmitARCRetain(type, value);
1472}
1473
1474namespace {
1475 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001476 CallObjCRelease(llvm::Value *object) : object(object) {}
1477 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001478
John McCallad346f42011-07-12 20:27:29 +00001479 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001480 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001481 }
1482 };
1483}
1484
John McCall33e56f32011-09-10 06:18:15 +00001485/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001486/// release at the end of the full-expression.
1487llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1488 llvm::Value *object) {
1489 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001490 // conditional.
1491 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001492 return object;
1493}
1494
1495llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1496 llvm::Value *value) {
1497 return EmitARCRetainAutorelease(type, value);
1498}
1499
1500
1501static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001502 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001503 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001504 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1505
1506 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1507 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001508 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001509 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1510 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1511
1512 return fn;
1513}
1514
1515/// Perform an operation having the signature
1516/// i8* (i8*)
1517/// where a null input causes a no-op and returns null.
1518static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1519 llvm::Value *value,
1520 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001521 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001522 if (isa<llvm::ConstantPointerNull>(value)) return value;
1523
1524 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001525 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001526 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001527 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1528 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1529 }
1530
1531 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001532 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001533 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1534
1535 // Call the function.
1536 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1537 call->setDoesNotThrow();
1538
1539 // Cast the result back to the original type.
1540 return CGF.Builder.CreateBitCast(call, origType);
1541}
1542
1543/// Perform an operation having the following signature:
1544/// i8* (i8**)
1545static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1546 llvm::Value *addr,
1547 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001548 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001549 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001550 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001551 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001552 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1553 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1554 }
1555
1556 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001557 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001558 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1559
1560 // Call the function.
1561 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1562 call->setDoesNotThrow();
1563
1564 // Cast the result back to a dereference of the original type.
1565 llvm::Value *result = call;
1566 if (origType != CGF.Int8PtrPtrTy)
1567 result = CGF.Builder.CreateBitCast(result,
1568 cast<llvm::PointerType>(origType)->getElementType());
1569
1570 return result;
1571}
1572
1573/// Perform an operation having the following signature:
1574/// i8* (i8**, i8*)
1575static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1576 llvm::Value *addr,
1577 llvm::Value *value,
1578 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001579 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001580 bool ignored) {
1581 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1582 == value->getType());
1583
1584 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001585 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001586
Chris Lattner2acc6e32011-07-18 04:24:23 +00001587 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001588 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1589 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1590 }
1591
Chris Lattner2acc6e32011-07-18 04:24:23 +00001592 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001593
1594 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1595 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1596
1597 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1598 result->setDoesNotThrow();
1599
1600 if (ignored) return 0;
1601
1602 return CGF.Builder.CreateBitCast(result, origType);
1603}
1604
1605/// Perform an operation having the following signature:
1606/// void (i8**, i8**)
1607static void emitARCCopyOperation(CodeGenFunction &CGF,
1608 llvm::Value *dst,
1609 llvm::Value *src,
1610 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001611 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001612 assert(dst->getType() == src->getType());
1613
1614 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001615 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001616 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001617 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1618 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1619 }
1620
1621 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1622 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1623
1624 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1625 result->setDoesNotThrow();
1626}
1627
1628/// Produce the code to do a retain. Based on the type, calls one of:
1629/// call i8* @objc_retain(i8* %value)
1630/// call i8* @objc_retainBlock(i8* %value)
1631llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1632 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001633 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001634 else
1635 return EmitARCRetainNonBlock(value);
1636}
1637
1638/// Retain the given object, with normal retain semantics.
1639/// call i8* @objc_retain(i8* %value)
1640llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1641 return emitARCValueOperation(*this, value,
1642 CGM.getARCEntrypoints().objc_retain,
1643 "objc_retain");
1644}
1645
1646/// Retain the given block, with _Block_copy semantics.
1647/// call i8* @objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001648///
1649/// \param mandatory - If false, emit the call with metadata
1650/// indicating that it's okay for the optimizer to eliminate this call
1651/// if it can prove that the block never escapes except down the stack.
1652llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1653 bool mandatory) {
1654 llvm::Value *result
1655 = emitARCValueOperation(*this, value,
1656 CGM.getARCEntrypoints().objc_retainBlock,
1657 "objc_retainBlock");
1658
1659 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1660 // tell the optimizer that it doesn't need to do this copy if the
1661 // block doesn't escape, where being passed as an argument doesn't
1662 // count as escaping.
1663 if (!mandatory && isa<llvm::Instruction>(result)) {
1664 llvm::CallInst *call
1665 = cast<llvm::CallInst>(result->stripPointerCasts());
1666 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1667
1668 SmallVector<llvm::Value*,1> args;
1669 call->setMetadata("clang.arc.copy_on_escape",
1670 llvm::MDNode::get(Builder.getContext(), args));
1671 }
1672
1673 return result;
John McCallf85e1932011-06-15 23:02:42 +00001674}
1675
1676/// Retain the given object which is the result of a function call.
1677/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1678///
1679/// Yes, this function name is one character away from a different
1680/// call with completely different semantics.
1681llvm::Value *
1682CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1683 // Fetch the void(void) inline asm which marks that we're going to
1684 // retain the autoreleased return value.
1685 llvm::InlineAsm *&marker
1686 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1687 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001688 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001689 = CGM.getTargetCodeGenInfo()
1690 .getARCRetainAutoreleasedReturnValueMarker();
1691
1692 // If we have an empty assembly string, there's nothing to do.
1693 if (assembly.empty()) {
1694
1695 // Otherwise, at -O0, build an inline asm that we're going to call
1696 // in a moment.
1697 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1698 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001699 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001700
1701 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1702
1703 // If we're at -O1 and above, we don't want to litter the code
1704 // with this marker yet, so leave a breadcrumb for the ARC
1705 // optimizer to pick up.
1706 } else {
1707 llvm::NamedMDNode *metadata =
1708 CGM.getModule().getOrInsertNamedMetadata(
1709 "clang.arc.retainAutoreleasedReturnValueMarker");
1710 assert(metadata->getNumOperands() <= 1);
1711 if (metadata->getNumOperands() == 0) {
1712 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001713 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001714 }
1715 }
1716 }
1717
1718 // Call the marker asm if we made one, which we do only at -O0.
1719 if (marker) Builder.CreateCall(marker);
1720
1721 return emitARCValueOperation(*this, value,
1722 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1723 "objc_retainAutoreleasedReturnValue");
1724}
1725
1726/// Release the given object.
1727/// call void @objc_release(i8* %value)
1728void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1729 if (isa<llvm::ConstantPointerNull>(value)) return;
1730
1731 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1732 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001733 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001734 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001735 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1736 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1737 }
1738
1739 // Cast the argument to 'id'.
1740 value = Builder.CreateBitCast(value, Int8PtrTy);
1741
1742 // Call objc_release.
1743 llvm::CallInst *call = Builder.CreateCall(fn, value);
1744 call->setDoesNotThrow();
1745
1746 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001747 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001748 call->setMetadata("clang.imprecise_release",
1749 llvm::MDNode::get(Builder.getContext(), args));
1750 }
1751}
1752
1753/// Store into a strong object. Always calls this:
1754/// call void @objc_storeStrong(i8** %addr, i8* %value)
1755llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1756 llvm::Value *value,
1757 bool ignored) {
1758 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1759 == value->getType());
1760
1761 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1762 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001763 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001764 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001765 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1766 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1767 }
1768
1769 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1770 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1771
1772 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1773
1774 if (ignored) return 0;
1775 return value;
1776}
1777
1778/// Store into a strong object. Sometimes calls this:
1779/// call void @objc_storeStrong(i8** %addr, i8* %value)
1780/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001781llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001782 llvm::Value *newValue,
1783 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001784 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001785 bool isBlock = type->isBlockPointerType();
1786
1787 // Use a store barrier at -O0 unless this is a block type or the
1788 // lvalue is inadequately aligned.
1789 if (shouldUseFusedARCCalls() &&
1790 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00001791 (dst.getAlignment().isZero() ||
1792 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00001793 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1794 }
1795
1796 // Otherwise, split it out.
1797
1798 // Retain the new value.
1799 newValue = EmitARCRetain(type, newValue);
1800
1801 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001802 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001803
1804 // Store. We do this before the release so that any deallocs won't
1805 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001806 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001807
1808 // Finally, release the old value.
1809 EmitARCRelease(oldValue, /*precise*/ false);
1810
1811 return newValue;
1812}
1813
1814/// Autorelease the given object.
1815/// call i8* @objc_autorelease(i8* %value)
1816llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1817 return emitARCValueOperation(*this, value,
1818 CGM.getARCEntrypoints().objc_autorelease,
1819 "objc_autorelease");
1820}
1821
1822/// Autorelease the given object.
1823/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1824llvm::Value *
1825CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1826 return emitARCValueOperation(*this, value,
1827 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1828 "objc_autoreleaseReturnValue");
1829}
1830
1831/// Do a fused retain/autorelease of the given object.
1832/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1833llvm::Value *
1834CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1835 return emitARCValueOperation(*this, value,
1836 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1837 "objc_retainAutoreleaseReturnValue");
1838}
1839
1840/// Do a fused retain/autorelease of the given object.
1841/// call i8* @objc_retainAutorelease(i8* %value)
1842/// or
1843/// %retain = call i8* @objc_retainBlock(i8* %value)
1844/// call i8* @objc_autorelease(i8* %retain)
1845llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1846 llvm::Value *value) {
1847 if (!type->isBlockPointerType())
1848 return EmitARCRetainAutoreleaseNonBlock(value);
1849
1850 if (isa<llvm::ConstantPointerNull>(value)) return value;
1851
Chris Lattner2acc6e32011-07-18 04:24:23 +00001852 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001853 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00001854 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001855 value = EmitARCAutorelease(value);
1856 return Builder.CreateBitCast(value, origType);
1857}
1858
1859/// Do a fused retain/autorelease of the given object.
1860/// call i8* @objc_retainAutorelease(i8* %value)
1861llvm::Value *
1862CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1863 return emitARCValueOperation(*this, value,
1864 CGM.getARCEntrypoints().objc_retainAutorelease,
1865 "objc_retainAutorelease");
1866}
1867
1868/// i8* @objc_loadWeak(i8** %addr)
1869/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1870llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1871 return emitARCLoadOperation(*this, addr,
1872 CGM.getARCEntrypoints().objc_loadWeak,
1873 "objc_loadWeak");
1874}
1875
1876/// i8* @objc_loadWeakRetained(i8** %addr)
1877llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1878 return emitARCLoadOperation(*this, addr,
1879 CGM.getARCEntrypoints().objc_loadWeakRetained,
1880 "objc_loadWeakRetained");
1881}
1882
1883/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1884/// Returns %value.
1885llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1886 llvm::Value *value,
1887 bool ignored) {
1888 return emitARCStoreOperation(*this, addr, value,
1889 CGM.getARCEntrypoints().objc_storeWeak,
1890 "objc_storeWeak", ignored);
1891}
1892
1893/// i8* @objc_initWeak(i8** %addr, i8* %value)
1894/// Returns %value. %addr is known to not have a current weak entry.
1895/// Essentially equivalent to:
1896/// *addr = nil; objc_storeWeak(addr, value);
1897void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1898 // If we're initializing to null, just write null to memory; no need
1899 // to get the runtime involved. But don't do this if optimization
1900 // is enabled, because accounting for this would make the optimizer
1901 // much more complicated.
1902 if (isa<llvm::ConstantPointerNull>(value) &&
1903 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1904 Builder.CreateStore(value, addr);
1905 return;
1906 }
1907
1908 emitARCStoreOperation(*this, addr, value,
1909 CGM.getARCEntrypoints().objc_initWeak,
1910 "objc_initWeak", /*ignored*/ true);
1911}
1912
1913/// void @objc_destroyWeak(i8** %addr)
1914/// Essentially objc_storeWeak(addr, nil).
1915void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1916 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1917 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001918 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001919 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001920 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1921 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1922 }
1923
1924 // Cast the argument to 'id*'.
1925 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1926
1927 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1928 call->setDoesNotThrow();
1929}
1930
1931/// void @objc_moveWeak(i8** %dest, i8** %src)
1932/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1933/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1934void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1935 emitARCCopyOperation(*this, dst, src,
1936 CGM.getARCEntrypoints().objc_moveWeak,
1937 "objc_moveWeak");
1938}
1939
1940/// void @objc_copyWeak(i8** %dest, i8** %src)
1941/// Disregards the current value in %dest. Essentially
1942/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1943void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1944 emitARCCopyOperation(*this, dst, src,
1945 CGM.getARCEntrypoints().objc_copyWeak,
1946 "objc_copyWeak");
1947}
1948
1949/// Produce the code to do a objc_autoreleasepool_push.
1950/// call i8* @objc_autoreleasePoolPush(void)
1951llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1952 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1953 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001954 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001955 llvm::FunctionType::get(Int8PtrTy, false);
1956 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1957 }
1958
1959 llvm::CallInst *call = Builder.CreateCall(fn);
1960 call->setDoesNotThrow();
1961
1962 return call;
1963}
1964
1965/// Produce the code to do a primitive release.
1966/// call void @objc_autoreleasePoolPop(i8* %ptr)
1967void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1968 assert(value->getType() == Int8PtrTy);
1969
1970 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1971 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001972 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001973 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001974 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1975
1976 // We don't want to use a weak import here; instead we should not
1977 // fall into this path.
1978 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1979 }
1980
1981 llvm::CallInst *call = Builder.CreateCall(fn, value);
1982 call->setDoesNotThrow();
1983}
1984
1985/// Produce the code to do an MRR version objc_autoreleasepool_push.
1986/// Which is: [[NSAutoreleasePool alloc] init];
1987/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1988/// init is declared as: - (id) init; in its NSObject super class.
1989///
1990llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1991 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1992 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1993 // [NSAutoreleasePool alloc]
1994 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1995 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1996 CallArgList Args;
1997 RValue AllocRV =
1998 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1999 getContext().getObjCIdType(),
2000 AllocSel, Receiver, Args);
2001
2002 // [Receiver init]
2003 Receiver = AllocRV.getScalarVal();
2004 II = &CGM.getContext().Idents.get("init");
2005 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2006 RValue InitRV =
2007 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2008 getContext().getObjCIdType(),
2009 InitSel, Receiver, Args);
2010 return InitRV.getScalarVal();
2011}
2012
2013/// Produce the code to do a primitive release.
2014/// [tmp drain];
2015void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2016 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2017 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2018 CallArgList Args;
2019 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2020 getContext().VoidTy, DrainSel, Arg, Args);
2021}
2022
John McCallbdc4d802011-07-09 01:37:26 +00002023void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2024 llvm::Value *addr,
2025 QualType type) {
2026 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2027 CGF.EmitARCRelease(ptr, /*precise*/ true);
2028}
2029
2030void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2031 llvm::Value *addr,
2032 QualType type) {
2033 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2034 CGF.EmitARCRelease(ptr, /*precise*/ false);
2035}
2036
2037void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2038 llvm::Value *addr,
2039 QualType type) {
2040 CGF.EmitARCDestroyWeak(addr);
2041}
2042
John McCallf85e1932011-06-15 23:02:42 +00002043namespace {
John McCallf85e1932011-06-15 23:02:42 +00002044 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2045 llvm::Value *Token;
2046
2047 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2048
John McCallad346f42011-07-12 20:27:29 +00002049 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002050 CGF.EmitObjCAutoreleasePoolPop(Token);
2051 }
2052 };
2053 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2054 llvm::Value *Token;
2055
2056 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2057
John McCallad346f42011-07-12 20:27:29 +00002058 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002059 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2060 }
2061 };
2062}
2063
2064void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2065 if (CGM.getLangOptions().ObjCAutoRefCount)
2066 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2067 else
2068 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2069}
2070
John McCallf85e1932011-06-15 23:02:42 +00002071static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2072 LValue lvalue,
2073 QualType type) {
2074 switch (type.getObjCLifetime()) {
2075 case Qualifiers::OCL_None:
2076 case Qualifiers::OCL_ExplicitNone:
2077 case Qualifiers::OCL_Strong:
2078 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002079 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002080 false);
2081
2082 case Qualifiers::OCL_Weak:
2083 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2084 true);
2085 }
2086
2087 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002088}
2089
2090static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2091 const Expr *e) {
2092 e = e->IgnoreParens();
2093 QualType type = e->getType();
2094
John McCall21480112011-08-30 00:57:29 +00002095 // If we're loading retained from a __strong xvalue, we can avoid
2096 // an extra retain/release pair by zeroing out the source of this
2097 // "move" operation.
2098 if (e->isXValue() &&
2099 !type.isConstQualified() &&
2100 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2101 // Emit the lvalue.
2102 LValue lv = CGF.EmitLValue(e);
2103
2104 // Load the object pointer.
2105 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2106
2107 // Set the source pointer to NULL.
2108 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2109
2110 return TryEmitResult(result, true);
2111 }
2112
John McCallf85e1932011-06-15 23:02:42 +00002113 // As a very special optimization, in ARC++, if the l-value is the
2114 // result of a non-volatile assignment, do a simple retain of the
2115 // result of the call to objc_storeWeak instead of reloading.
2116 if (CGF.getLangOptions().CPlusPlus &&
2117 !type.isVolatileQualified() &&
2118 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2119 isa<BinaryOperator>(e) &&
2120 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2121 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2122
2123 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2124}
2125
2126static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2127 llvm::Value *value);
2128
2129/// Given that the given expression is some sort of call (which does
2130/// not return retained), emit a retain following it.
2131static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2132 llvm::Value *value = CGF.EmitScalarExpr(e);
2133 return emitARCRetainAfterCall(CGF, value);
2134}
2135
2136static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2137 llvm::Value *value) {
2138 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2139 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2140
2141 // Place the retain immediately following the call.
2142 CGF.Builder.SetInsertPoint(call->getParent(),
2143 ++llvm::BasicBlock::iterator(call));
2144 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2145
2146 CGF.Builder.restoreIP(ip);
2147 return value;
2148 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2149 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2150
2151 // Place the retain at the beginning of the normal destination block.
2152 llvm::BasicBlock *BB = invoke->getNormalDest();
2153 CGF.Builder.SetInsertPoint(BB, BB->begin());
2154 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2155
2156 CGF.Builder.restoreIP(ip);
2157 return value;
2158
2159 // Bitcasts can arise because of related-result returns. Rewrite
2160 // the operand.
2161 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2162 llvm::Value *operand = bitcast->getOperand(0);
2163 operand = emitARCRetainAfterCall(CGF, operand);
2164 bitcast->setOperand(0, operand);
2165 return bitcast;
2166
2167 // Generic fall-back case.
2168 } else {
2169 // Retain using the non-block variant: we never need to do a copy
2170 // of a block that's been returned to us.
2171 return CGF.EmitARCRetainNonBlock(value);
2172 }
2173}
2174
John McCalldc05b112011-09-10 01:16:55 +00002175/// Determine whether it might be important to emit a separate
2176/// objc_retain_block on the result of the given expression, or
2177/// whether it's okay to just emit it in a +1 context.
2178static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2179 assert(e->getType()->isBlockPointerType());
2180 e = e->IgnoreParens();
2181
2182 // For future goodness, emit block expressions directly in +1
2183 // contexts if we can.
2184 if (isa<BlockExpr>(e))
2185 return false;
2186
2187 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2188 switch (cast->getCastKind()) {
2189 // Emitting these operations in +1 contexts is goodness.
2190 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002191 case CK_ARCReclaimReturnedObject:
2192 case CK_ARCConsumeObject:
2193 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002194 return false;
2195
2196 // These operations preserve a block type.
2197 case CK_NoOp:
2198 case CK_BitCast:
2199 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2200
2201 // These operations are known to be bad (or haven't been considered).
2202 case CK_AnyPointerToBlockPointerCast:
2203 default:
2204 return true;
2205 }
2206 }
2207
2208 return true;
2209}
2210
John McCall4b9c2d22011-11-06 09:01:30 +00002211/// Try to emit a PseudoObjectExpr at +1.
2212///
2213/// This massively duplicates emitPseudoObjectRValue.
2214static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2215 const PseudoObjectExpr *E) {
2216 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2217
2218 // Find the result expression.
2219 const Expr *resultExpr = E->getResultExpr();
2220 assert(resultExpr);
2221 TryEmitResult result;
2222
2223 for (PseudoObjectExpr::const_semantics_iterator
2224 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2225 const Expr *semantic = *i;
2226
2227 // If this semantic expression is an opaque value, bind it
2228 // to the result of its source expression.
2229 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2230 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2231 OVMA opaqueData;
2232
2233 // If this semantic is the result of the pseudo-object
2234 // expression, try to evaluate the source as +1.
2235 if (ov == resultExpr) {
2236 assert(!OVMA::shouldBindAsLValue(ov));
2237 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2238 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2239
2240 // Otherwise, just bind it.
2241 } else {
2242 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2243 }
2244 opaques.push_back(opaqueData);
2245
2246 // Otherwise, if the expression is the result, evaluate it
2247 // and remember the result.
2248 } else if (semantic == resultExpr) {
2249 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2250
2251 // Otherwise, evaluate the expression in an ignored context.
2252 } else {
2253 CGF.EmitIgnoredExpr(semantic);
2254 }
2255 }
2256
2257 // Unbind all the opaques now.
2258 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2259 opaques[i].unbind(CGF);
2260
2261 return result;
2262}
2263
John McCallf85e1932011-06-15 23:02:42 +00002264static TryEmitResult
2265tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002266 // Look through cleanups.
2267 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall1a343eb2011-11-10 08:15:53 +00002268 CGF.enterFullExpression(cleanups);
John McCall990567c2011-07-27 01:07:15 +00002269 CodeGenFunction::RunCleanupsScope scope(CGF);
2270 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2271 }
2272
John McCallf85e1932011-06-15 23:02:42 +00002273 // The desired result type, if it differs from the type of the
2274 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002275 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002276
2277 while (true) {
2278 e = e->IgnoreParens();
2279
2280 // There's a break at the end of this if-chain; anything
2281 // that wants to keep looping has to explicitly continue.
2282 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2283 switch (ce->getCastKind()) {
2284 // No-op casts don't change the type, so we just ignore them.
2285 case CK_NoOp:
2286 e = ce->getSubExpr();
2287 continue;
2288
2289 case CK_LValueToRValue: {
2290 TryEmitResult loadResult
2291 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2292 if (resultType) {
2293 llvm::Value *value = loadResult.getPointer();
2294 value = CGF.Builder.CreateBitCast(value, resultType);
2295 loadResult.setPointer(value);
2296 }
2297 return loadResult;
2298 }
2299
2300 // These casts can change the type, so remember that and
2301 // soldier on. We only need to remember the outermost such
2302 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002303 case CK_CPointerToObjCPointerCast:
2304 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002305 case CK_AnyPointerToBlockPointerCast:
2306 case CK_BitCast:
2307 if (!resultType)
2308 resultType = CGF.ConvertType(ce->getType());
2309 e = ce->getSubExpr();
2310 assert(e->getType()->hasPointerRepresentation());
2311 continue;
2312
2313 // For consumptions, just emit the subexpression and thus elide
2314 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002315 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002316 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2317 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2318 return TryEmitResult(result, true);
2319 }
2320
John McCalldc05b112011-09-10 01:16:55 +00002321 // Block extends are net +0. Naively, we could just recurse on
2322 // the subexpression, but actually we need to ensure that the
2323 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002324 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002325 llvm::Value *result; // will be a +0 value
2326
2327 // If we can't safely assume the sub-expression will produce a
2328 // block-copied value, emit the sub-expression at +0.
2329 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2330 result = CGF.EmitScalarExpr(ce->getSubExpr());
2331
2332 // Otherwise, try to emit the sub-expression at +1 recursively.
2333 } else {
2334 TryEmitResult subresult
2335 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2336 result = subresult.getPointer();
2337
2338 // If that produced a retained value, just use that,
2339 // possibly casting down.
2340 if (subresult.getInt()) {
2341 if (resultType)
2342 result = CGF.Builder.CreateBitCast(result, resultType);
2343 return TryEmitResult(result, true);
2344 }
2345
2346 // Otherwise it's +0.
2347 }
2348
2349 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002350 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002351 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2352 return TryEmitResult(result, true);
2353 }
2354
John McCall7e5e5f42011-07-07 06:58:02 +00002355 // For reclaims, emit the subexpression as a retained call and
2356 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002357 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002358 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2359 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2360 return TryEmitResult(result, true);
2361 }
2362
John McCallf85e1932011-06-15 23:02:42 +00002363 default:
2364 break;
2365 }
2366
2367 // Skip __extension__.
2368 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2369 if (op->getOpcode() == UO_Extension) {
2370 e = op->getSubExpr();
2371 continue;
2372 }
2373
2374 // For calls and message sends, use the retained-call logic.
2375 // Delegate inits are a special case in that they're the only
2376 // returns-retained expression that *isn't* surrounded by
2377 // a consume.
2378 } else if (isa<CallExpr>(e) ||
2379 (isa<ObjCMessageExpr>(e) &&
2380 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2381 llvm::Value *result = emitARCRetainCall(CGF, e);
2382 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2383 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002384
2385 // Look through pseudo-object expressions.
2386 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2387 TryEmitResult result
2388 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2389 if (resultType) {
2390 llvm::Value *value = result.getPointer();
2391 value = CGF.Builder.CreateBitCast(value, resultType);
2392 result.setPointer(value);
2393 }
2394 return result;
John McCallf85e1932011-06-15 23:02:42 +00002395 }
2396
2397 // Conservatively halt the search at any other expression kind.
2398 break;
2399 }
2400
2401 // We didn't find an obvious production, so emit what we've got and
2402 // tell the caller that we didn't manage to retain.
2403 llvm::Value *result = CGF.EmitScalarExpr(e);
2404 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2405 return TryEmitResult(result, false);
2406}
2407
2408static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2409 LValue lvalue,
2410 QualType type) {
2411 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2412 llvm::Value *value = result.getPointer();
2413 if (!result.getInt())
2414 value = CGF.EmitARCRetain(type, value);
2415 return value;
2416}
2417
2418/// EmitARCRetainScalarExpr - Semantically equivalent to
2419/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2420/// best-effort attempt to peephole expressions that naturally produce
2421/// retained objects.
2422llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2423 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2424 llvm::Value *value = result.getPointer();
2425 if (!result.getInt())
2426 value = EmitARCRetain(e->getType(), value);
2427 return value;
2428}
2429
2430llvm::Value *
2431CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2432 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2433 llvm::Value *value = result.getPointer();
2434 if (result.getInt())
2435 value = EmitARCAutorelease(value);
2436 else
2437 value = EmitARCRetainAutorelease(e->getType(), value);
2438 return value;
2439}
2440
John McCall348f16f2011-10-04 06:23:45 +00002441llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2442 llvm::Value *result;
2443 bool doRetain;
2444
2445 if (shouldEmitSeparateBlockRetain(e)) {
2446 result = EmitScalarExpr(e);
2447 doRetain = true;
2448 } else {
2449 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2450 result = subresult.getPointer();
2451 doRetain = !subresult.getInt();
2452 }
2453
2454 if (doRetain)
2455 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2456 return EmitObjCConsumeObject(e->getType(), result);
2457}
2458
John McCall2b014d62011-10-01 10:32:24 +00002459llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2460 // In ARC, retain and autorelease the expression.
2461 if (getLangOptions().ObjCAutoRefCount) {
2462 // Do so before running any cleanups for the full-expression.
2463 // tryEmitARCRetainScalarExpr does make an effort to do things
2464 // inside cleanups, but there are crazy cases like
2465 // @throw A().foo;
2466 // where a full retain+autorelease is required and would
2467 // otherwise happen after the destructor for the temporary.
John McCall1a343eb2011-11-10 08:15:53 +00002468 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2469 enterFullExpression(ewc);
John McCall2b014d62011-10-01 10:32:24 +00002470 expr = ewc->getSubExpr();
John McCall1a343eb2011-11-10 08:15:53 +00002471 }
John McCall2b014d62011-10-01 10:32:24 +00002472
John McCall1a343eb2011-11-10 08:15:53 +00002473 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall2b014d62011-10-01 10:32:24 +00002474 return EmitARCRetainAutoreleaseScalarExpr(expr);
2475 }
2476
2477 // Otherwise, use the normal scalar-expression emission. The
2478 // exception machinery doesn't do anything special with the
2479 // exception like retaining it, so there's no safety associated with
2480 // only running cleanups after the throw has started, and when it
2481 // matters it tends to be substantially inferior code.
2482 return EmitScalarExpr(expr);
2483}
2484
John McCallf85e1932011-06-15 23:02:42 +00002485std::pair<LValue,llvm::Value*>
2486CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2487 bool ignored) {
2488 // Evaluate the RHS first.
2489 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2490 llvm::Value *value = result.getPointer();
2491
John McCallfb720812011-07-28 07:23:35 +00002492 bool hasImmediateRetain = result.getInt();
2493
2494 // If we didn't emit a retained object, and the l-value is of block
2495 // type, then we need to emit the block-retain immediately in case
2496 // it invalidates the l-value.
2497 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002498 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002499 hasImmediateRetain = true;
2500 }
2501
John McCallf85e1932011-06-15 23:02:42 +00002502 LValue lvalue = EmitLValue(e->getLHS());
2503
2504 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002505 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002506 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002507 EmitLoadOfScalar(lvalue);
2508 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002509 EmitARCRelease(oldValue, /*precise*/ false);
2510 } else {
John McCall545d9962011-06-25 02:11:03 +00002511 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002512 }
2513
2514 return std::pair<LValue,llvm::Value*>(lvalue, value);
2515}
2516
2517std::pair<LValue,llvm::Value*>
2518CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2519 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2520 LValue lvalue = EmitLValue(e->getLHS());
2521
Eli Friedman6da2c712011-12-03 04:14:32 +00002522 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002523
2524 return std::pair<LValue,llvm::Value*>(lvalue, value);
2525}
2526
2527void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2528 const ObjCAutoreleasePoolStmt &ARPS) {
2529 const Stmt *subStmt = ARPS.getSubStmt();
2530 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2531
2532 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002533 if (DI)
2534 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002535
2536 // Keep track of the current cleanup stack depth.
2537 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002538 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002539 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2540 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2541 } else {
2542 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2543 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2544 }
2545
2546 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2547 E = S.body_end(); I != E; ++I)
2548 EmitStmt(*I);
2549
Eric Christopher73fb3502011-10-13 21:45:18 +00002550 if (DI)
2551 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002552}
John McCall0c24c802011-06-24 23:21:27 +00002553
2554/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2555/// make sure it survives garbage collection until this point.
2556void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2557 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002558 llvm::FunctionType *extenderType
Jay Foadda549e82011-07-29 13:56:53 +00002559 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall0c24c802011-06-24 23:21:27 +00002560 llvm::Value *extender
2561 = llvm::InlineAsm::get(extenderType,
2562 /* assembly */ "",
2563 /* constraints */ "r",
2564 /* side effects */ true);
2565
2566 object = Builder.CreateBitCast(object, VoidPtrTy);
2567 Builder.CreateCall(extender, object)->setDoesNotThrow();
2568}
2569
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002570/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002571/// non-trivial copy assignment function, produce following helper function.
2572/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2573///
2574llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002575CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2576 const ObjCPropertyImplDecl *PID) {
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002577 // FIXME. This api is for NeXt runtime only for now.
2578 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002579 return 0;
2580 QualType Ty = PID->getPropertyIvarDecl()->getType();
2581 if (!Ty->isRecordType())
2582 return 0;
2583 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002584 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002585 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002586 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002587 if (hasTrivialSetExpr(PID))
2588 return 0;
2589 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2590 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2591 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002592
2593 ASTContext &C = getContext();
2594 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002595 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002596 FunctionDecl *FD = FunctionDecl::Create(C,
2597 C.getTranslationUnitDecl(),
2598 SourceLocation(),
2599 SourceLocation(), II, C.VoidTy, 0,
2600 SC_Static,
2601 SC_None,
2602 false,
2603 true);
2604
2605 QualType DestTy = C.getPointerType(Ty);
2606 QualType SrcTy = Ty;
2607 SrcTy.addConst();
2608 SrcTy = C.getPointerType(SrcTy);
2609
2610 FunctionArgList args;
2611 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2612 args.push_back(&dstDecl);
2613 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2614 args.push_back(&srcDecl);
2615
2616 const CGFunctionInfo &FI =
2617 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
2618
2619 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
2620
2621 llvm::Function *Fn =
2622 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002623 "__assign_helper_atomic_property_", &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002624
2625 if (CGM.getModuleDebugInfo())
2626 DebugInfo = CGM.getModuleDebugInfo();
2627
2628
2629 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2630
2631 DeclRefExpr *DstExpr =
2632 new (C) DeclRefExpr(&dstDecl, DestTy,
2633 VK_RValue, SourceLocation());
2634
2635 Expr* DST = new (C) UnaryOperator(DstExpr, UO_Deref, DestTy->getPointeeType(),
2636 VK_LValue, OK_Ordinary, SourceLocation());
2637
2638 DeclRefExpr *SrcExpr =
2639 new (C) DeclRefExpr(&srcDecl, SrcTy,
2640 VK_RValue, SourceLocation());
2641
2642 Expr* SRC = new (C) UnaryOperator(SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2643 VK_LValue, OK_Ordinary, SourceLocation());
2644
2645 Expr *Args[2] = { DST, SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002646 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002647 CXXOperatorCallExpr *TheCall =
2648 new (C) CXXOperatorCallExpr(C, OO_Equal, CalleeExp->getCallee(),
2649 Args, 2, DestTy->getPointeeType(),
2650 VK_LValue, SourceLocation());
2651
2652 EmitStmt(TheCall);
2653
2654 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002655 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002656 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002657 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002658}
2659
2660llvm::Constant *
2661CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2662 const ObjCPropertyImplDecl *PID) {
2663 // FIXME. This api is for NeXt runtime only for now.
2664 if (!getLangOptions().CPlusPlus || !getLangOptions().NeXTRuntime)
2665 return 0;
2666 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2667 QualType Ty = PD->getType();
2668 if (!Ty->isRecordType())
2669 return 0;
2670 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2671 return 0;
2672 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002673
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002674 if (hasTrivialGetExpr(PID))
2675 return 0;
2676 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2677 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2678 return HelperFn;
2679
2680
2681 ASTContext &C = getContext();
2682 IdentifierInfo *II
2683 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2684 FunctionDecl *FD = FunctionDecl::Create(C,
2685 C.getTranslationUnitDecl(),
2686 SourceLocation(),
2687 SourceLocation(), II, C.VoidTy, 0,
2688 SC_Static,
2689 SC_None,
2690 false,
2691 true);
2692
2693 QualType DestTy = C.getPointerType(Ty);
2694 QualType SrcTy = Ty;
2695 SrcTy.addConst();
2696 SrcTy = C.getPointerType(SrcTy);
2697
2698 FunctionArgList args;
2699 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2700 args.push_back(&dstDecl);
2701 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2702 args.push_back(&srcDecl);
2703
2704 const CGFunctionInfo &FI =
2705 CGM.getTypes().getFunctionInfo(C.VoidTy, args, FunctionType::ExtInfo());
2706
2707 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI, false);
2708
2709 llvm::Function *Fn =
2710 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2711 "__copy_helper_atomic_property_", &CGM.getModule());
2712
2713 if (CGM.getModuleDebugInfo())
2714 DebugInfo = CGM.getModuleDebugInfo();
2715
2716
2717 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2718
2719 DeclRefExpr *SrcExpr =
2720 new (C) DeclRefExpr(&srcDecl, SrcTy,
2721 VK_RValue, SourceLocation());
2722
2723 Expr* SRC = new (C) UnaryOperator(SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2724 VK_LValue, OK_Ordinary, SourceLocation());
2725
2726 CXXConstructExpr *CXXConstExpr =
2727 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2728
2729 SmallVector<Expr*, 4> ConstructorArgs;
2730 ConstructorArgs.push_back(SRC);
2731 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2732 ++A;
2733
2734 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2735 A != AEnd; ++A)
2736 ConstructorArgs.push_back(*A);
2737
2738 CXXConstructExpr *TheCXXConstructExpr =
2739 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2740 CXXConstExpr->getConstructor(),
2741 CXXConstExpr->isElidable(),
2742 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002743 CXXConstExpr->hadMultipleCandidates(),
2744 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002745 CXXConstExpr->requiresZeroInitialization(),
2746 CXXConstExpr->getConstructionKind(), SourceRange());
2747
2748 DeclRefExpr *DstExpr =
2749 new (C) DeclRefExpr(&dstDecl, DestTy,
2750 VK_RValue, SourceLocation());
2751
2752 RValue DV = EmitAnyExpr(DstExpr);
2753 CharUnits Alignment = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
2754 EmitAggExpr(TheCXXConstructExpr,
2755 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2756 AggValueSlot::IsDestructed,
2757 AggValueSlot::DoesNotNeedGCBarriers,
2758 AggValueSlot::IsNotAliased));
2759
2760 FinishFunction();
2761 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2762 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2763 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002764}
2765
2766
Ted Kremenek2979ec72008-04-09 15:51:31 +00002767CGObjCRuntime::~CGObjCRuntime() {}