blob: 888f67d6618ea5d067a1459b0eba13a0844a3763 [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();
139
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 }
265
John McCalldc7c5ad2011-07-22 08:53:00 +0000266 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
Chris Lattner89951a82009-02-20 18:43:26 +0000316 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
317 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) {
381 return (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64);
382}
383
384/// Return the maximum size that permits atomic accesses for the given
385/// architecture.
386static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
387 llvm::Triple::ArchType arch) {
388 // ARM has 8-byte atomic accesses, but it's not clear whether we
389 // want to rely on them here.
390
391 // In the default case, just assume that any size up to a pointer is
392 // fine given adequate alignment.
393 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
394}
395
396namespace {
397 class PropertyImplStrategy {
398 public:
399 enum StrategyKind {
400 /// The 'native' strategy is to use the architecture's provided
401 /// reads and writes.
402 Native,
403
404 /// Use objc_setProperty and objc_getProperty.
405 GetSetProperty,
406
407 /// Use objc_setProperty for the setter, but use expression
408 /// evaluation for the getter.
409 SetPropertyAndExpressionGet,
410
411 /// Use objc_copyStruct.
412 CopyStruct,
413
414 /// The 'expression' strategy is to emit normal assignment or
415 /// lvalue-to-rvalue expressions.
416 Expression
417 };
418
419 StrategyKind getKind() const { return StrategyKind(Kind); }
420
421 bool hasStrongMember() const { return HasStrong; }
422 bool isAtomic() const { return IsAtomic; }
423 bool isCopy() const { return IsCopy; }
424
425 CharUnits getIvarSize() const { return IvarSize; }
426 CharUnits getIvarAlignment() const { return IvarAlignment; }
427
428 PropertyImplStrategy(CodeGenModule &CGM,
429 const ObjCPropertyImplDecl *propImpl);
430
431 private:
432 unsigned Kind : 8;
433 unsigned IsAtomic : 1;
434 unsigned IsCopy : 1;
435 unsigned HasStrong : 1;
436
437 CharUnits IvarSize;
438 CharUnits IvarAlignment;
439 };
440}
441
442/// Pick an implementation strategy for the the given property synthesis.
443PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
444 const ObjCPropertyImplDecl *propImpl) {
445 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
446 ObjCPropertyDecl::PropertyAttributeKind attrs = prop->getPropertyAttributes();
447
448 IsCopy = (attrs & ObjCPropertyDecl::OBJC_PR_copy);
449 IsAtomic = !(attrs & ObjCPropertyDecl::OBJC_PR_nonatomic);
450 HasStrong = false; // doesn't matter here.
451
452 // Evaluate the ivar's size and alignment.
453 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
454 QualType ivarType = ivar->getType();
455 llvm::tie(IvarSize, IvarAlignment)
456 = CGM.getContext().getTypeInfoInChars(ivarType);
457
458 // If we have a copy property, we always have to use getProperty/setProperty.
459 if (IsCopy) {
460 Kind = GetSetProperty;
461 return;
462 }
463
464 // Handle retain/strong.
465 if (attrs & (ObjCPropertyDecl::OBJC_PR_retain
466 | ObjCPropertyDecl::OBJC_PR_strong)) {
467 // In GC-only, there's nothing special that needs to be done.
468 if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly) {
469 // fallthrough
470
471 // In ARC, if the property is non-atomic, use expression emission,
472 // which translates to objc_storeStrong. This isn't required, but
473 // it's slightly nicer.
474 } else if (CGM.getLangOptions().ObjCAutoRefCount && !IsAtomic) {
475 Kind = Expression;
476 return;
477
478 // Otherwise, we need to at least use setProperty. However, if
479 // the property isn't atomic, we can use normal expression
480 // emission for the getter.
481 } else if (!IsAtomic) {
482 Kind = SetPropertyAndExpressionGet;
483 return;
484
485 // Otherwise, we have to use both setProperty and getProperty.
486 } else {
487 Kind = GetSetProperty;
488 return;
489 }
490 }
491
492 // If we're not atomic, just use expression accesses.
493 if (!IsAtomic) {
494 Kind = Expression;
495 return;
496 }
497
498 // GC-qualified or ARC-qualified ivars need to be emitted as
499 // expressions. This actually works out to being atomic anyway,
500 // except for ARC __strong, but that should trigger the above code.
501 if (ivarType.hasNonTrivialObjCLifetime() ||
502 (CGM.getLangOptions().getGCMode() &&
503 CGM.getContext().getObjCGCAttrKind(ivarType))) {
504 Kind = Expression;
505 return;
506 }
507
508 // Compute whether the ivar has strong members.
509 if (CGM.getLangOptions().getGCMode())
510 if (const RecordType *recordType = ivarType->getAs<RecordType>())
511 HasStrong = recordType->getDecl()->hasObjectMember();
512
513 // We can never access structs with object members with a native
514 // access, because we need to use write barriers. This is what
515 // objc_copyStruct is for.
516 if (HasStrong) {
517 Kind = CopyStruct;
518 return;
519 }
520
521 // Otherwise, this is target-dependent and based on the size and
522 // alignment of the ivar.
523 llvm::Triple::ArchType arch =
524 CGM.getContext().getTargetInfo().getTriple().getArch();
525
526 // Most architectures require memory to fit within a single cache
527 // line, so the alignment has to be at least the size of the access.
528 // Otherwise we have to grab a lock.
529 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
530 Kind = CopyStruct;
531 return;
532 }
533
534 // If the ivar's size exceeds the architecture's maximum atomic
535 // access size, we have to use CopyStruct.
536 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
537 Kind = CopyStruct;
538 return;
539 }
540
541 // Otherwise, we can use native loads and stores.
542 Kind = Native;
543}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000544
545/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000546/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
547/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000548void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
549 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000550 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
551 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
552 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000553 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000554
John McCall1e1f4872011-09-13 03:34:09 +0000555 generateObjCGetterBody(IMP, PID);
556
557 FinishFunction();
558}
559
560static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *PID) {
561 const Expr *getter = PID->getGetterCXXConstructor();
562 if (!getter) return true;
563
564 // Sema only makes only of these when the ivar has a C++ class type,
565 // so the form is pretty constrained.
566
567 // If we selected a trivial copy-constructor, we're okay.
568 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
569 return (construct->getConstructor()->isTrivial());
570
571 // The constructor might require cleanups (in which case it's never
572 // trivial).
573 assert(isa<ExprWithCleanups>(getter));
574 return false;
575}
576
577void
578CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
579 const ObjCPropertyImplDecl *propImpl) {
580 // If there's a non-trivial 'get' expression, we just have to emit that.
581 if (!hasTrivialGetExpr(propImpl)) {
582 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
583 /*nrvo*/ 0);
584 EmitReturnStmt(ret);
585 return;
586 }
587
588 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
589 QualType propType = prop->getType();
590 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
591
592 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
593
594 // Pick an implementation strategy.
595 PropertyImplStrategy strategy(CGM, propImpl);
596 switch (strategy.getKind()) {
597 case PropertyImplStrategy::Native: {
598 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
599
600 // Currently, all atomic accesses have to be through integer
601 // types, so there's no point in trying to pick a prettier type.
602 llvm::Type *bitcastType =
603 llvm::Type::getIntNTy(getLLVMContext(),
604 getContext().toBits(strategy.getIvarSize()));
605 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
606
607 // Perform an atomic load. This does not impose ordering constraints.
608 llvm::Value *ivarAddr = LV.getAddress();
609 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
610 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
611 load->setAlignment(strategy.getIvarAlignment().getQuantity());
612 load->setAtomic(llvm::Unordered);
613
614 // Store that value into the return address. Doing this with a
615 // bitcast is likely to produce some pretty ugly IR, but it's not
616 // the *most* terrible thing in the world.
617 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
618
619 // Make sure we don't do an autorelease.
620 AutoreleaseResult = false;
621 return;
622 }
623
624 case PropertyImplStrategy::GetSetProperty: {
625 llvm::Value *getPropertyFn =
626 CGM.getObjCRuntime().GetPropertyGetFunction();
627 if (!getPropertyFn) {
628 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000629 return;
630 }
631
632 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
633 // FIXME: Can't this be simpler? This might even be worse than the
634 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000635 llvm::Value *cmd =
636 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
637 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
638 llvm::Value *ivarOffset =
639 EmitIvarOffset(classImpl->getClassInterface(), ivar);
640
641 CallArgList args;
642 args.add(RValue::get(self), getContext().getObjCIdType());
643 args.add(RValue::get(cmd), getContext().getObjCSelType());
644 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
645
646 assert(strategy.isAtomic());
647 args.add(RValue::get(Builder.getTrue()), getContext().BoolTy);
648
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000649 // FIXME: We shouldn't need to get the function info here, the
650 // runtime already should have computed it to build the function.
John McCall1e1f4872011-09-13 03:34:09 +0000651 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCall41bdde92011-09-12 23:06:44 +0000652 FunctionType::ExtInfo()),
John McCall1e1f4872011-09-13 03:34:09 +0000653 getPropertyFn, ReturnValueSlot(), args);
654
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000655 // We need to fix the type here. Ivars with copy & retain are
656 // always objects so we don't need to worry about complex or
657 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000658 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCall1e1f4872011-09-13 03:34:09 +0000659 getTypes().ConvertType(propType)));
660
661 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000662
663 // objc_getProperty does an autorelease, so we should suppress ours.
664 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000665
John McCall1e1f4872011-09-13 03:34:09 +0000666 return;
667 }
668
669 case PropertyImplStrategy::CopyStruct:
670 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
671 strategy.hasStrongMember());
672 return;
673
674 case PropertyImplStrategy::Expression:
675 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
676 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
677
678 QualType ivarType = ivar->getType();
679 if (ivarType->isAnyComplexType()) {
680 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
681 LV.isVolatileQualified());
682 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
683 } else if (hasAggregateLLVMType(ivarType)) {
684 // The return value slot is guaranteed to not be aliased, but
685 // that's not necessarily the same as "on the stack", so
686 // we still potentially need objc_memmove_collectable.
687 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
688 } else {
John McCallba3dd902011-07-22 05:23:13 +0000689 llvm::Value *value;
690 if (propType->isReferenceType()) {
691 value = LV.getAddress();
692 } else {
693 // We want to load and autoreleaseReturnValue ARC __weak ivars.
694 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000695 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000696
697 // Otherwise we want to do a simple load, suppressing the
698 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000699 } else {
John McCallba3dd902011-07-22 05:23:13 +0000700 value = EmitLoadOfLValue(LV).getScalarVal();
701 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000702 }
John McCallf85e1932011-06-15 23:02:42 +0000703
John McCallba3dd902011-07-22 05:23:13 +0000704 value = Builder.CreateBitCast(value, ConvertType(propType));
705 }
706
707 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000708 }
John McCall1e1f4872011-09-13 03:34:09 +0000709 return;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000710 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000711
John McCall1e1f4872011-09-13 03:34:09 +0000712 }
713 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000714}
715
John McCall41bdde92011-09-12 23:06:44 +0000716/// emitStructSetterCall - Call the runtime function to store the value
717/// from the first formal parameter into the given ivar.
718static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
719 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000720 // objc_copyStruct (&structIvar, &Arg,
721 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000722 CallArgList args;
723
724 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000725 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
726 CGF.LoadObjCSelf(), ivar, 0)
727 .getAddress();
728 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
729 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000730
731 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000732 ParmVarDecl *argVar = *OMD->param_begin();
733 DeclRefExpr argRef(argVar, argVar->getType(), VK_LValue, SourceLocation());
734 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
735 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
736 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000737
738 // The third argument is the sizeof the type.
739 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000740 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
741 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000742
John McCall41bdde92011-09-12 23:06:44 +0000743 // The fourth argument is the 'isAtomic' flag.
744 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000745
John McCall41bdde92011-09-12 23:06:44 +0000746 // The fifth argument is the 'hasStrong' flag.
747 // FIXME: should this really always be false?
748 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
749
750 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
751 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
752 FunctionType::ExtInfo()),
753 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000754}
755
John McCall1e1f4872011-09-13 03:34:09 +0000756static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
757 Expr *setter = PID->getSetterCXXAssignment();
758 if (!setter) return true;
759
760 // Sema only makes only of these when the ivar has a C++ class type,
761 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +0000762
763 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +0000764 // This also implies that there's nothing non-trivial going on with
765 // the arguments, because operator= can only be trivial if it's a
766 // synthesized assignment operator and therefore both parameters are
767 // references.
768 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +0000769 if (const FunctionDecl *callee
770 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
771 if (callee->isTrivial())
772 return true;
773 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000774 }
John McCall71c758d2011-09-10 09:17:20 +0000775
John McCall1e1f4872011-09-13 03:34:09 +0000776 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +0000777 return false;
778}
779
John McCall71c758d2011-09-10 09:17:20 +0000780void
781CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
782 const ObjCPropertyImplDecl *propImpl) {
783 // Just use the setter expression if Sema gave us one and it's
784 // non-trivial. There's no way to do this atomically.
John McCall1e1f4872011-09-13 03:34:09 +0000785 if (!hasTrivialSetExpr(propImpl)) {
John McCall71c758d2011-09-10 09:17:20 +0000786 EmitStmt(propImpl->getSetterCXXAssignment());
787 return;
788 }
789
790 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
791 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
792 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
793
John McCall1e1f4872011-09-13 03:34:09 +0000794 PropertyImplStrategy strategy(CGM, propImpl);
795 switch (strategy.getKind()) {
796 case PropertyImplStrategy::Native: {
797 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +0000798
John McCall1e1f4872011-09-13 03:34:09 +0000799 LValue ivarLValue =
800 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
801 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +0000802
John McCall1e1f4872011-09-13 03:34:09 +0000803 // Currently, all atomic accesses have to be through integer
804 // types, so there's no point in trying to pick a prettier type.
805 llvm::Type *bitcastType =
806 llvm::Type::getIntNTy(getLLVMContext(),
807 getContext().toBits(strategy.getIvarSize()));
808 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
809
810 // Cast both arguments to the chosen operation type.
811 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
812 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
813
814 // This bitcast load is likely to cause some nasty IR.
815 llvm::Value *load = Builder.CreateLoad(argAddr);
816
817 // Perform an atomic store. There are no memory ordering requirements.
818 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
819 store->setAlignment(strategy.getIvarAlignment().getQuantity());
820 store->setAtomic(llvm::Unordered);
821 return;
822 }
823
824 case PropertyImplStrategy::GetSetProperty:
825 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall71c758d2011-09-10 09:17:20 +0000826 llvm::Value *setPropertyFn =
827 CGM.getObjCRuntime().GetPropertySetFunction();
828 if (!setPropertyFn) {
829 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
830 return;
831 }
832
833 // Emit objc_setProperty((id) self, _cmd, offset, arg,
834 // <is-atomic>, <is-copy>).
835 llvm::Value *cmd =
836 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
837 llvm::Value *self =
838 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
839 llvm::Value *ivarOffset =
840 EmitIvarOffset(classImpl->getClassInterface(), ivar);
841 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
842 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
843
844 CallArgList args;
845 args.add(RValue::get(self), getContext().getObjCIdType());
846 args.add(RValue::get(cmd), getContext().getObjCSelType());
847 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
848 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCall1e1f4872011-09-13 03:34:09 +0000849 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
850 getContext().BoolTy);
851 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
852 getContext().BoolTy);
John McCall71c758d2011-09-10 09:17:20 +0000853 // FIXME: We shouldn't need to get the function info here, the runtime
854 // already should have computed it to build the function.
855 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
856 FunctionType::ExtInfo()),
857 setPropertyFn, ReturnValueSlot(), args);
858 return;
859 }
860
John McCall1e1f4872011-09-13 03:34:09 +0000861 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +0000862 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +0000863 return;
John McCall1e1f4872011-09-13 03:34:09 +0000864
865 case PropertyImplStrategy::Expression:
866 break;
John McCall71c758d2011-09-10 09:17:20 +0000867 }
868
869 // Otherwise, fake up some ASTs and emit a normal assignment.
870 ValueDecl *selfDecl = setterMethod->getSelfDecl();
871 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
872 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
873 selfDecl->getType(), CK_LValueToRValue, &self,
874 VK_RValue);
875 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
876 SourceLocation(), &selfLoad, true, true);
877
878 ParmVarDecl *argDecl = *setterMethod->param_begin();
879 QualType argType = argDecl->getType().getNonReferenceType();
880 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
881 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
882 argType.getUnqualifiedType(), CK_LValueToRValue,
883 &arg, VK_RValue);
884
885 // The property type can differ from the ivar type in some situations with
886 // Objective-C pointer types, we can always bit cast the RHS in these cases.
887 // The following absurdity is just to ensure well-formed IR.
888 CastKind argCK = CK_NoOp;
889 if (ivarRef.getType()->isObjCObjectPointerType()) {
890 if (argLoad.getType()->isObjCObjectPointerType())
891 argCK = CK_BitCast;
892 else if (argLoad.getType()->isBlockPointerType())
893 argCK = CK_BlockPointerToObjCPointerCast;
894 else
895 argCK = CK_CPointerToObjCPointerCast;
896 } else if (ivarRef.getType()->isBlockPointerType()) {
897 if (argLoad.getType()->isBlockPointerType())
898 argCK = CK_BitCast;
899 else
900 argCK = CK_AnyPointerToBlockPointerCast;
901 } else if (ivarRef.getType()->isPointerType()) {
902 argCK = CK_BitCast;
903 }
904 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
905 ivarRef.getType(), argCK, &argLoad,
906 VK_RValue);
907 Expr *finalArg = &argLoad;
908 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
909 argLoad.getType()))
910 finalArg = &argCast;
911
912
913 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
914 ivarRef.getType(), VK_RValue, OK_Ordinary,
915 SourceLocation());
916 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000917}
918
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000919/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000920/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
921/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000922void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
923 const ObjCPropertyImplDecl *PID) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000924 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
925 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
926 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000927 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000928
John McCall71c758d2011-09-10 09:17:20 +0000929 generateObjCSetterBody(IMP, PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000930
931 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000932}
933
John McCalle81ac692011-03-22 07:05:39 +0000934namespace {
John McCall9928c482011-07-12 16:41:08 +0000935 struct DestroyIvar : EHScopeStack::Cleanup {
936 private:
937 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000938 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000939 CodeGenFunction::Destroyer &destroyer;
940 bool useEHCleanupForArray;
941 public:
942 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
943 CodeGenFunction::Destroyer *destroyer,
944 bool useEHCleanupForArray)
945 : addr(addr), ivar(ivar), destroyer(*destroyer),
946 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000947
John McCallad346f42011-07-12 20:27:29 +0000948 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000949 LValue lvalue
950 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
951 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000952 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000953 }
954 };
955}
956
John McCall9928c482011-07-12 16:41:08 +0000957/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
958static void destroyARCStrongWithStore(CodeGenFunction &CGF,
959 llvm::Value *addr,
960 QualType type) {
961 llvm::Value *null = getNullForVariable(addr);
962 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
963}
John McCallf85e1932011-06-15 23:02:42 +0000964
John McCalle81ac692011-03-22 07:05:39 +0000965static void emitCXXDestructMethod(CodeGenFunction &CGF,
966 ObjCImplementationDecl *impl) {
967 CodeGenFunction::RunCleanupsScope scope(CGF);
968
969 llvm::Value *self = CGF.LoadObjCSelf();
970
Jordy Rosedb8264e2011-07-22 02:08:32 +0000971 const ObjCInterfaceDecl *iface = impl->getClassInterface();
972 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +0000973 ivar; ivar = ivar->getNextIvar()) {
974 QualType type = ivar->getType();
975
John McCalle81ac692011-03-22 07:05:39 +0000976 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +0000977 QualType::DestructionKind dtorKind = type.isDestructedType();
978 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +0000979
John McCall9928c482011-07-12 16:41:08 +0000980 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +0000981
John McCall9928c482011-07-12 16:41:08 +0000982 // Use a call to objc_storeStrong to destroy strong ivars, for the
983 // general benefit of the tools.
984 if (dtorKind == QualType::DK_objc_strong_lifetime) {
985 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +0000986
John McCall9928c482011-07-12 16:41:08 +0000987 // Otherwise use the default for the destruction kind.
988 } else {
989 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +0000990 }
John McCall9928c482011-07-12 16:41:08 +0000991
992 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
993
994 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
995 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +0000996 }
997
998 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
999}
1000
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001001void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1002 ObjCMethodDecl *MD,
1003 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001004 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001005 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001006
1007 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001008 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001009 // Suppress the final autorelease in ARC.
1010 AutoreleaseResult = false;
1011
Chris Lattner5f9e2722011-07-23 10:55:15 +00001012 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001013 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1014 E = IMP->init_end(); B != E; ++B) {
1015 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001016 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001017 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001018 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1019 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001020 EmitAggExpr(IvarInit->getInit(),
1021 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001022 AggValueSlot::DoesNotNeedGCBarriers,
1023 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001024 }
1025 // constructor returns 'self'.
1026 CodeGenTypes &Types = CGM.getTypes();
1027 QualType IdTy(CGM.getContext().getObjCIdType());
1028 llvm::Value *SelfAsId =
1029 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1030 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001031
1032 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001033 } else {
John McCalle81ac692011-03-22 07:05:39 +00001034 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001035 }
1036 FinishFunction();
1037}
1038
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001039bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1040 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1041 it++; it++;
1042 const ABIArgInfo &AI = it->info;
1043 // FIXME. Is this sufficient check?
1044 return (AI.getKind() == ABIArgInfo::Indirect);
1045}
1046
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001047bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1048 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
1049 return false;
1050 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1051 return FDTTy->getDecl()->hasObjectMember();
1052 return false;
1053}
1054
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001055llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001056 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1057 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001058}
1059
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001060QualType CodeGenFunction::TypeOfSelfObject() {
1061 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1062 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001063 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1064 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001065 return PTy->getPointeeType();
1066}
1067
John McCalle68b9842010-12-04 03:11:00 +00001068LValue
1069CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1070 // This is a special l-value that just issues sends when we load or
1071 // store through it.
1072
1073 // For certain base kinds, we need to emit the base immediately.
1074 llvm::Value *Base;
1075 if (E->isSuperReceiver())
1076 Base = LoadObjCSelf();
1077 else if (E->isClassReceiver())
1078 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
1079 else
1080 Base = EmitScalarExpr(E->getBase());
1081 return LValue::MakePropertyRef(E, Base);
1082}
1083
1084static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
1085 ReturnValueSlot Return,
1086 QualType ResultType,
1087 Selector S,
1088 llvm::Value *Receiver,
1089 const CallArgList &CallArgs) {
1090 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +00001091 bool isClassMessage = OMD->isClassMethod();
1092 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +00001093 return CGF.CGM.getObjCRuntime()
1094 .GenerateMessageSendSuper(CGF, Return, ResultType,
1095 S, OMD->getClassInterface(),
1096 isCategoryImpl, Receiver,
1097 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +00001098}
1099
John McCall119a1c62010-12-04 02:32:38 +00001100RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
1101 ReturnValueSlot Return) {
1102 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +00001103 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +00001104 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +00001105 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +00001106 if (E->isExplicitProperty()) {
1107 const ObjCPropertyDecl *Property = E->getExplicitProperty();
1108 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +00001109 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +00001110 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001111 method = E->getImplicitPropertyGetter();
1112 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +00001113 }
John McCall12f78a62010-12-02 01:19:52 +00001114
John McCall119a1c62010-12-04 02:32:38 +00001115 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +00001116
John McCallf85e1932011-06-15 23:02:42 +00001117 if (CGM.getLangOptions().ObjCAutoRefCount) {
1118 QualType receiverType;
1119 if (E->isSuperReceiver())
1120 receiverType = E->getSuperReceiverType();
1121 else if (E->isClassReceiver())
1122 receiverType = getContext().getObjCClassType();
1123 else
1124 receiverType = E->getBase()->getType();
1125 }
1126
John McCalle68b9842010-12-04 03:11:00 +00001127 // Accesses to 'super' follow a different code path.
1128 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +00001129 return AdjustRelatedResultType(*this, E, method,
1130 GenerateMessageSendSuper(*this, Return,
1131 ResultType,
1132 S, Receiver,
1133 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +00001134 const ObjCInterfaceDecl *ReceiverClass
1135 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001136 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +00001137 CGM.getObjCRuntime().
1138 GenerateMessageSend(*this, Return, ResultType, S,
1139 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +00001140}
1141
John McCall119a1c62010-12-04 02:32:38 +00001142void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
1143 LValue Dst) {
1144 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +00001145 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +00001146 QualType ArgType = E->getSetterArgType();
1147
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001148 // FIXME. Other than scalars, AST is not adequate for setter and
1149 // getter type mismatches which require conversion.
1150 if (Src.isScalar()) {
1151 llvm::Value *SrcVal = Src.getScalarVal();
1152 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001153 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +00001154 if (SrcVal->getType() != DstTy)
1155 Src =
1156 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
1157 }
1158
John McCalle68b9842010-12-04 03:11:00 +00001159 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +00001160 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +00001161
1162 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
1163 QualType ResultType = getContext().VoidTy;
1164
John McCall12f78a62010-12-02 01:19:52 +00001165 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +00001166 GenerateMessageSendSuper(*this, ReturnValueSlot(),
1167 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +00001168 return;
1169 }
1170
John McCall119a1c62010-12-04 02:32:38 +00001171 const ObjCInterfaceDecl *ReceiverClass
1172 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +00001173
John McCall12f78a62010-12-02 01:19:52 +00001174 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +00001175 ResultType, S, Receiver, Args,
1176 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +00001177}
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();
1189 if (DI) {
1190 DI->setLocation(S.getSourceRange().getBegin());
1191 DI->EmitRegionStart(Builder);
1192 }
1193
Devang Patel9d99f2d2011-06-13 23:15:32 +00001194 // The local variable comes into scope immediately.
1195 AutoVarEmission variable = AutoVarEmission::invalid();
1196 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1197 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1198
John McCalld88687f2011-01-07 01:49:06 +00001199 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Anders Carlssonf484c312008-08-31 02:33:12 +00001201 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001202 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001203 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001204 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Anders Carlssonf484c312008-08-31 02:33:12 +00001206 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001207 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001208
John McCalld88687f2011-01-07 01:49:06 +00001209 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001210 IdentifierInfo *II[] = {
1211 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1212 &CGM.getContext().Idents.get("objects"),
1213 &CGM.getContext().Idents.get("count")
1214 };
1215 Selector FastEnumSel =
1216 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001217
1218 QualType ItemsTy =
1219 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001220 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001221 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001222 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001223
John McCall990567c2011-07-27 01:07:15 +00001224 // Emit the collection pointer. In ARC, we do a retain.
1225 llvm::Value *Collection;
1226 if (getLangOptions().ObjCAutoRefCount) {
1227 Collection = EmitARCRetainScalarExpr(S.getCollection());
1228
1229 // Enter a cleanup to do the release.
1230 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1231 } else {
1232 Collection = EmitScalarExpr(S.getCollection());
1233 }
Mike Stump1eb44332009-09-09 15:08:12 +00001234
John McCall4b302d32011-08-05 00:14:38 +00001235 // The 'continue' label needs to appear within the cleanup for the
1236 // collection object.
1237 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1238
John McCalld88687f2011-01-07 01:49:06 +00001239 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001240 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001241
1242 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001243 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001244
John McCalld88687f2011-01-07 01:49:06 +00001245 // The second argument is a temporary array with space for NumItems
1246 // pointers. We'll actually be loading elements from the array
1247 // pointer written into the control state; this buffer is so that
1248 // collections that *aren't* backed by arrays can still queue up
1249 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001250 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001251
John McCalld88687f2011-01-07 01:49:06 +00001252 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001253 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001254 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001255 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001256
John McCalld88687f2011-01-07 01:49:06 +00001257 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001258 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001259 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001260 getContext().UnsignedLongTy,
1261 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001262 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001263
John McCalld88687f2011-01-07 01:49:06 +00001264 // The initial number of objects that were returned in the buffer.
1265 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001266
John McCalld88687f2011-01-07 01:49:06 +00001267 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1268 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001269
John McCalld88687f2011-01-07 01:49:06 +00001270 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001271
John McCalld88687f2011-01-07 01:49:06 +00001272 // If the limit pointer was zero to begin with, the collection is
1273 // empty; skip all this.
1274 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1275 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001276
John McCalld88687f2011-01-07 01:49:06 +00001277 // Otherwise, initialize the loop.
1278 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
John McCalld88687f2011-01-07 01:49:06 +00001280 // Save the initial mutations value. This is the value at an
1281 // address that was written into the state object by
1282 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001283 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001284 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001285 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001286 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001287
John McCalld88687f2011-01-07 01:49:06 +00001288 llvm::Value *initialMutations =
1289 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001290
John McCalld88687f2011-01-07 01:49:06 +00001291 // Start looping. This is the point we return to whenever we have a
1292 // fresh, non-empty batch of objects.
1293 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1294 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001295
John McCalld88687f2011-01-07 01:49:06 +00001296 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001297 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001298 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001299
John McCalld88687f2011-01-07 01:49:06 +00001300 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001301 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001302 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001303
John McCalld88687f2011-01-07 01:49:06 +00001304 // Check whether the mutations value has changed from where it was
1305 // at start. StateMutationsPtr should actually be invariant between
1306 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001307 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001308 llvm::Value *currentMutations
1309 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001310
John McCalld88687f2011-01-07 01:49:06 +00001311 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001312 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001313
John McCalld88687f2011-01-07 01:49:06 +00001314 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1315 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001316
John McCalld88687f2011-01-07 01:49:06 +00001317 // If so, call the enumeration-mutation function.
1318 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001319 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001320 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001321 ConvertType(getContext().getObjCIdType()),
1322 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001323 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001324 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001325 // FIXME: We shouldn't need to get the function info here, the runtime already
1326 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001327 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001328 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001329 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001330
John McCalld88687f2011-01-07 01:49:06 +00001331 // Otherwise, or if the mutation function returns, just continue.
1332 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001333
John McCalld88687f2011-01-07 01:49:06 +00001334 // Initialize the element variable.
1335 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001336 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001337 LValue elementLValue;
1338 QualType elementType;
1339 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001340 // Initialize the variable, in case it's a __block variable or something.
1341 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001342
John McCall57b3b6a2011-02-22 07:16:58 +00001343 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001344 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1345 VK_LValue, SourceLocation());
1346 elementLValue = EmitLValue(&tempDRE);
1347 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001348 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001349
1350 if (D->isARCPseudoStrong())
1351 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001352 } else {
1353 elementLValue = LValue(); // suppress warning
1354 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001355 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001356 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001357 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001358
1359 // Fetch the buffer out of the enumeration state.
1360 // TODO: this pointer should actually be invariant between
1361 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001362 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001363 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001364 llvm::Value *EnumStateItems =
1365 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001366
John McCalld88687f2011-01-07 01:49:06 +00001367 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001368 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001369 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1370 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001371
John McCalld88687f2011-01-07 01:49:06 +00001372 // Cast that value to the right type.
1373 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1374 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001375
John McCalld88687f2011-01-07 01:49:06 +00001376 // Make sure we have an l-value. Yes, this gets evaluated every
1377 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001378 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001379 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001380 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001381 } else {
1382 EmitScalarInit(CurrentItem, elementLValue);
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
John McCall57b3b6a2011-02-22 07:16:58 +00001385 // If we do have an element variable, this assignment is the end of
1386 // its initialization.
1387 if (elementIsVariable)
1388 EmitAutoVarCleanups(variable);
1389
John McCalld88687f2011-01-07 01:49:06 +00001390 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001391 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001392 {
1393 RunCleanupsScope Scope(*this);
1394 EmitStmt(S.getBody());
1395 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001396 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001397
John McCalld88687f2011-01-07 01:49:06 +00001398 // Destroy the element variable now.
1399 elementVariableScope.ForceCleanup();
1400
1401 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001402 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001403
John McCalld88687f2011-01-07 01:49:06 +00001404 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001405
John McCalld88687f2011-01-07 01:49:06 +00001406 // First we check in the local buffer.
1407 llvm::Value *indexPlusOne
1408 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001409
John McCalld88687f2011-01-07 01:49:06 +00001410 // If we haven't overrun the buffer yet, we can continue.
1411 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1412 LoopBodyBB, FetchMoreBB);
1413
1414 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1415 count->addIncoming(count, AfterBody.getBlock());
1416
1417 // Otherwise, we have to fetch more elements.
1418 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001419
1420 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001421 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001422 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001423 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001424 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001425
John McCalld88687f2011-01-07 01:49:06 +00001426 // If we got a zero count, we're done.
1427 llvm::Value *refetchCount = CountRV.getScalarVal();
1428
1429 // (note that the message send might split FetchMoreBB)
1430 index->addIncoming(zero, Builder.GetInsertBlock());
1431 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1432
1433 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1434 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Anders Carlssonf484c312008-08-31 02:33:12 +00001436 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001437 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001438
John McCall57b3b6a2011-02-22 07:16:58 +00001439 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001440 // If the element was not a declaration, set it to be null.
1441
John McCalld88687f2011-01-07 01:49:06 +00001442 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1443 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001444 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001445 }
1446
Devang Patelbcbd03a2011-01-19 01:36:36 +00001447 if (DI) {
1448 DI->setLocation(S.getSourceRange().getEnd());
1449 DI->EmitRegionEnd(Builder);
1450 }
1451
John McCall990567c2011-07-27 01:07:15 +00001452 // Leave the cleanup we entered in ARC.
1453 if (getLangOptions().ObjCAutoRefCount)
1454 PopCleanupBlock();
1455
John McCallff8e1152010-07-23 21:56:41 +00001456 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001457}
1458
Mike Stump1eb44332009-09-09 15:08:12 +00001459void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001460 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001461}
1462
Mike Stump1eb44332009-09-09 15:08:12 +00001463void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001464 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1465}
1466
Chris Lattner10cac6f2008-11-15 21:26:17 +00001467void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001468 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001469 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001470}
1471
John McCall33e56f32011-09-10 06:18:15 +00001472/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001473/// primitive retain.
1474llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1475 llvm::Value *value) {
1476 return EmitARCRetain(type, value);
1477}
1478
1479namespace {
1480 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001481 CallObjCRelease(llvm::Value *object) : object(object) {}
1482 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001483
John McCallad346f42011-07-12 20:27:29 +00001484 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001485 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001486 }
1487 };
1488}
1489
John McCall33e56f32011-09-10 06:18:15 +00001490/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001491/// release at the end of the full-expression.
1492llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1493 llvm::Value *object) {
1494 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001495 // conditional.
1496 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001497 return object;
1498}
1499
1500llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1501 llvm::Value *value) {
1502 return EmitARCRetainAutorelease(type, value);
1503}
1504
1505
1506static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001507 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001508 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001509 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1510
1511 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1512 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001513 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001514 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1515 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1516
1517 return fn;
1518}
1519
1520/// Perform an operation having the signature
1521/// i8* (i8*)
1522/// where a null input causes a no-op and returns null.
1523static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1524 llvm::Value *value,
1525 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001526 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001527 if (isa<llvm::ConstantPointerNull>(value)) return value;
1528
1529 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001530 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001531 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001532 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1533 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1534 }
1535
1536 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001537 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001538 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1539
1540 // Call the function.
1541 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1542 call->setDoesNotThrow();
1543
1544 // Cast the result back to the original type.
1545 return CGF.Builder.CreateBitCast(call, origType);
1546}
1547
1548/// Perform an operation having the following signature:
1549/// i8* (i8**)
1550static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1551 llvm::Value *addr,
1552 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001553 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001554 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001555 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001556 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001557 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1558 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1559 }
1560
1561 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001562 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001563 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1564
1565 // Call the function.
1566 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1567 call->setDoesNotThrow();
1568
1569 // Cast the result back to a dereference of the original type.
1570 llvm::Value *result = call;
1571 if (origType != CGF.Int8PtrPtrTy)
1572 result = CGF.Builder.CreateBitCast(result,
1573 cast<llvm::PointerType>(origType)->getElementType());
1574
1575 return result;
1576}
1577
1578/// Perform an operation having the following signature:
1579/// i8* (i8**, i8*)
1580static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1581 llvm::Value *addr,
1582 llvm::Value *value,
1583 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001584 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001585 bool ignored) {
1586 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1587 == value->getType());
1588
1589 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001590 std::vector<llvm::Type*> argTypes(2);
John McCallf85e1932011-06-15 23:02:42 +00001591 argTypes[0] = CGF.Int8PtrPtrTy;
1592 argTypes[1] = CGF.Int8PtrTy;
1593
Chris Lattner2acc6e32011-07-18 04:24:23 +00001594 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001595 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1596 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1597 }
1598
Chris Lattner2acc6e32011-07-18 04:24:23 +00001599 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001600
1601 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1602 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1603
1604 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1605 result->setDoesNotThrow();
1606
1607 if (ignored) return 0;
1608
1609 return CGF.Builder.CreateBitCast(result, origType);
1610}
1611
1612/// Perform an operation having the following signature:
1613/// void (i8**, i8**)
1614static void emitARCCopyOperation(CodeGenFunction &CGF,
1615 llvm::Value *dst,
1616 llvm::Value *src,
1617 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001618 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001619 assert(dst->getType() == src->getType());
1620
1621 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001622 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001623 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001624 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1625 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1626 }
1627
1628 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1629 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1630
1631 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1632 result->setDoesNotThrow();
1633}
1634
1635/// Produce the code to do a retain. Based on the type, calls one of:
1636/// call i8* @objc_retain(i8* %value)
1637/// call i8* @objc_retainBlock(i8* %value)
1638llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1639 if (type->isBlockPointerType())
1640 return EmitARCRetainBlock(value);
1641 else
1642 return EmitARCRetainNonBlock(value);
1643}
1644
1645/// Retain the given object, with normal retain semantics.
1646/// call i8* @objc_retain(i8* %value)
1647llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1648 return emitARCValueOperation(*this, value,
1649 CGM.getARCEntrypoints().objc_retain,
1650 "objc_retain");
1651}
1652
1653/// Retain the given block, with _Block_copy semantics.
1654/// call i8* @objc_retainBlock(i8* %value)
1655llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1656 return emitARCValueOperation(*this, value,
1657 CGM.getARCEntrypoints().objc_retainBlock,
1658 "objc_retainBlock");
1659}
1660
1661/// Retain the given object which is the result of a function call.
1662/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1663///
1664/// Yes, this function name is one character away from a different
1665/// call with completely different semantics.
1666llvm::Value *
1667CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1668 // Fetch the void(void) inline asm which marks that we're going to
1669 // retain the autoreleased return value.
1670 llvm::InlineAsm *&marker
1671 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1672 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001673 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001674 = CGM.getTargetCodeGenInfo()
1675 .getARCRetainAutoreleasedReturnValueMarker();
1676
1677 // If we have an empty assembly string, there's nothing to do.
1678 if (assembly.empty()) {
1679
1680 // Otherwise, at -O0, build an inline asm that we're going to call
1681 // in a moment.
1682 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1683 llvm::FunctionType *type =
1684 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1685 /*variadic*/ false);
1686
1687 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1688
1689 // If we're at -O1 and above, we don't want to litter the code
1690 // with this marker yet, so leave a breadcrumb for the ARC
1691 // optimizer to pick up.
1692 } else {
1693 llvm::NamedMDNode *metadata =
1694 CGM.getModule().getOrInsertNamedMetadata(
1695 "clang.arc.retainAutoreleasedReturnValueMarker");
1696 assert(metadata->getNumOperands() <= 1);
1697 if (metadata->getNumOperands() == 0) {
1698 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001699 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001700 }
1701 }
1702 }
1703
1704 // Call the marker asm if we made one, which we do only at -O0.
1705 if (marker) Builder.CreateCall(marker);
1706
1707 return emitARCValueOperation(*this, value,
1708 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1709 "objc_retainAutoreleasedReturnValue");
1710}
1711
1712/// Release the given object.
1713/// call void @objc_release(i8* %value)
1714void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1715 if (isa<llvm::ConstantPointerNull>(value)) return;
1716
1717 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1718 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001719 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001720 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001721 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1722 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1723 }
1724
1725 // Cast the argument to 'id'.
1726 value = Builder.CreateBitCast(value, Int8PtrTy);
1727
1728 // Call objc_release.
1729 llvm::CallInst *call = Builder.CreateCall(fn, value);
1730 call->setDoesNotThrow();
1731
1732 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001733 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001734 call->setMetadata("clang.imprecise_release",
1735 llvm::MDNode::get(Builder.getContext(), args));
1736 }
1737}
1738
1739/// Store into a strong object. Always calls this:
1740/// call void @objc_storeStrong(i8** %addr, i8* %value)
1741llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1742 llvm::Value *value,
1743 bool ignored) {
1744 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1745 == value->getType());
1746
1747 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1748 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001749 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001750 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001751 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1752 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1753 }
1754
1755 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1756 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1757
1758 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1759
1760 if (ignored) return 0;
1761 return value;
1762}
1763
1764/// Store into a strong object. Sometimes calls this:
1765/// call void @objc_storeStrong(i8** %addr, i8* %value)
1766/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001767llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001768 llvm::Value *newValue,
1769 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001770 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001771 bool isBlock = type->isBlockPointerType();
1772
1773 // Use a store barrier at -O0 unless this is a block type or the
1774 // lvalue is inadequately aligned.
1775 if (shouldUseFusedARCCalls() &&
1776 !isBlock &&
1777 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1778 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1779 }
1780
1781 // Otherwise, split it out.
1782
1783 // Retain the new value.
1784 newValue = EmitARCRetain(type, newValue);
1785
1786 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001787 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001788
1789 // Store. We do this before the release so that any deallocs won't
1790 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001791 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001792
1793 // Finally, release the old value.
1794 EmitARCRelease(oldValue, /*precise*/ false);
1795
1796 return newValue;
1797}
1798
1799/// Autorelease the given object.
1800/// call i8* @objc_autorelease(i8* %value)
1801llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1802 return emitARCValueOperation(*this, value,
1803 CGM.getARCEntrypoints().objc_autorelease,
1804 "objc_autorelease");
1805}
1806
1807/// Autorelease the given object.
1808/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1809llvm::Value *
1810CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1811 return emitARCValueOperation(*this, value,
1812 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1813 "objc_autoreleaseReturnValue");
1814}
1815
1816/// Do a fused retain/autorelease of the given object.
1817/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1818llvm::Value *
1819CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1820 return emitARCValueOperation(*this, value,
1821 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1822 "objc_retainAutoreleaseReturnValue");
1823}
1824
1825/// Do a fused retain/autorelease of the given object.
1826/// call i8* @objc_retainAutorelease(i8* %value)
1827/// or
1828/// %retain = call i8* @objc_retainBlock(i8* %value)
1829/// call i8* @objc_autorelease(i8* %retain)
1830llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1831 llvm::Value *value) {
1832 if (!type->isBlockPointerType())
1833 return EmitARCRetainAutoreleaseNonBlock(value);
1834
1835 if (isa<llvm::ConstantPointerNull>(value)) return value;
1836
Chris Lattner2acc6e32011-07-18 04:24:23 +00001837 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001838 value = Builder.CreateBitCast(value, Int8PtrTy);
1839 value = EmitARCRetainBlock(value);
1840 value = EmitARCAutorelease(value);
1841 return Builder.CreateBitCast(value, origType);
1842}
1843
1844/// Do a fused retain/autorelease of the given object.
1845/// call i8* @objc_retainAutorelease(i8* %value)
1846llvm::Value *
1847CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1848 return emitARCValueOperation(*this, value,
1849 CGM.getARCEntrypoints().objc_retainAutorelease,
1850 "objc_retainAutorelease");
1851}
1852
1853/// i8* @objc_loadWeak(i8** %addr)
1854/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1855llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1856 return emitARCLoadOperation(*this, addr,
1857 CGM.getARCEntrypoints().objc_loadWeak,
1858 "objc_loadWeak");
1859}
1860
1861/// i8* @objc_loadWeakRetained(i8** %addr)
1862llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1863 return emitARCLoadOperation(*this, addr,
1864 CGM.getARCEntrypoints().objc_loadWeakRetained,
1865 "objc_loadWeakRetained");
1866}
1867
1868/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1869/// Returns %value.
1870llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1871 llvm::Value *value,
1872 bool ignored) {
1873 return emitARCStoreOperation(*this, addr, value,
1874 CGM.getARCEntrypoints().objc_storeWeak,
1875 "objc_storeWeak", ignored);
1876}
1877
1878/// i8* @objc_initWeak(i8** %addr, i8* %value)
1879/// Returns %value. %addr is known to not have a current weak entry.
1880/// Essentially equivalent to:
1881/// *addr = nil; objc_storeWeak(addr, value);
1882void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1883 // If we're initializing to null, just write null to memory; no need
1884 // to get the runtime involved. But don't do this if optimization
1885 // is enabled, because accounting for this would make the optimizer
1886 // much more complicated.
1887 if (isa<llvm::ConstantPointerNull>(value) &&
1888 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1889 Builder.CreateStore(value, addr);
1890 return;
1891 }
1892
1893 emitARCStoreOperation(*this, addr, value,
1894 CGM.getARCEntrypoints().objc_initWeak,
1895 "objc_initWeak", /*ignored*/ true);
1896}
1897
1898/// void @objc_destroyWeak(i8** %addr)
1899/// Essentially objc_storeWeak(addr, nil).
1900void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1901 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1902 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001903 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001904 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001905 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1906 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1907 }
1908
1909 // Cast the argument to 'id*'.
1910 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1911
1912 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1913 call->setDoesNotThrow();
1914}
1915
1916/// void @objc_moveWeak(i8** %dest, i8** %src)
1917/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1918/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1919void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1920 emitARCCopyOperation(*this, dst, src,
1921 CGM.getARCEntrypoints().objc_moveWeak,
1922 "objc_moveWeak");
1923}
1924
1925/// void @objc_copyWeak(i8** %dest, i8** %src)
1926/// Disregards the current value in %dest. Essentially
1927/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1928void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1929 emitARCCopyOperation(*this, dst, src,
1930 CGM.getARCEntrypoints().objc_copyWeak,
1931 "objc_copyWeak");
1932}
1933
1934/// Produce the code to do a objc_autoreleasepool_push.
1935/// call i8* @objc_autoreleasePoolPush(void)
1936llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1937 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1938 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001939 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001940 llvm::FunctionType::get(Int8PtrTy, false);
1941 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1942 }
1943
1944 llvm::CallInst *call = Builder.CreateCall(fn);
1945 call->setDoesNotThrow();
1946
1947 return call;
1948}
1949
1950/// Produce the code to do a primitive release.
1951/// call void @objc_autoreleasePoolPop(i8* %ptr)
1952void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1953 assert(value->getType() == Int8PtrTy);
1954
1955 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1956 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001957 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001958 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001959 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1960
1961 // We don't want to use a weak import here; instead we should not
1962 // fall into this path.
1963 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1964 }
1965
1966 llvm::CallInst *call = Builder.CreateCall(fn, value);
1967 call->setDoesNotThrow();
1968}
1969
1970/// Produce the code to do an MRR version objc_autoreleasepool_push.
1971/// Which is: [[NSAutoreleasePool alloc] init];
1972/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1973/// init is declared as: - (id) init; in its NSObject super class.
1974///
1975llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1976 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1977 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1978 // [NSAutoreleasePool alloc]
1979 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1980 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1981 CallArgList Args;
1982 RValue AllocRV =
1983 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1984 getContext().getObjCIdType(),
1985 AllocSel, Receiver, Args);
1986
1987 // [Receiver init]
1988 Receiver = AllocRV.getScalarVal();
1989 II = &CGM.getContext().Idents.get("init");
1990 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1991 RValue InitRV =
1992 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1993 getContext().getObjCIdType(),
1994 InitSel, Receiver, Args);
1995 return InitRV.getScalarVal();
1996}
1997
1998/// Produce the code to do a primitive release.
1999/// [tmp drain];
2000void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2001 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2002 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2003 CallArgList Args;
2004 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2005 getContext().VoidTy, DrainSel, Arg, Args);
2006}
2007
John McCallbdc4d802011-07-09 01:37:26 +00002008void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2009 llvm::Value *addr,
2010 QualType type) {
2011 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2012 CGF.EmitARCRelease(ptr, /*precise*/ true);
2013}
2014
2015void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2016 llvm::Value *addr,
2017 QualType type) {
2018 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2019 CGF.EmitARCRelease(ptr, /*precise*/ false);
2020}
2021
2022void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2023 llvm::Value *addr,
2024 QualType type) {
2025 CGF.EmitARCDestroyWeak(addr);
2026}
2027
John McCallf85e1932011-06-15 23:02:42 +00002028namespace {
John McCallf85e1932011-06-15 23:02:42 +00002029 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2030 llvm::Value *Token;
2031
2032 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2033
John McCallad346f42011-07-12 20:27:29 +00002034 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002035 CGF.EmitObjCAutoreleasePoolPop(Token);
2036 }
2037 };
2038 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2039 llvm::Value *Token;
2040
2041 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2042
John McCallad346f42011-07-12 20:27:29 +00002043 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002044 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2045 }
2046 };
2047}
2048
2049void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2050 if (CGM.getLangOptions().ObjCAutoRefCount)
2051 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2052 else
2053 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2054}
2055
John McCallf85e1932011-06-15 23:02:42 +00002056static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2057 LValue lvalue,
2058 QualType type) {
2059 switch (type.getObjCLifetime()) {
2060 case Qualifiers::OCL_None:
2061 case Qualifiers::OCL_ExplicitNone:
2062 case Qualifiers::OCL_Strong:
2063 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002064 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002065 false);
2066
2067 case Qualifiers::OCL_Weak:
2068 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2069 true);
2070 }
2071
2072 llvm_unreachable("impossible lifetime!");
2073 return TryEmitResult();
2074}
2075
2076static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2077 const Expr *e) {
2078 e = e->IgnoreParens();
2079 QualType type = e->getType();
2080
John McCall21480112011-08-30 00:57:29 +00002081 // If we're loading retained from a __strong xvalue, we can avoid
2082 // an extra retain/release pair by zeroing out the source of this
2083 // "move" operation.
2084 if (e->isXValue() &&
2085 !type.isConstQualified() &&
2086 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2087 // Emit the lvalue.
2088 LValue lv = CGF.EmitLValue(e);
2089
2090 // Load the object pointer.
2091 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2092
2093 // Set the source pointer to NULL.
2094 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2095
2096 return TryEmitResult(result, true);
2097 }
2098
John McCallf85e1932011-06-15 23:02:42 +00002099 // As a very special optimization, in ARC++, if the l-value is the
2100 // result of a non-volatile assignment, do a simple retain of the
2101 // result of the call to objc_storeWeak instead of reloading.
2102 if (CGF.getLangOptions().CPlusPlus &&
2103 !type.isVolatileQualified() &&
2104 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2105 isa<BinaryOperator>(e) &&
2106 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2107 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2108
2109 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2110}
2111
2112static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2113 llvm::Value *value);
2114
2115/// Given that the given expression is some sort of call (which does
2116/// not return retained), emit a retain following it.
2117static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2118 llvm::Value *value = CGF.EmitScalarExpr(e);
2119 return emitARCRetainAfterCall(CGF, value);
2120}
2121
2122static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2123 llvm::Value *value) {
2124 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2125 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2126
2127 // Place the retain immediately following the call.
2128 CGF.Builder.SetInsertPoint(call->getParent(),
2129 ++llvm::BasicBlock::iterator(call));
2130 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2131
2132 CGF.Builder.restoreIP(ip);
2133 return value;
2134 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2135 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2136
2137 // Place the retain at the beginning of the normal destination block.
2138 llvm::BasicBlock *BB = invoke->getNormalDest();
2139 CGF.Builder.SetInsertPoint(BB, BB->begin());
2140 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2141
2142 CGF.Builder.restoreIP(ip);
2143 return value;
2144
2145 // Bitcasts can arise because of related-result returns. Rewrite
2146 // the operand.
2147 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2148 llvm::Value *operand = bitcast->getOperand(0);
2149 operand = emitARCRetainAfterCall(CGF, operand);
2150 bitcast->setOperand(0, operand);
2151 return bitcast;
2152
2153 // Generic fall-back case.
2154 } else {
2155 // Retain using the non-block variant: we never need to do a copy
2156 // of a block that's been returned to us.
2157 return CGF.EmitARCRetainNonBlock(value);
2158 }
2159}
2160
John McCalldc05b112011-09-10 01:16:55 +00002161/// Determine whether it might be important to emit a separate
2162/// objc_retain_block on the result of the given expression, or
2163/// whether it's okay to just emit it in a +1 context.
2164static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2165 assert(e->getType()->isBlockPointerType());
2166 e = e->IgnoreParens();
2167
2168 // For future goodness, emit block expressions directly in +1
2169 // contexts if we can.
2170 if (isa<BlockExpr>(e))
2171 return false;
2172
2173 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2174 switch (cast->getCastKind()) {
2175 // Emitting these operations in +1 contexts is goodness.
2176 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002177 case CK_ARCReclaimReturnedObject:
2178 case CK_ARCConsumeObject:
2179 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002180 return false;
2181
2182 // These operations preserve a block type.
2183 case CK_NoOp:
2184 case CK_BitCast:
2185 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2186
2187 // These operations are known to be bad (or haven't been considered).
2188 case CK_AnyPointerToBlockPointerCast:
2189 default:
2190 return true;
2191 }
2192 }
2193
2194 return true;
2195}
2196
John McCallf85e1932011-06-15 23:02:42 +00002197static TryEmitResult
2198tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall990567c2011-07-27 01:07:15 +00002199 // Look through cleanups.
2200 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2201 CodeGenFunction::RunCleanupsScope scope(CGF);
2202 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2203 }
2204
John McCallf85e1932011-06-15 23:02:42 +00002205 // The desired result type, if it differs from the type of the
2206 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002207 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002208
2209 while (true) {
2210 e = e->IgnoreParens();
2211
2212 // There's a break at the end of this if-chain; anything
2213 // that wants to keep looping has to explicitly continue.
2214 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2215 switch (ce->getCastKind()) {
2216 // No-op casts don't change the type, so we just ignore them.
2217 case CK_NoOp:
2218 e = ce->getSubExpr();
2219 continue;
2220
2221 case CK_LValueToRValue: {
2222 TryEmitResult loadResult
2223 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2224 if (resultType) {
2225 llvm::Value *value = loadResult.getPointer();
2226 value = CGF.Builder.CreateBitCast(value, resultType);
2227 loadResult.setPointer(value);
2228 }
2229 return loadResult;
2230 }
2231
2232 // These casts can change the type, so remember that and
2233 // soldier on. We only need to remember the outermost such
2234 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002235 case CK_CPointerToObjCPointerCast:
2236 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002237 case CK_AnyPointerToBlockPointerCast:
2238 case CK_BitCast:
2239 if (!resultType)
2240 resultType = CGF.ConvertType(ce->getType());
2241 e = ce->getSubExpr();
2242 assert(e->getType()->hasPointerRepresentation());
2243 continue;
2244
2245 // For consumptions, just emit the subexpression and thus elide
2246 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002247 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002248 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2249 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2250 return TryEmitResult(result, true);
2251 }
2252
John McCalldc05b112011-09-10 01:16:55 +00002253 // Block extends are net +0. Naively, we could just recurse on
2254 // the subexpression, but actually we need to ensure that the
2255 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002256 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002257 llvm::Value *result; // will be a +0 value
2258
2259 // If we can't safely assume the sub-expression will produce a
2260 // block-copied value, emit the sub-expression at +0.
2261 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2262 result = CGF.EmitScalarExpr(ce->getSubExpr());
2263
2264 // Otherwise, try to emit the sub-expression at +1 recursively.
2265 } else {
2266 TryEmitResult subresult
2267 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2268 result = subresult.getPointer();
2269
2270 // If that produced a retained value, just use that,
2271 // possibly casting down.
2272 if (subresult.getInt()) {
2273 if (resultType)
2274 result = CGF.Builder.CreateBitCast(result, resultType);
2275 return TryEmitResult(result, true);
2276 }
2277
2278 // Otherwise it's +0.
2279 }
2280
2281 // Retain the object as a block, then cast down.
2282 result = CGF.EmitARCRetainBlock(result);
2283 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2284 return TryEmitResult(result, true);
2285 }
2286
John McCall7e5e5f42011-07-07 06:58:02 +00002287 // For reclaims, emit the subexpression as a retained call and
2288 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002289 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002290 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2291 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2292 return TryEmitResult(result, true);
2293 }
2294
John McCallf85e1932011-06-15 23:02:42 +00002295 case CK_GetObjCProperty: {
2296 llvm::Value *result = emitARCRetainCall(CGF, ce);
2297 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2298 return TryEmitResult(result, true);
2299 }
2300
2301 default:
2302 break;
2303 }
2304
2305 // Skip __extension__.
2306 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2307 if (op->getOpcode() == UO_Extension) {
2308 e = op->getSubExpr();
2309 continue;
2310 }
2311
2312 // For calls and message sends, use the retained-call logic.
2313 // Delegate inits are a special case in that they're the only
2314 // returns-retained expression that *isn't* surrounded by
2315 // a consume.
2316 } else if (isa<CallExpr>(e) ||
2317 (isa<ObjCMessageExpr>(e) &&
2318 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2319 llvm::Value *result = emitARCRetainCall(CGF, e);
2320 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2321 return TryEmitResult(result, true);
2322 }
2323
2324 // Conservatively halt the search at any other expression kind.
2325 break;
2326 }
2327
2328 // We didn't find an obvious production, so emit what we've got and
2329 // tell the caller that we didn't manage to retain.
2330 llvm::Value *result = CGF.EmitScalarExpr(e);
2331 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2332 return TryEmitResult(result, false);
2333}
2334
2335static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2336 LValue lvalue,
2337 QualType type) {
2338 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2339 llvm::Value *value = result.getPointer();
2340 if (!result.getInt())
2341 value = CGF.EmitARCRetain(type, value);
2342 return value;
2343}
2344
2345/// EmitARCRetainScalarExpr - Semantically equivalent to
2346/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2347/// best-effort attempt to peephole expressions that naturally produce
2348/// retained objects.
2349llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2350 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2351 llvm::Value *value = result.getPointer();
2352 if (!result.getInt())
2353 value = EmitARCRetain(e->getType(), value);
2354 return value;
2355}
2356
2357llvm::Value *
2358CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2359 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2360 llvm::Value *value = result.getPointer();
2361 if (result.getInt())
2362 value = EmitARCAutorelease(value);
2363 else
2364 value = EmitARCRetainAutorelease(e->getType(), value);
2365 return value;
2366}
2367
2368std::pair<LValue,llvm::Value*>
2369CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2370 bool ignored) {
2371 // Evaluate the RHS first.
2372 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2373 llvm::Value *value = result.getPointer();
2374
John McCallfb720812011-07-28 07:23:35 +00002375 bool hasImmediateRetain = result.getInt();
2376
2377 // If we didn't emit a retained object, and the l-value is of block
2378 // type, then we need to emit the block-retain immediately in case
2379 // it invalidates the l-value.
2380 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2381 value = EmitARCRetainBlock(value);
2382 hasImmediateRetain = true;
2383 }
2384
John McCallf85e1932011-06-15 23:02:42 +00002385 LValue lvalue = EmitLValue(e->getLHS());
2386
2387 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002388 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002389 llvm::Value *oldValue =
2390 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2391 lvalue.getAlignment(), e->getType(),
2392 lvalue.getTBAAInfo());
2393 EmitStoreOfScalar(value, lvalue.getAddress(),
2394 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2395 e->getType(), lvalue.getTBAAInfo());
2396 EmitARCRelease(oldValue, /*precise*/ false);
2397 } else {
John McCall545d9962011-06-25 02:11:03 +00002398 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002399 }
2400
2401 return std::pair<LValue,llvm::Value*>(lvalue, value);
2402}
2403
2404std::pair<LValue,llvm::Value*>
2405CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2406 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2407 LValue lvalue = EmitLValue(e->getLHS());
2408
2409 EmitStoreOfScalar(value, lvalue.getAddress(),
2410 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2411 e->getType(), lvalue.getTBAAInfo());
2412
2413 return std::pair<LValue,llvm::Value*>(lvalue, value);
2414}
2415
2416void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2417 const ObjCAutoreleasePoolStmt &ARPS) {
2418 const Stmt *subStmt = ARPS.getSubStmt();
2419 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2420
2421 CGDebugInfo *DI = getDebugInfo();
2422 if (DI) {
2423 DI->setLocation(S.getLBracLoc());
2424 DI->EmitRegionStart(Builder);
2425 }
2426
2427 // Keep track of the current cleanup stack depth.
2428 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002429 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002430 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2431 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2432 } else {
2433 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2434 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2435 }
2436
2437 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2438 E = S.body_end(); I != E; ++I)
2439 EmitStmt(*I);
2440
2441 if (DI) {
2442 DI->setLocation(S.getRBracLoc());
2443 DI->EmitRegionEnd(Builder);
2444 }
2445}
John McCall0c24c802011-06-24 23:21:27 +00002446
2447/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2448/// make sure it survives garbage collection until this point.
2449void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2450 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002451 llvm::FunctionType *extenderType
Jay Foadda549e82011-07-29 13:56:53 +00002452 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall0c24c802011-06-24 23:21:27 +00002453 llvm::Value *extender
2454 = llvm::InlineAsm::get(extenderType,
2455 /* assembly */ "",
2456 /* constraints */ "r",
2457 /* side effects */ true);
2458
2459 object = Builder.CreateBitCast(object, VoidPtrTy);
2460 Builder.CreateCall(extender, object)->setDoesNotThrow();
2461}
2462
Ted Kremenek2979ec72008-04-09 15:51:31 +00002463CGObjCRuntime::~CGObjCRuntime() {}