blob: ca04a7b17853e2c868d18b05f1eefbfa57557dde [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbara08dff12008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCall31168b02011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-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 Lattner2192fe52011-07-18 04:24:23 +000036 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattnerb1d329d2008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000043{
David Chisnall481e3a82010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-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 Dunbar45858d22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +000057}
58
Daniel Dunbar66912a12008-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 Lattnerb1d329d2008-06-24 17:04:18 +000063
Douglas Gregor33823722011-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 McCall31168b02011-06-15 23:02:42 +000072
Douglas Gregor33823722011-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 Lattnerb1d329d2008-06-24 17:04:18 +000082
John McCallcf166702011-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 McCall78a15112010-05-22 01:48:05 +0000130RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
131 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-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 Stump11289f42009-09-09 15:08:12 +0000135
John McCall31168b02011-06-15 23:02:42 +0000136 bool isDelegateInit = E->isDelegateInitCall();
137
John McCallcf166702011-07-22 08:53:00 +0000138 const ObjCMethodDecl *method = E->getMethodDecl();
139
John McCall31168b02011-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 McCallcf166702011-07-22 08:53:00 +0000147 method &&
148 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000149
Daniel Dunbar8d480592008-08-11 18:12:00 +0000150 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000151 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000152 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +0000153 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000154 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000155 QualType ReceiverType;
Daniel Dunbarb2197802010-04-22 03:17:06 +0000156 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +0000157 switch (E->getReceiverKind()) {
158 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000159 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000160 if (retainSelf) {
161 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
162 E->getInstanceReceiver());
163 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000164 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000165 } else
166 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000167 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000168
Douglas Gregor9a129192010-04-21 00:45:42 +0000169 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000170 ReceiverType = E->getClassReceiver();
171 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-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 Chisnall01aa4672010-04-28 19:33:36 +0000175 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000176 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000177 break;
178 }
179
180 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000181 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000182 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000183 isSuperMessage = true;
184 break;
185
186 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000187 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000188 Receiver = LoadObjCSelf();
189 isSuperMessage = true;
190 isClassMessage = true;
191 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000192 }
193
John McCallcf166702011-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 McCall31168b02011-06-15 23:02:42 +0000205 QualType ResultType =
John McCallcf166702011-07-22 08:53:00 +0000206 method ? method->getResultType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000207
Daniel Dunbarc722b852008-08-30 03:02:31 +0000208 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000209 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000210
John McCall31168b02011-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 Carlsson280e61f12010-06-21 20:59:55 +0000229
Douglas Gregor33823722011-06-11 01:09:30 +0000230 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000231 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000232 // super is only valid in an Objective-C method
233 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000234 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-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 McCallcf166702011-07-22 08:53:00 +0000242 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000243 } else {
244 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
245 E->getSelector(),
246 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000247 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000248 }
John McCall31168b02011-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 Lattner2192fe52011-07-18 04:24:23 +0000259 llvm::Type *selfTy =
John McCall31168b02011-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 McCallcf166702011-07-22 08:53:00 +0000266 return AdjustRelatedResultType(*this, E, method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000267}
268
John McCall31168b02011-06-15 23:02:42 +0000269namespace {
270struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCall30317fd2011-07-12 20:27:29 +0000271 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +0000272 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000273
274 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000275 const ObjCInterfaceDecl *iface = impl->getClassInterface();
276 if (!iface->getSuperClass()) return;
277
John McCalldffafde2011-07-13 18:26:47 +0000278 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
279
John McCall31168b02011-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 McCalldffafde2011-07-13 18:26:47 +0000288 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000289 self,
290 /*is class msg*/ false,
291 args,
292 method);
293 }
294};
295}
296
Daniel Dunbar89654ee2008-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 Jahanian0196a1c2009-01-10 21:06:09 +0000300void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000301 const ObjCContainerDecl *CD,
302 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000303 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000304 // Check if we should generate debug info for this method.
Devang Pateld6ffebb2011-03-07 18:45:56 +0000305 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
306 DebugInfo = CGM.getModuleDebugInfo();
Devang Patela2c048e2010-04-05 21:09:15 +0000307
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000308 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000309
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000310 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
311 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000312
John McCalla738c252011-03-09 04:27:21 +0000313 args.push_back(OMD->getSelfDecl());
314 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000315
Chris Lattnera4997152009-02-20 18:43:26 +0000316 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
317 E = OMD->param_end(); PI != E; ++PI)
John McCalla738c252011-03-09 04:27:21 +0000318 args.push_back(*PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000319
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000320 CurGD = OMD;
321
Devang Patele7ce5402011-05-19 23:37:41 +0000322 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCall31168b02011-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 Dunbar89654ee2008-08-26 08:29:31 +0000333}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000334
John McCall31168b02011-06-15 23:02:42 +0000335static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
336 LValue lvalue, QualType type);
337
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000338/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000339/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000340void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000341 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000342 EmitStmt(OMD->getBody());
343 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000344}
345
John McCallb923ece2011-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 McCallf4528ae2011-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
John McCall0e5c0862011-09-13 05:36:29 +0000498 // Properties on bitfield ivars need to be emitted using expression
499 // accesses even if they're nominally atomic.
500 if (ivar->isBitField()) {
501 Kind = Expression;
502 return;
503 }
504
John McCallf4528ae2011-09-13 03:34:09 +0000505 // GC-qualified or ARC-qualified ivars need to be emitted as
506 // expressions. This actually works out to being atomic anyway,
507 // except for ARC __strong, but that should trigger the above code.
508 if (ivarType.hasNonTrivialObjCLifetime() ||
509 (CGM.getLangOptions().getGCMode() &&
510 CGM.getContext().getObjCGCAttrKind(ivarType))) {
511 Kind = Expression;
512 return;
513 }
514
515 // Compute whether the ivar has strong members.
516 if (CGM.getLangOptions().getGCMode())
517 if (const RecordType *recordType = ivarType->getAs<RecordType>())
518 HasStrong = recordType->getDecl()->hasObjectMember();
519
520 // We can never access structs with object members with a native
521 // access, because we need to use write barriers. This is what
522 // objc_copyStruct is for.
523 if (HasStrong) {
524 Kind = CopyStruct;
525 return;
526 }
527
528 // Otherwise, this is target-dependent and based on the size and
529 // alignment of the ivar.
530 llvm::Triple::ArchType arch =
531 CGM.getContext().getTargetInfo().getTriple().getArch();
532
533 // Most architectures require memory to fit within a single cache
534 // line, so the alignment has to be at least the size of the access.
535 // Otherwise we have to grab a lock.
536 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
537 Kind = CopyStruct;
538 return;
539 }
540
541 // If the ivar's size exceeds the architecture's maximum atomic
542 // access size, we have to use CopyStruct.
543 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
544 Kind = CopyStruct;
545 return;
546 }
547
548 // Otherwise, we can use native loads and stores.
549 Kind = Native;
550}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000551
552/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff5a7dd782009-01-10 22:55:25 +0000553/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
554/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000555void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
556 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000557 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
558 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
559 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patele7ce5402011-05-19 23:37:41 +0000560 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000561
John McCallf4528ae2011-09-13 03:34:09 +0000562 generateObjCGetterBody(IMP, PID);
563
564 FinishFunction();
565}
566
John McCallbdd81852011-09-13 06:00:03 +0000567static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
568 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000569 if (!getter) return true;
570
571 // Sema only makes only of these when the ivar has a C++ class type,
572 // so the form is pretty constrained.
573
John McCallbdd81852011-09-13 06:00:03 +0000574 // If the property has a reference type, we might just be binding a
575 // reference, in which case the result will be a gl-value. We should
576 // treat this as a non-trivial operation.
577 if (getter->isGLValue())
578 return false;
579
John McCallf4528ae2011-09-13 03:34:09 +0000580 // If we selected a trivial copy-constructor, we're okay.
581 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
582 return (construct->getConstructor()->isTrivial());
583
584 // The constructor might require cleanups (in which case it's never
585 // trivial).
586 assert(isa<ExprWithCleanups>(getter));
587 return false;
588}
589
590void
591CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
592 const ObjCPropertyImplDecl *propImpl) {
593 // If there's a non-trivial 'get' expression, we just have to emit that.
594 if (!hasTrivialGetExpr(propImpl)) {
595 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
596 /*nrvo*/ 0);
597 EmitReturnStmt(ret);
598 return;
599 }
600
601 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
602 QualType propType = prop->getType();
603 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
604
605 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
606
607 // Pick an implementation strategy.
608 PropertyImplStrategy strategy(CGM, propImpl);
609 switch (strategy.getKind()) {
610 case PropertyImplStrategy::Native: {
611 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
612
613 // Currently, all atomic accesses have to be through integer
614 // types, so there's no point in trying to pick a prettier type.
615 llvm::Type *bitcastType =
616 llvm::Type::getIntNTy(getLLVMContext(),
617 getContext().toBits(strategy.getIvarSize()));
618 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
619
620 // Perform an atomic load. This does not impose ordering constraints.
621 llvm::Value *ivarAddr = LV.getAddress();
622 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
623 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
624 load->setAlignment(strategy.getIvarAlignment().getQuantity());
625 load->setAtomic(llvm::Unordered);
626
627 // Store that value into the return address. Doing this with a
628 // bitcast is likely to produce some pretty ugly IR, but it's not
629 // the *most* terrible thing in the world.
630 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
631
632 // Make sure we don't do an autorelease.
633 AutoreleaseResult = false;
634 return;
635 }
636
637 case PropertyImplStrategy::GetSetProperty: {
638 llvm::Value *getPropertyFn =
639 CGM.getObjCRuntime().GetPropertyGetFunction();
640 if (!getPropertyFn) {
641 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000642 return;
643 }
644
645 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
646 // FIXME: Can't this be simpler? This might even be worse than the
647 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000648 llvm::Value *cmd =
649 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
650 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
651 llvm::Value *ivarOffset =
652 EmitIvarOffset(classImpl->getClassInterface(), ivar);
653
654 CallArgList args;
655 args.add(RValue::get(self), getContext().getObjCIdType());
656 args.add(RValue::get(cmd), getContext().getObjCSelType());
657 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
658
659 assert(strategy.isAtomic());
660 args.add(RValue::get(Builder.getTrue()), getContext().BoolTy);
661
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000662 // FIXME: We shouldn't need to get the function info here, the
663 // runtime already should have computed it to build the function.
John McCallf4528ae2011-09-13 03:34:09 +0000664 RValue RV = EmitCall(getTypes().getFunctionInfo(propType, args,
John McCallb923ece2011-09-12 23:06:44 +0000665 FunctionType::ExtInfo()),
John McCallf4528ae2011-09-13 03:34:09 +0000666 getPropertyFn, ReturnValueSlot(), args);
667
Daniel Dunbara08dff12008-09-24 04:04:31 +0000668 // We need to fix the type here. Ivars with copy & retain are
669 // always objects so we don't need to worry about complex or
670 // aggregates.
Mike Stump11289f42009-09-09 15:08:12 +0000671 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
John McCallf4528ae2011-09-13 03:34:09 +0000672 getTypes().ConvertType(propType)));
673
674 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000675
676 // objc_getProperty does an autorelease, so we should suppress ours.
677 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000678
John McCallf4528ae2011-09-13 03:34:09 +0000679 return;
680 }
681
682 case PropertyImplStrategy::CopyStruct:
683 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
684 strategy.hasStrongMember());
685 return;
686
687 case PropertyImplStrategy::Expression:
688 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
689 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
690
691 QualType ivarType = ivar->getType();
692 if (ivarType->isAnyComplexType()) {
693 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
694 LV.isVolatileQualified());
695 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
696 } else if (hasAggregateLLVMType(ivarType)) {
697 // The return value slot is guaranteed to not be aliased, but
698 // that's not necessarily the same as "on the stack", so
699 // we still potentially need objc_memmove_collectable.
700 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
701 } else {
John McCall24fada12011-07-22 05:23:13 +0000702 llvm::Value *value;
703 if (propType->isReferenceType()) {
704 value = LV.getAddress();
705 } else {
706 // We want to load and autoreleaseReturnValue ARC __weak ivars.
707 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000708 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000709
710 // Otherwise we want to do a simple load, suppressing the
711 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000712 } else {
John McCall24fada12011-07-22 05:23:13 +0000713 value = EmitLoadOfLValue(LV).getScalarVal();
714 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000715 }
John McCall31168b02011-06-15 23:02:42 +0000716
John McCall24fada12011-07-22 05:23:13 +0000717 value = Builder.CreateBitCast(value, ConvertType(propType));
718 }
719
720 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000721 }
John McCallf4528ae2011-09-13 03:34:09 +0000722 return;
Daniel Dunbara08dff12008-09-24 04:04:31 +0000723 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000724
John McCallf4528ae2011-09-13 03:34:09 +0000725 }
726 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000727}
728
John McCallb923ece2011-09-12 23:06:44 +0000729/// emitStructSetterCall - Call the runtime function to store the value
730/// from the first formal parameter into the given ivar.
731static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
732 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000733 // objc_copyStruct (&structIvar, &Arg,
734 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000735 CallArgList args;
736
737 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000738 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
739 CGF.LoadObjCSelf(), ivar, 0)
740 .getAddress();
741 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
742 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000743
744 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000745 ParmVarDecl *argVar = *OMD->param_begin();
746 DeclRefExpr argRef(argVar, argVar->getType(), VK_LValue, SourceLocation());
747 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
748 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
749 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000750
751 // The third argument is the sizeof the type.
752 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +0000753 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
754 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +0000755
John McCallb923ece2011-09-12 23:06:44 +0000756 // The fourth argument is the 'isAtomic' flag.
757 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +0000758
John McCallb923ece2011-09-12 23:06:44 +0000759 // The fifth argument is the 'hasStrong' flag.
760 // FIXME: should this really always be false?
761 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
762
763 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
764 CGF.EmitCall(CGF.getTypes().getFunctionInfo(CGF.getContext().VoidTy, args,
765 FunctionType::ExtInfo()),
766 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000767}
768
John McCallf4528ae2011-09-13 03:34:09 +0000769static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
770 Expr *setter = PID->getSetterCXXAssignment();
771 if (!setter) return true;
772
773 // Sema only makes only of these when the ivar has a C++ class type,
774 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +0000775
776 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +0000777 // This also implies that there's nothing non-trivial going on with
778 // the arguments, because operator= can only be trivial if it's a
779 // synthesized assignment operator and therefore both parameters are
780 // references.
781 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +0000782 if (const FunctionDecl *callee
783 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
784 if (callee->isTrivial())
785 return true;
786 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +0000787 }
John McCall7f16c422011-09-10 09:17:20 +0000788
John McCallf4528ae2011-09-13 03:34:09 +0000789 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +0000790 return false;
791}
792
John McCall7f16c422011-09-10 09:17:20 +0000793void
794CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
795 const ObjCPropertyImplDecl *propImpl) {
796 // Just use the setter expression if Sema gave us one and it's
797 // non-trivial. There's no way to do this atomically.
John McCallf4528ae2011-09-13 03:34:09 +0000798 if (!hasTrivialSetExpr(propImpl)) {
John McCall7f16c422011-09-10 09:17:20 +0000799 EmitStmt(propImpl->getSetterCXXAssignment());
800 return;
801 }
802
803 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
804 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
805 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
806
John McCallf4528ae2011-09-13 03:34:09 +0000807 PropertyImplStrategy strategy(CGM, propImpl);
808 switch (strategy.getKind()) {
809 case PropertyImplStrategy::Native: {
810 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +0000811
John McCallf4528ae2011-09-13 03:34:09 +0000812 LValue ivarLValue =
813 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
814 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +0000815
John McCallf4528ae2011-09-13 03:34:09 +0000816 // Currently, all atomic accesses have to be through integer
817 // types, so there's no point in trying to pick a prettier type.
818 llvm::Type *bitcastType =
819 llvm::Type::getIntNTy(getLLVMContext(),
820 getContext().toBits(strategy.getIvarSize()));
821 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
822
823 // Cast both arguments to the chosen operation type.
824 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
825 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
826
827 // This bitcast load is likely to cause some nasty IR.
828 llvm::Value *load = Builder.CreateLoad(argAddr);
829
830 // Perform an atomic store. There are no memory ordering requirements.
831 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
832 store->setAlignment(strategy.getIvarAlignment().getQuantity());
833 store->setAtomic(llvm::Unordered);
834 return;
835 }
836
837 case PropertyImplStrategy::GetSetProperty:
838 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
John McCall7f16c422011-09-10 09:17:20 +0000839 llvm::Value *setPropertyFn =
840 CGM.getObjCRuntime().GetPropertySetFunction();
841 if (!setPropertyFn) {
842 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
843 return;
844 }
845
846 // Emit objc_setProperty((id) self, _cmd, offset, arg,
847 // <is-atomic>, <is-copy>).
848 llvm::Value *cmd =
849 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
850 llvm::Value *self =
851 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
852 llvm::Value *ivarOffset =
853 EmitIvarOffset(classImpl->getClassInterface(), ivar);
854 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
855 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
856
857 CallArgList args;
858 args.add(RValue::get(self), getContext().getObjCIdType());
859 args.add(RValue::get(cmd), getContext().getObjCSelType());
860 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
861 args.add(RValue::get(arg), getContext().getObjCIdType());
John McCallf4528ae2011-09-13 03:34:09 +0000862 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
863 getContext().BoolTy);
864 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
865 getContext().BoolTy);
John McCall7f16c422011-09-10 09:17:20 +0000866 // FIXME: We shouldn't need to get the function info here, the runtime
867 // already should have computed it to build the function.
868 EmitCall(getTypes().getFunctionInfo(getContext().VoidTy, args,
869 FunctionType::ExtInfo()),
870 setPropertyFn, ReturnValueSlot(), args);
871 return;
872 }
873
John McCallf4528ae2011-09-13 03:34:09 +0000874 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +0000875 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +0000876 return;
John McCallf4528ae2011-09-13 03:34:09 +0000877
878 case PropertyImplStrategy::Expression:
879 break;
John McCall7f16c422011-09-10 09:17:20 +0000880 }
881
882 // Otherwise, fake up some ASTs and emit a normal assignment.
883 ValueDecl *selfDecl = setterMethod->getSelfDecl();
884 DeclRefExpr self(selfDecl, selfDecl->getType(), VK_LValue, SourceLocation());
885 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
886 selfDecl->getType(), CK_LValueToRValue, &self,
887 VK_RValue);
888 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
889 SourceLocation(), &selfLoad, true, true);
890
891 ParmVarDecl *argDecl = *setterMethod->param_begin();
892 QualType argType = argDecl->getType().getNonReferenceType();
893 DeclRefExpr arg(argDecl, argType, VK_LValue, SourceLocation());
894 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
895 argType.getUnqualifiedType(), CK_LValueToRValue,
896 &arg, VK_RValue);
897
898 // The property type can differ from the ivar type in some situations with
899 // Objective-C pointer types, we can always bit cast the RHS in these cases.
900 // The following absurdity is just to ensure well-formed IR.
901 CastKind argCK = CK_NoOp;
902 if (ivarRef.getType()->isObjCObjectPointerType()) {
903 if (argLoad.getType()->isObjCObjectPointerType())
904 argCK = CK_BitCast;
905 else if (argLoad.getType()->isBlockPointerType())
906 argCK = CK_BlockPointerToObjCPointerCast;
907 else
908 argCK = CK_CPointerToObjCPointerCast;
909 } else if (ivarRef.getType()->isBlockPointerType()) {
910 if (argLoad.getType()->isBlockPointerType())
911 argCK = CK_BitCast;
912 else
913 argCK = CK_AnyPointerToBlockPointerCast;
914 } else if (ivarRef.getType()->isPointerType()) {
915 argCK = CK_BitCast;
916 }
917 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
918 ivarRef.getType(), argCK, &argLoad,
919 VK_RValue);
920 Expr *finalArg = &argLoad;
921 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
922 argLoad.getType()))
923 finalArg = &argCast;
924
925
926 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
927 ivarRef.getType(), VK_RValue, OK_Ordinary,
928 SourceLocation());
929 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +0000930}
931
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000932/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff5a7dd782009-01-10 22:55:25 +0000933/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
934/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000935void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
936 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000937 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
938 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
939 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patele7ce5402011-05-19 23:37:41 +0000940 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000941
John McCall7f16c422011-09-10 09:17:20 +0000942 generateObjCSetterBody(IMP, PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000943
944 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +0000945}
946
John McCall6a4fa522011-03-22 07:05:39 +0000947namespace {
John McCall4bd0fb12011-07-12 16:41:08 +0000948 struct DestroyIvar : EHScopeStack::Cleanup {
949 private:
950 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +0000951 const ObjCIvarDecl *ivar;
John McCall4bd0fb12011-07-12 16:41:08 +0000952 CodeGenFunction::Destroyer &destroyer;
953 bool useEHCleanupForArray;
954 public:
955 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
956 CodeGenFunction::Destroyer *destroyer,
957 bool useEHCleanupForArray)
958 : addr(addr), ivar(ivar), destroyer(*destroyer),
959 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +0000960
John McCall30317fd2011-07-12 20:27:29 +0000961 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +0000962 LValue lvalue
963 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
964 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +0000965 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +0000966 }
967 };
968}
969
John McCall4bd0fb12011-07-12 16:41:08 +0000970/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
971static void destroyARCStrongWithStore(CodeGenFunction &CGF,
972 llvm::Value *addr,
973 QualType type) {
974 llvm::Value *null = getNullForVariable(addr);
975 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
976}
John McCall31168b02011-06-15 23:02:42 +0000977
John McCall6a4fa522011-03-22 07:05:39 +0000978static void emitCXXDestructMethod(CodeGenFunction &CGF,
979 ObjCImplementationDecl *impl) {
980 CodeGenFunction::RunCleanupsScope scope(CGF);
981
982 llvm::Value *self = CGF.LoadObjCSelf();
983
Jordy Rosea91768e2011-07-22 02:08:32 +0000984 const ObjCInterfaceDecl *iface = impl->getClassInterface();
985 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +0000986 ivar; ivar = ivar->getNextIvar()) {
987 QualType type = ivar->getType();
988
John McCall6a4fa522011-03-22 07:05:39 +0000989 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +0000990 QualType::DestructionKind dtorKind = type.isDestructedType();
991 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +0000992
John McCall4bd0fb12011-07-12 16:41:08 +0000993 CodeGenFunction::Destroyer *destroyer = 0;
John McCall6a4fa522011-03-22 07:05:39 +0000994
John McCall4bd0fb12011-07-12 16:41:08 +0000995 // Use a call to objc_storeStrong to destroy strong ivars, for the
996 // general benefit of the tools.
997 if (dtorKind == QualType::DK_objc_strong_lifetime) {
998 destroyer = &destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +0000999
John McCall4bd0fb12011-07-12 16:41:08 +00001000 // Otherwise use the default for the destruction kind.
1001 } else {
1002 destroyer = &CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001003 }
John McCall4bd0fb12011-07-12 16:41:08 +00001004
1005 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1006
1007 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1008 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001009 }
1010
1011 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1012}
1013
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001014void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1015 ObjCMethodDecl *MD,
1016 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001017 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001018 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001019
1020 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001021 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001022 // Suppress the final autorelease in ARC.
1023 AutoreleaseResult = false;
1024
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001025 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCall6a4fa522011-03-22 07:05:39 +00001026 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1027 E = IMP->init_end(); B != E; ++B) {
1028 CXXCtorInitializer *IvarInit = (*B);
Francois Pichetd583da02010-12-04 09:14:42 +00001029 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001030 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001031 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1032 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001033 EmitAggExpr(IvarInit->getInit(),
1034 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001035 AggValueSlot::DoesNotNeedGCBarriers,
1036 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001037 }
1038 // constructor returns 'self'.
1039 CodeGenTypes &Types = CGM.getTypes();
1040 QualType IdTy(CGM.getContext().getObjCIdType());
1041 llvm::Value *SelfAsId =
1042 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1043 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001044
1045 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001046 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001047 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001048 }
1049 FinishFunction();
1050}
1051
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001052bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1053 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1054 it++; it++;
1055 const ABIArgInfo &AI = it->info;
1056 // FIXME. Is this sufficient check?
1057 return (AI.getKind() == ABIArgInfo::Indirect);
1058}
1059
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001060bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1061 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
1062 return false;
1063 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1064 return FDTTy->getDecl()->hasObjectMember();
1065 return false;
1066}
1067
Daniel Dunbara08dff12008-09-24 04:04:31 +00001068llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001069 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1070 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner5696e7b2008-06-17 18:05:57 +00001071}
1072
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001073QualType CodeGenFunction::TypeOfSelfObject() {
1074 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1075 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001076 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1077 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001078 return PTy->getPointeeType();
1079}
1080
John McCall0692a322010-12-04 03:11:00 +00001081LValue
1082CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
1083 // This is a special l-value that just issues sends when we load or
1084 // store through it.
1085
1086 // For certain base kinds, we need to emit the base immediately.
1087 llvm::Value *Base;
1088 if (E->isSuperReceiver())
1089 Base = LoadObjCSelf();
1090 else if (E->isClassReceiver())
1091 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
1092 else
1093 Base = EmitScalarExpr(E->getBase());
1094 return LValue::MakePropertyRef(E, Base);
1095}
1096
1097static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
1098 ReturnValueSlot Return,
1099 QualType ResultType,
1100 Selector S,
1101 llvm::Value *Receiver,
1102 const CallArgList &CallArgs) {
1103 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanian391d4fc2009-03-20 19:18:21 +00001104 bool isClassMessage = OMD->isClassMethod();
1105 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCall0692a322010-12-04 03:11:00 +00001106 return CGF.CGM.getObjCRuntime()
1107 .GenerateMessageSendSuper(CGF, Return, ResultType,
1108 S, OMD->getClassInterface(),
1109 isCategoryImpl, Receiver,
1110 isClassMessage, CallArgs);
Fariborz Jahanian391d4fc2009-03-20 19:18:21 +00001111}
1112
John McCallf3eb96f2010-12-04 02:32:38 +00001113RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
1114 ReturnValueSlot Return) {
1115 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian7a26ba42011-03-30 16:11:20 +00001116 QualType ResultType = E->getGetterResultType();
John McCallb7bd14f2010-12-02 01:19:52 +00001117 Selector S;
Douglas Gregor33823722011-06-11 01:09:30 +00001118 const ObjCMethodDecl *method;
John McCallb7bd14f2010-12-02 01:19:52 +00001119 if (E->isExplicitProperty()) {
1120 const ObjCPropertyDecl *Property = E->getExplicitProperty();
1121 S = Property->getGetterName();
Douglas Gregor33823722011-06-11 01:09:30 +00001122 method = Property->getGetterMethodDecl();
Mike Stump658fe022009-07-30 22:28:39 +00001123 } else {
Douglas Gregor33823722011-06-11 01:09:30 +00001124 method = E->getImplicitPropertyGetter();
1125 S = method->getSelector();
Fariborz Jahanian9ac53512008-11-22 22:30:21 +00001126 }
John McCallb7bd14f2010-12-02 01:19:52 +00001127
John McCallf3eb96f2010-12-04 02:32:38 +00001128 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCall0692a322010-12-04 03:11:00 +00001129
John McCall31168b02011-06-15 23:02:42 +00001130 if (CGM.getLangOptions().ObjCAutoRefCount) {
1131 QualType receiverType;
1132 if (E->isSuperReceiver())
1133 receiverType = E->getSuperReceiverType();
1134 else if (E->isClassReceiver())
1135 receiverType = getContext().getObjCClassType();
1136 else
1137 receiverType = E->getBase()->getType();
1138 }
1139
John McCall0692a322010-12-04 03:11:00 +00001140 // Accesses to 'super' follow a different code path.
1141 if (E->isSuperReceiver())
Douglas Gregor33823722011-06-11 01:09:30 +00001142 return AdjustRelatedResultType(*this, E, method,
1143 GenerateMessageSendSuper(*this, Return,
1144 ResultType,
1145 S, Receiver,
1146 CallArgList()));
John McCallf3eb96f2010-12-04 02:32:38 +00001147 const ObjCInterfaceDecl *ReceiverClass
1148 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor33823722011-06-11 01:09:30 +00001149 return AdjustRelatedResultType(*this, E, method,
John McCall31168b02011-06-15 23:02:42 +00001150 CGM.getObjCRuntime().
1151 GenerateMessageSend(*this, Return, ResultType, S,
1152 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar55310df2008-08-27 06:57:25 +00001153}
1154
John McCallf3eb96f2010-12-04 02:32:38 +00001155void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
1156 LValue Dst) {
1157 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCallb7bd14f2010-12-02 01:19:52 +00001158 Selector S = E->getSetterSelector();
Fariborz Jahanian7a26ba42011-03-30 16:11:20 +00001159 QualType ArgType = E->getSetterArgType();
1160
Fariborz Jahanian701f0942011-02-08 22:33:23 +00001161 // FIXME. Other than scalars, AST is not adequate for setter and
1162 // getter type mismatches which require conversion.
1163 if (Src.isScalar()) {
1164 llvm::Value *SrcVal = Src.getScalarVal();
1165 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2192fe52011-07-18 04:24:23 +00001166 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanian701f0942011-02-08 22:33:23 +00001167 if (SrcVal->getType() != DstTy)
1168 Src =
1169 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
1170 }
1171
John McCall0692a322010-12-04 03:11:00 +00001172 CallArgList Args;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001173 Args.add(Src, ArgType);
John McCall0692a322010-12-04 03:11:00 +00001174
1175 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
1176 QualType ResultType = getContext().VoidTy;
1177
John McCallb7bd14f2010-12-02 01:19:52 +00001178 if (E->isSuperReceiver()) {
John McCall0692a322010-12-04 03:11:00 +00001179 GenerateMessageSendSuper(*this, ReturnValueSlot(),
1180 ResultType, S, Receiver, Args);
John McCallb7bd14f2010-12-02 01:19:52 +00001181 return;
1182 }
1183
John McCallf3eb96f2010-12-04 02:32:38 +00001184 const ObjCInterfaceDecl *ReceiverClass
1185 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCallb7bd14f2010-12-02 01:19:52 +00001186
John McCallb7bd14f2010-12-02 01:19:52 +00001187 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCall0692a322010-12-04 03:11:00 +00001188 ResultType, S, Receiver, Args,
1189 ReceiverClass);
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +00001190}
1191
Chris Lattnerd4808922009-03-22 21:03:39 +00001192void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001193 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001194 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001195
Daniel Dunbara08dff12008-09-24 04:04:31 +00001196 if (!EnumerationMutationFn) {
1197 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1198 return;
1199 }
1200
Devang Pateld2d66652011-01-19 01:36:36 +00001201 CGDebugInfo *DI = getDebugInfo();
1202 if (DI) {
1203 DI->setLocation(S.getSourceRange().getBegin());
1204 DI->EmitRegionStart(Builder);
1205 }
1206
Devang Patel297207f2011-06-13 23:15:32 +00001207 // The local variable comes into scope immediately.
1208 AutoVarEmission variable = AutoVarEmission::invalid();
1209 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1210 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1211
John McCall1c926b72011-01-07 01:49:06 +00001212 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001213
Anders Carlsson75658592008-08-31 02:33:12 +00001214 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001215 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001216 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001217 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001218
Anders Carlsson75658592008-08-31 02:33:12 +00001219 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001220 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001221
John McCall1c926b72011-01-07 01:49:06 +00001222 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001223 IdentifierInfo *II[] = {
1224 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1225 &CGM.getContext().Idents.get("objects"),
1226 &CGM.getContext().Idents.get("count")
1227 };
1228 Selector FastEnumSel =
1229 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001230
1231 QualType ItemsTy =
1232 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001233 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001234 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001235 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001236
John McCall53848232011-07-27 01:07:15 +00001237 // Emit the collection pointer. In ARC, we do a retain.
1238 llvm::Value *Collection;
1239 if (getLangOptions().ObjCAutoRefCount) {
1240 Collection = EmitARCRetainScalarExpr(S.getCollection());
1241
1242 // Enter a cleanup to do the release.
1243 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1244 } else {
1245 Collection = EmitScalarExpr(S.getCollection());
1246 }
Mike Stump11289f42009-09-09 15:08:12 +00001247
John McCall91e82dd2011-08-05 00:14:38 +00001248 // The 'continue' label needs to appear within the cleanup for the
1249 // collection object.
1250 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1251
John McCall1c926b72011-01-07 01:49:06 +00001252 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001253 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001254
1255 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001256 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001257
John McCall1c926b72011-01-07 01:49:06 +00001258 // The second argument is a temporary array with space for NumItems
1259 // pointers. We'll actually be loading elements from the array
1260 // pointer written into the control state; this buffer is so that
1261 // collections that *aren't* backed by arrays can still queue up
1262 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001263 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001264
John McCall1c926b72011-01-07 01:49:06 +00001265 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001266 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001267 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001268 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001269
John McCall1c926b72011-01-07 01:49:06 +00001270 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001271 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001272 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001273 getContext().UnsignedLongTy,
1274 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001275 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001276
John McCall1c926b72011-01-07 01:49:06 +00001277 // The initial number of objects that were returned in the buffer.
1278 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001279
John McCall1c926b72011-01-07 01:49:06 +00001280 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1281 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001282
John McCall1c926b72011-01-07 01:49:06 +00001283 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001284
John McCall1c926b72011-01-07 01:49:06 +00001285 // If the limit pointer was zero to begin with, the collection is
1286 // empty; skip all this.
1287 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1288 EmptyBB, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001289
John McCall1c926b72011-01-07 01:49:06 +00001290 // Otherwise, initialize the loop.
1291 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCall1c926b72011-01-07 01:49:06 +00001293 // Save the initial mutations value. This is the value at an
1294 // address that was written into the state object by
1295 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001296 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001297 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001298 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001299 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001300
John McCall1c926b72011-01-07 01:49:06 +00001301 llvm::Value *initialMutations =
1302 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001303
John McCall1c926b72011-01-07 01:49:06 +00001304 // Start looping. This is the point we return to whenever we have a
1305 // fresh, non-empty batch of objects.
1306 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1307 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001308
John McCall1c926b72011-01-07 01:49:06 +00001309 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001310 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001311 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001312
John McCall1c926b72011-01-07 01:49:06 +00001313 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001314 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001315 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001316
John McCall1c926b72011-01-07 01:49:06 +00001317 // Check whether the mutations value has changed from where it was
1318 // at start. StateMutationsPtr should actually be invariant between
1319 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001320 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001321 llvm::Value *currentMutations
1322 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001323
John McCall1c926b72011-01-07 01:49:06 +00001324 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001325 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001326
John McCall1c926b72011-01-07 01:49:06 +00001327 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1328 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001329
John McCall1c926b72011-01-07 01:49:06 +00001330 // If so, call the enumeration-mutation function.
1331 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001332 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001333 Builder.CreateBitCast(Collection,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001334 ConvertType(getContext().getObjCIdType()),
1335 "tmp");
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001336 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001337 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001338 // FIXME: We shouldn't need to get the function info here, the runtime already
1339 // should have computed it to build the function.
John McCallab26cfa2010-02-05 21:31:56 +00001340 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001341 FunctionType::ExtInfo()),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001342 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001343
John McCall1c926b72011-01-07 01:49:06 +00001344 // Otherwise, or if the mutation function returns, just continue.
1345 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001346
John McCall1c926b72011-01-07 01:49:06 +00001347 // Initialize the element variable.
1348 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001349 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001350 LValue elementLValue;
1351 QualType elementType;
1352 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001353 // Initialize the variable, in case it's a __block variable or something.
1354 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001355
John McCall9e2e22f2011-02-22 07:16:58 +00001356 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall1c926b72011-01-07 01:49:06 +00001357 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1358 VK_LValue, SourceLocation());
1359 elementLValue = EmitLValue(&tempDRE);
1360 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001361 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001362
1363 if (D->isARCPseudoStrong())
1364 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001365 } else {
1366 elementLValue = LValue(); // suppress warning
1367 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001368 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001369 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001370 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001371
1372 // Fetch the buffer out of the enumeration state.
1373 // TODO: this pointer should actually be invariant between
1374 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001375 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001376 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001377 llvm::Value *EnumStateItems =
1378 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001379
John McCall1c926b72011-01-07 01:49:06 +00001380 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001381 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001382 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1383 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001384
John McCall1c926b72011-01-07 01:49:06 +00001385 // Cast that value to the right type.
1386 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1387 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001388
John McCall1c926b72011-01-07 01:49:06 +00001389 // Make sure we have an l-value. Yes, this gets evaluated every
1390 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001391 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001392 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001393 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001394 } else {
1395 EmitScalarInit(CurrentItem, elementLValue);
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
John McCall9e2e22f2011-02-22 07:16:58 +00001398 // If we do have an element variable, this assignment is the end of
1399 // its initialization.
1400 if (elementIsVariable)
1401 EmitAutoVarCleanups(variable);
1402
John McCall1c926b72011-01-07 01:49:06 +00001403 // Perform the loop body, setting up break and continue labels.
Anders Carlsson33747b62009-02-10 05:52:02 +00001404 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001405 {
1406 RunCleanupsScope Scope(*this);
1407 EmitStmt(S.getBody());
1408 }
Anders Carlsson75658592008-08-31 02:33:12 +00001409 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001410
John McCall1c926b72011-01-07 01:49:06 +00001411 // Destroy the element variable now.
1412 elementVariableScope.ForceCleanup();
1413
1414 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001415 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001416
John McCall1c926b72011-01-07 01:49:06 +00001417 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001418
John McCall1c926b72011-01-07 01:49:06 +00001419 // First we check in the local buffer.
1420 llvm::Value *indexPlusOne
1421 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001422
John McCall1c926b72011-01-07 01:49:06 +00001423 // If we haven't overrun the buffer yet, we can continue.
1424 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1425 LoopBodyBB, FetchMoreBB);
1426
1427 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1428 count->addIncoming(count, AfterBody.getBlock());
1429
1430 // Otherwise, we have to fetch more elements.
1431 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001432
1433 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001434 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001435 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001436 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001437 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001438
John McCall1c926b72011-01-07 01:49:06 +00001439 // If we got a zero count, we're done.
1440 llvm::Value *refetchCount = CountRV.getScalarVal();
1441
1442 // (note that the message send might split FetchMoreBB)
1443 index->addIncoming(zero, Builder.GetInsertBlock());
1444 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1445
1446 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1447 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001448
Anders Carlsson75658592008-08-31 02:33:12 +00001449 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001450 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001451
John McCall9e2e22f2011-02-22 07:16:58 +00001452 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001453 // If the element was not a declaration, set it to be null.
1454
John McCall1c926b72011-01-07 01:49:06 +00001455 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1456 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001457 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001458 }
1459
Devang Pateld2d66652011-01-19 01:36:36 +00001460 if (DI) {
1461 DI->setLocation(S.getSourceRange().getEnd());
1462 DI->EmitRegionEnd(Builder);
1463 }
1464
John McCall53848232011-07-27 01:07:15 +00001465 // Leave the cleanup we entered in ARC.
1466 if (getLangOptions().ObjCAutoRefCount)
1467 PopCleanupBlock();
1468
John McCallad5d61e2010-07-23 21:56:41 +00001469 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001470}
1471
Mike Stump11289f42009-09-09 15:08:12 +00001472void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001473 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001474}
1475
Mike Stump11289f42009-09-09 15:08:12 +00001476void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001477 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1478}
1479
Chris Lattnere132e242008-11-15 21:26:17 +00001480void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001481 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001482 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001483}
1484
John McCall2d637d22011-09-10 06:18:15 +00001485/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001486/// primitive retain.
1487llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1488 llvm::Value *value) {
1489 return EmitARCRetain(type, value);
1490}
1491
1492namespace {
1493 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001494 CallObjCRelease(llvm::Value *object) : object(object) {}
1495 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001496
John McCall30317fd2011-07-12 20:27:29 +00001497 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00001498 CGF.EmitARCRelease(object, /*precise*/ true);
John McCall31168b02011-06-15 23:02:42 +00001499 }
1500 };
1501}
1502
John McCall2d637d22011-09-10 06:18:15 +00001503/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001504/// release at the end of the full-expression.
1505llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1506 llvm::Value *object) {
1507 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001508 // conditional.
1509 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001510 return object;
1511}
1512
1513llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1514 llvm::Value *value) {
1515 return EmitARCRetainAutorelease(type, value);
1516}
1517
1518
1519static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001520 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001521 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001522 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1523
1524 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1525 // support library.
John McCall24fc0de2011-07-06 00:26:06 +00001526 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCall31168b02011-06-15 23:02:42 +00001527 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1528 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1529
1530 return fn;
1531}
1532
1533/// Perform an operation having the signature
1534/// i8* (i8*)
1535/// where a null input causes a no-op and returns null.
1536static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1537 llvm::Value *value,
1538 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001539 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001540 if (isa<llvm::ConstantPointerNull>(value)) return value;
1541
1542 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001543 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001544 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001545 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1546 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1547 }
1548
1549 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001550 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001551 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1552
1553 // Call the function.
1554 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1555 call->setDoesNotThrow();
1556
1557 // Cast the result back to the original type.
1558 return CGF.Builder.CreateBitCast(call, origType);
1559}
1560
1561/// Perform an operation having the following signature:
1562/// i8* (i8**)
1563static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1564 llvm::Value *addr,
1565 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001566 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001567 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001568 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001569 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001570 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1571 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1572 }
1573
1574 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001575 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001576 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1577
1578 // Call the function.
1579 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1580 call->setDoesNotThrow();
1581
1582 // Cast the result back to a dereference of the original type.
1583 llvm::Value *result = call;
1584 if (origType != CGF.Int8PtrPtrTy)
1585 result = CGF.Builder.CreateBitCast(result,
1586 cast<llvm::PointerType>(origType)->getElementType());
1587
1588 return result;
1589}
1590
1591/// Perform an operation having the following signature:
1592/// i8* (i8**, i8*)
1593static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1594 llvm::Value *addr,
1595 llvm::Value *value,
1596 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001597 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001598 bool ignored) {
1599 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1600 == value->getType());
1601
1602 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001603 std::vector<llvm::Type*> argTypes(2);
John McCall31168b02011-06-15 23:02:42 +00001604 argTypes[0] = CGF.Int8PtrPtrTy;
1605 argTypes[1] = CGF.Int8PtrTy;
1606
Chris Lattner2192fe52011-07-18 04:24:23 +00001607 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001608 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1609 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1610 }
1611
Chris Lattner2192fe52011-07-18 04:24:23 +00001612 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001613
1614 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1615 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1616
1617 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1618 result->setDoesNotThrow();
1619
1620 if (ignored) return 0;
1621
1622 return CGF.Builder.CreateBitCast(result, origType);
1623}
1624
1625/// Perform an operation having the following signature:
1626/// void (i8**, i8**)
1627static void emitARCCopyOperation(CodeGenFunction &CGF,
1628 llvm::Value *dst,
1629 llvm::Value *src,
1630 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001631 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001632 assert(dst->getType() == src->getType());
1633
1634 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001635 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001636 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001637 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1638 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1639 }
1640
1641 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1642 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1643
1644 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1645 result->setDoesNotThrow();
1646}
1647
1648/// Produce the code to do a retain. Based on the type, calls one of:
1649/// call i8* @objc_retain(i8* %value)
1650/// call i8* @objc_retainBlock(i8* %value)
1651llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1652 if (type->isBlockPointerType())
1653 return EmitARCRetainBlock(value);
1654 else
1655 return EmitARCRetainNonBlock(value);
1656}
1657
1658/// Retain the given object, with normal retain semantics.
1659/// call i8* @objc_retain(i8* %value)
1660llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1661 return emitARCValueOperation(*this, value,
1662 CGM.getARCEntrypoints().objc_retain,
1663 "objc_retain");
1664}
1665
1666/// Retain the given block, with _Block_copy semantics.
1667/// call i8* @objc_retainBlock(i8* %value)
1668llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1669 return emitARCValueOperation(*this, value,
1670 CGM.getARCEntrypoints().objc_retainBlock,
1671 "objc_retainBlock");
1672}
1673
1674/// Retain the given object which is the result of a function call.
1675/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1676///
1677/// Yes, this function name is one character away from a different
1678/// call with completely different semantics.
1679llvm::Value *
1680CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1681 // Fetch the void(void) inline asm which marks that we're going to
1682 // retain the autoreleased return value.
1683 llvm::InlineAsm *&marker
1684 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1685 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001686 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001687 = CGM.getTargetCodeGenInfo()
1688 .getARCRetainAutoreleasedReturnValueMarker();
1689
1690 // If we have an empty assembly string, there's nothing to do.
1691 if (assembly.empty()) {
1692
1693 // Otherwise, at -O0, build an inline asm that we're going to call
1694 // in a moment.
1695 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1696 llvm::FunctionType *type =
1697 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1698 /*variadic*/ false);
1699
1700 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1701
1702 // If we're at -O1 and above, we don't want to litter the code
1703 // with this marker yet, so leave a breadcrumb for the ARC
1704 // optimizer to pick up.
1705 } else {
1706 llvm::NamedMDNode *metadata =
1707 CGM.getModule().getOrInsertNamedMetadata(
1708 "clang.arc.retainAutoreleasedReturnValueMarker");
1709 assert(metadata->getNumOperands() <= 1);
1710 if (metadata->getNumOperands() == 0) {
1711 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00001712 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00001713 }
1714 }
1715 }
1716
1717 // Call the marker asm if we made one, which we do only at -O0.
1718 if (marker) Builder.CreateCall(marker);
1719
1720 return emitARCValueOperation(*this, value,
1721 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1722 "objc_retainAutoreleasedReturnValue");
1723}
1724
1725/// Release the given object.
1726/// call void @objc_release(i8* %value)
1727void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1728 if (isa<llvm::ConstantPointerNull>(value)) return;
1729
1730 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1731 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001732 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001733 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001734 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1735 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1736 }
1737
1738 // Cast the argument to 'id'.
1739 value = Builder.CreateBitCast(value, Int8PtrTy);
1740
1741 // Call objc_release.
1742 llvm::CallInst *call = Builder.CreateCall(fn, value);
1743 call->setDoesNotThrow();
1744
1745 if (!precise) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001746 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00001747 call->setMetadata("clang.imprecise_release",
1748 llvm::MDNode::get(Builder.getContext(), args));
1749 }
1750}
1751
1752/// Store into a strong object. Always calls this:
1753/// call void @objc_storeStrong(i8** %addr, i8* %value)
1754llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1755 llvm::Value *value,
1756 bool ignored) {
1757 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1758 == value->getType());
1759
1760 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1761 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001762 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00001763 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001764 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1765 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1766 }
1767
1768 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1769 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1770
1771 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1772
1773 if (ignored) return 0;
1774 return value;
1775}
1776
1777/// Store into a strong object. Sometimes calls this:
1778/// call void @objc_storeStrong(i8** %addr, i8* %value)
1779/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00001780llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00001781 llvm::Value *newValue,
1782 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00001783 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00001784 bool isBlock = type->isBlockPointerType();
1785
1786 // Use a store barrier at -O0 unless this is a block type or the
1787 // lvalue is inadequately aligned.
1788 if (shouldUseFusedARCCalls() &&
1789 !isBlock &&
1790 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1791 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1792 }
1793
1794 // Otherwise, split it out.
1795
1796 // Retain the new value.
1797 newValue = EmitARCRetain(type, newValue);
1798
1799 // Read the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001800 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCall31168b02011-06-15 23:02:42 +00001801
1802 // Store. We do this before the release so that any deallocs won't
1803 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001804 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00001805
1806 // Finally, release the old value.
1807 EmitARCRelease(oldValue, /*precise*/ false);
1808
1809 return newValue;
1810}
1811
1812/// Autorelease the given object.
1813/// call i8* @objc_autorelease(i8* %value)
1814llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1815 return emitARCValueOperation(*this, value,
1816 CGM.getARCEntrypoints().objc_autorelease,
1817 "objc_autorelease");
1818}
1819
1820/// Autorelease the given object.
1821/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1822llvm::Value *
1823CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1824 return emitARCValueOperation(*this, value,
1825 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1826 "objc_autoreleaseReturnValue");
1827}
1828
1829/// Do a fused retain/autorelease of the given object.
1830/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1831llvm::Value *
1832CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1833 return emitARCValueOperation(*this, value,
1834 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1835 "objc_retainAutoreleaseReturnValue");
1836}
1837
1838/// Do a fused retain/autorelease of the given object.
1839/// call i8* @objc_retainAutorelease(i8* %value)
1840/// or
1841/// %retain = call i8* @objc_retainBlock(i8* %value)
1842/// call i8* @objc_autorelease(i8* %retain)
1843llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1844 llvm::Value *value) {
1845 if (!type->isBlockPointerType())
1846 return EmitARCRetainAutoreleaseNonBlock(value);
1847
1848 if (isa<llvm::ConstantPointerNull>(value)) return value;
1849
Chris Lattner2192fe52011-07-18 04:24:23 +00001850 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001851 value = Builder.CreateBitCast(value, Int8PtrTy);
1852 value = EmitARCRetainBlock(value);
1853 value = EmitARCAutorelease(value);
1854 return Builder.CreateBitCast(value, origType);
1855}
1856
1857/// Do a fused retain/autorelease of the given object.
1858/// call i8* @objc_retainAutorelease(i8* %value)
1859llvm::Value *
1860CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1861 return emitARCValueOperation(*this, value,
1862 CGM.getARCEntrypoints().objc_retainAutorelease,
1863 "objc_retainAutorelease");
1864}
1865
1866/// i8* @objc_loadWeak(i8** %addr)
1867/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1868llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1869 return emitARCLoadOperation(*this, addr,
1870 CGM.getARCEntrypoints().objc_loadWeak,
1871 "objc_loadWeak");
1872}
1873
1874/// i8* @objc_loadWeakRetained(i8** %addr)
1875llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1876 return emitARCLoadOperation(*this, addr,
1877 CGM.getARCEntrypoints().objc_loadWeakRetained,
1878 "objc_loadWeakRetained");
1879}
1880
1881/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1882/// Returns %value.
1883llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1884 llvm::Value *value,
1885 bool ignored) {
1886 return emitARCStoreOperation(*this, addr, value,
1887 CGM.getARCEntrypoints().objc_storeWeak,
1888 "objc_storeWeak", ignored);
1889}
1890
1891/// i8* @objc_initWeak(i8** %addr, i8* %value)
1892/// Returns %value. %addr is known to not have a current weak entry.
1893/// Essentially equivalent to:
1894/// *addr = nil; objc_storeWeak(addr, value);
1895void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1896 // If we're initializing to null, just write null to memory; no need
1897 // to get the runtime involved. But don't do this if optimization
1898 // is enabled, because accounting for this would make the optimizer
1899 // much more complicated.
1900 if (isa<llvm::ConstantPointerNull>(value) &&
1901 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1902 Builder.CreateStore(value, addr);
1903 return;
1904 }
1905
1906 emitARCStoreOperation(*this, addr, value,
1907 CGM.getARCEntrypoints().objc_initWeak,
1908 "objc_initWeak", /*ignored*/ true);
1909}
1910
1911/// void @objc_destroyWeak(i8** %addr)
1912/// Essentially objc_storeWeak(addr, nil).
1913void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1914 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1915 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001916 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001917 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001918 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1919 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1920 }
1921
1922 // Cast the argument to 'id*'.
1923 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1924
1925 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1926 call->setDoesNotThrow();
1927}
1928
1929/// void @objc_moveWeak(i8** %dest, i8** %src)
1930/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1931/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1932void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1933 emitARCCopyOperation(*this, dst, src,
1934 CGM.getARCEntrypoints().objc_moveWeak,
1935 "objc_moveWeak");
1936}
1937
1938/// void @objc_copyWeak(i8** %dest, i8** %src)
1939/// Disregards the current value in %dest. Essentially
1940/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1941void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1942 emitARCCopyOperation(*this, dst, src,
1943 CGM.getARCEntrypoints().objc_copyWeak,
1944 "objc_copyWeak");
1945}
1946
1947/// Produce the code to do a objc_autoreleasepool_push.
1948/// call i8* @objc_autoreleasePoolPush(void)
1949llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1950 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1951 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001952 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001953 llvm::FunctionType::get(Int8PtrTy, false);
1954 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1955 }
1956
1957 llvm::CallInst *call = Builder.CreateCall(fn);
1958 call->setDoesNotThrow();
1959
1960 return call;
1961}
1962
1963/// Produce the code to do a primitive release.
1964/// call void @objc_autoreleasePoolPop(i8* %ptr)
1965void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1966 assert(value->getType() == Int8PtrTy);
1967
1968 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1969 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001970 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001971 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001972 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1973
1974 // We don't want to use a weak import here; instead we should not
1975 // fall into this path.
1976 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1977 }
1978
1979 llvm::CallInst *call = Builder.CreateCall(fn, value);
1980 call->setDoesNotThrow();
1981}
1982
1983/// Produce the code to do an MRR version objc_autoreleasepool_push.
1984/// Which is: [[NSAutoreleasePool alloc] init];
1985/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1986/// init is declared as: - (id) init; in its NSObject super class.
1987///
1988llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1989 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1990 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1991 // [NSAutoreleasePool alloc]
1992 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1993 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1994 CallArgList Args;
1995 RValue AllocRV =
1996 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1997 getContext().getObjCIdType(),
1998 AllocSel, Receiver, Args);
1999
2000 // [Receiver init]
2001 Receiver = AllocRV.getScalarVal();
2002 II = &CGM.getContext().Idents.get("init");
2003 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2004 RValue InitRV =
2005 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2006 getContext().getObjCIdType(),
2007 InitSel, Receiver, Args);
2008 return InitRV.getScalarVal();
2009}
2010
2011/// Produce the code to do a primitive release.
2012/// [tmp drain];
2013void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2014 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2015 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2016 CallArgList Args;
2017 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2018 getContext().VoidTy, DrainSel, Arg, Args);
2019}
2020
John McCall82fe67b2011-07-09 01:37:26 +00002021void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2022 llvm::Value *addr,
2023 QualType type) {
2024 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2025 CGF.EmitARCRelease(ptr, /*precise*/ true);
2026}
2027
2028void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2029 llvm::Value *addr,
2030 QualType type) {
2031 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2032 CGF.EmitARCRelease(ptr, /*precise*/ false);
2033}
2034
2035void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2036 llvm::Value *addr,
2037 QualType type) {
2038 CGF.EmitARCDestroyWeak(addr);
2039}
2040
John McCall31168b02011-06-15 23:02:42 +00002041namespace {
John McCall31168b02011-06-15 23:02:42 +00002042 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2043 llvm::Value *Token;
2044
2045 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2046
John McCall30317fd2011-07-12 20:27:29 +00002047 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002048 CGF.EmitObjCAutoreleasePoolPop(Token);
2049 }
2050 };
2051 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2052 llvm::Value *Token;
2053
2054 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2055
John McCall30317fd2011-07-12 20:27:29 +00002056 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002057 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2058 }
2059 };
2060}
2061
2062void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2063 if (CGM.getLangOptions().ObjCAutoRefCount)
2064 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2065 else
2066 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2067}
2068
John McCall31168b02011-06-15 23:02:42 +00002069static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2070 LValue lvalue,
2071 QualType type) {
2072 switch (type.getObjCLifetime()) {
2073 case Qualifiers::OCL_None:
2074 case Qualifiers::OCL_ExplicitNone:
2075 case Qualifiers::OCL_Strong:
2076 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00002077 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002078 false);
2079
2080 case Qualifiers::OCL_Weak:
2081 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2082 true);
2083 }
2084
2085 llvm_unreachable("impossible lifetime!");
2086 return TryEmitResult();
2087}
2088
2089static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2090 const Expr *e) {
2091 e = e->IgnoreParens();
2092 QualType type = e->getType();
2093
John McCall154a2fd2011-08-30 00:57:29 +00002094 // If we're loading retained from a __strong xvalue, we can avoid
2095 // an extra retain/release pair by zeroing out the source of this
2096 // "move" operation.
2097 if (e->isXValue() &&
2098 !type.isConstQualified() &&
2099 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2100 // Emit the lvalue.
2101 LValue lv = CGF.EmitLValue(e);
2102
2103 // Load the object pointer.
2104 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2105
2106 // Set the source pointer to NULL.
2107 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2108
2109 return TryEmitResult(result, true);
2110 }
2111
John McCall31168b02011-06-15 23:02:42 +00002112 // As a very special optimization, in ARC++, if the l-value is the
2113 // result of a non-volatile assignment, do a simple retain of the
2114 // result of the call to objc_storeWeak instead of reloading.
2115 if (CGF.getLangOptions().CPlusPlus &&
2116 !type.isVolatileQualified() &&
2117 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2118 isa<BinaryOperator>(e) &&
2119 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2120 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2121
2122 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2123}
2124
2125static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2126 llvm::Value *value);
2127
2128/// Given that the given expression is some sort of call (which does
2129/// not return retained), emit a retain following it.
2130static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2131 llvm::Value *value = CGF.EmitScalarExpr(e);
2132 return emitARCRetainAfterCall(CGF, value);
2133}
2134
2135static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2136 llvm::Value *value) {
2137 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2138 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2139
2140 // Place the retain immediately following the call.
2141 CGF.Builder.SetInsertPoint(call->getParent(),
2142 ++llvm::BasicBlock::iterator(call));
2143 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2144
2145 CGF.Builder.restoreIP(ip);
2146 return value;
2147 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2148 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2149
2150 // Place the retain at the beginning of the normal destination block.
2151 llvm::BasicBlock *BB = invoke->getNormalDest();
2152 CGF.Builder.SetInsertPoint(BB, BB->begin());
2153 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2154
2155 CGF.Builder.restoreIP(ip);
2156 return value;
2157
2158 // Bitcasts can arise because of related-result returns. Rewrite
2159 // the operand.
2160 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2161 llvm::Value *operand = bitcast->getOperand(0);
2162 operand = emitARCRetainAfterCall(CGF, operand);
2163 bitcast->setOperand(0, operand);
2164 return bitcast;
2165
2166 // Generic fall-back case.
2167 } else {
2168 // Retain using the non-block variant: we never need to do a copy
2169 // of a block that's been returned to us.
2170 return CGF.EmitARCRetainNonBlock(value);
2171 }
2172}
2173
John McCallcd78e802011-09-10 01:16:55 +00002174/// Determine whether it might be important to emit a separate
2175/// objc_retain_block on the result of the given expression, or
2176/// whether it's okay to just emit it in a +1 context.
2177static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2178 assert(e->getType()->isBlockPointerType());
2179 e = e->IgnoreParens();
2180
2181 // For future goodness, emit block expressions directly in +1
2182 // contexts if we can.
2183 if (isa<BlockExpr>(e))
2184 return false;
2185
2186 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2187 switch (cast->getCastKind()) {
2188 // Emitting these operations in +1 contexts is goodness.
2189 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002190 case CK_ARCReclaimReturnedObject:
2191 case CK_ARCConsumeObject:
2192 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002193 return false;
2194
2195 // These operations preserve a block type.
2196 case CK_NoOp:
2197 case CK_BitCast:
2198 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2199
2200 // These operations are known to be bad (or haven't been considered).
2201 case CK_AnyPointerToBlockPointerCast:
2202 default:
2203 return true;
2204 }
2205 }
2206
2207 return true;
2208}
2209
John McCall31168b02011-06-15 23:02:42 +00002210static TryEmitResult
2211tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall53848232011-07-27 01:07:15 +00002212 // Look through cleanups.
2213 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2214 CodeGenFunction::RunCleanupsScope scope(CGF);
2215 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2216 }
2217
John McCall31168b02011-06-15 23:02:42 +00002218 // The desired result type, if it differs from the type of the
2219 // ultimate opaque expression.
Chris Lattner2192fe52011-07-18 04:24:23 +00002220 llvm::Type *resultType = 0;
John McCall31168b02011-06-15 23:02:42 +00002221
2222 while (true) {
2223 e = e->IgnoreParens();
2224
2225 // There's a break at the end of this if-chain; anything
2226 // that wants to keep looping has to explicitly continue.
2227 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2228 switch (ce->getCastKind()) {
2229 // No-op casts don't change the type, so we just ignore them.
2230 case CK_NoOp:
2231 e = ce->getSubExpr();
2232 continue;
2233
2234 case CK_LValueToRValue: {
2235 TryEmitResult loadResult
2236 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2237 if (resultType) {
2238 llvm::Value *value = loadResult.getPointer();
2239 value = CGF.Builder.CreateBitCast(value, resultType);
2240 loadResult.setPointer(value);
2241 }
2242 return loadResult;
2243 }
2244
2245 // These casts can change the type, so remember that and
2246 // soldier on. We only need to remember the outermost such
2247 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002248 case CK_CPointerToObjCPointerCast:
2249 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002250 case CK_AnyPointerToBlockPointerCast:
2251 case CK_BitCast:
2252 if (!resultType)
2253 resultType = CGF.ConvertType(ce->getType());
2254 e = ce->getSubExpr();
2255 assert(e->getType()->hasPointerRepresentation());
2256 continue;
2257
2258 // For consumptions, just emit the subexpression and thus elide
2259 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002260 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002261 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2262 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2263 return TryEmitResult(result, true);
2264 }
2265
John McCallcd78e802011-09-10 01:16:55 +00002266 // Block extends are net +0. Naively, we could just recurse on
2267 // the subexpression, but actually we need to ensure that the
2268 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002269 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002270 llvm::Value *result; // will be a +0 value
2271
2272 // If we can't safely assume the sub-expression will produce a
2273 // block-copied value, emit the sub-expression at +0.
2274 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2275 result = CGF.EmitScalarExpr(ce->getSubExpr());
2276
2277 // Otherwise, try to emit the sub-expression at +1 recursively.
2278 } else {
2279 TryEmitResult subresult
2280 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2281 result = subresult.getPointer();
2282
2283 // If that produced a retained value, just use that,
2284 // possibly casting down.
2285 if (subresult.getInt()) {
2286 if (resultType)
2287 result = CGF.Builder.CreateBitCast(result, resultType);
2288 return TryEmitResult(result, true);
2289 }
2290
2291 // Otherwise it's +0.
2292 }
2293
2294 // Retain the object as a block, then cast down.
2295 result = CGF.EmitARCRetainBlock(result);
2296 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2297 return TryEmitResult(result, true);
2298 }
2299
John McCall4db5c3c2011-07-07 06:58:02 +00002300 // For reclaims, emit the subexpression as a retained call and
2301 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002302 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002303 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2304 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2305 return TryEmitResult(result, true);
2306 }
2307
John McCall31168b02011-06-15 23:02:42 +00002308 case CK_GetObjCProperty: {
2309 llvm::Value *result = emitARCRetainCall(CGF, ce);
2310 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2311 return TryEmitResult(result, true);
2312 }
2313
2314 default:
2315 break;
2316 }
2317
2318 // Skip __extension__.
2319 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2320 if (op->getOpcode() == UO_Extension) {
2321 e = op->getSubExpr();
2322 continue;
2323 }
2324
2325 // For calls and message sends, use the retained-call logic.
2326 // Delegate inits are a special case in that they're the only
2327 // returns-retained expression that *isn't* surrounded by
2328 // a consume.
2329 } else if (isa<CallExpr>(e) ||
2330 (isa<ObjCMessageExpr>(e) &&
2331 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2332 llvm::Value *result = emitARCRetainCall(CGF, e);
2333 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2334 return TryEmitResult(result, true);
2335 }
2336
2337 // Conservatively halt the search at any other expression kind.
2338 break;
2339 }
2340
2341 // We didn't find an obvious production, so emit what we've got and
2342 // tell the caller that we didn't manage to retain.
2343 llvm::Value *result = CGF.EmitScalarExpr(e);
2344 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2345 return TryEmitResult(result, false);
2346}
2347
2348static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2349 LValue lvalue,
2350 QualType type) {
2351 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2352 llvm::Value *value = result.getPointer();
2353 if (!result.getInt())
2354 value = CGF.EmitARCRetain(type, value);
2355 return value;
2356}
2357
2358/// EmitARCRetainScalarExpr - Semantically equivalent to
2359/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2360/// best-effort attempt to peephole expressions that naturally produce
2361/// retained objects.
2362llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2363 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2364 llvm::Value *value = result.getPointer();
2365 if (!result.getInt())
2366 value = EmitARCRetain(e->getType(), value);
2367 return value;
2368}
2369
2370llvm::Value *
2371CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2372 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2373 llvm::Value *value = result.getPointer();
2374 if (result.getInt())
2375 value = EmitARCAutorelease(value);
2376 else
2377 value = EmitARCRetainAutorelease(e->getType(), value);
2378 return value;
2379}
2380
2381std::pair<LValue,llvm::Value*>
2382CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2383 bool ignored) {
2384 // Evaluate the RHS first.
2385 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2386 llvm::Value *value = result.getPointer();
2387
John McCallb726a552011-07-28 07:23:35 +00002388 bool hasImmediateRetain = result.getInt();
2389
2390 // If we didn't emit a retained object, and the l-value is of block
2391 // type, then we need to emit the block-retain immediately in case
2392 // it invalidates the l-value.
2393 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2394 value = EmitARCRetainBlock(value);
2395 hasImmediateRetain = true;
2396 }
2397
John McCall31168b02011-06-15 23:02:42 +00002398 LValue lvalue = EmitLValue(e->getLHS());
2399
2400 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002401 if (hasImmediateRetain) {
John McCall31168b02011-06-15 23:02:42 +00002402 llvm::Value *oldValue =
2403 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2404 lvalue.getAlignment(), e->getType(),
2405 lvalue.getTBAAInfo());
2406 EmitStoreOfScalar(value, lvalue.getAddress(),
2407 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2408 e->getType(), lvalue.getTBAAInfo());
2409 EmitARCRelease(oldValue, /*precise*/ false);
2410 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002411 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002412 }
2413
2414 return std::pair<LValue,llvm::Value*>(lvalue, value);
2415}
2416
2417std::pair<LValue,llvm::Value*>
2418CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2419 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2420 LValue lvalue = EmitLValue(e->getLHS());
2421
2422 EmitStoreOfScalar(value, lvalue.getAddress(),
2423 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2424 e->getType(), lvalue.getTBAAInfo());
2425
2426 return std::pair<LValue,llvm::Value*>(lvalue, value);
2427}
2428
2429void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2430 const ObjCAutoreleasePoolStmt &ARPS) {
2431 const Stmt *subStmt = ARPS.getSubStmt();
2432 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2433
2434 CGDebugInfo *DI = getDebugInfo();
2435 if (DI) {
2436 DI->setLocation(S.getLBracLoc());
2437 DI->EmitRegionStart(Builder);
2438 }
2439
2440 // Keep track of the current cleanup stack depth.
2441 RunCleanupsScope Scope(*this);
John McCall24fc0de2011-07-06 00:26:06 +00002442 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCall31168b02011-06-15 23:02:42 +00002443 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2444 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2445 } else {
2446 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2447 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2448 }
2449
2450 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2451 E = S.body_end(); I != E; ++I)
2452 EmitStmt(*I);
2453
2454 if (DI) {
2455 DI->setLocation(S.getRBracLoc());
2456 DI->EmitRegionEnd(Builder);
2457 }
2458}
John McCall1bd25562011-06-24 23:21:27 +00002459
2460/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2461/// make sure it survives garbage collection until this point.
2462void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2463 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002464 llvm::FunctionType *extenderType
Jay Foad5709f7c2011-07-29 13:56:53 +00002465 = llvm::FunctionType::get(VoidTy, VoidPtrTy, /*variadic*/ false);
John McCall1bd25562011-06-24 23:21:27 +00002466 llvm::Value *extender
2467 = llvm::InlineAsm::get(extenderType,
2468 /* assembly */ "",
2469 /* constraints */ "r",
2470 /* side effects */ true);
2471
2472 object = Builder.CreateBitCast(object, VoidPtrTy);
2473 Builder.CreateCall(extender, object)->setDoesNotThrow();
2474}
2475
Ted Kremenek43e06332008-04-09 15:51:31 +00002476CGObjCRuntime::~CGObjCRuntime() {}