blob: be38d36f6c5f2dce26b1980d0a220ac2f24819e6 [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
36 const llvm::Type *type =
37 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattner8fdf3282008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000043{
David Chisnall0d13f6f2010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000057}
58
Daniel Dunbared7c6182008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattner8fdf3282008-06-24 17:04:18 +000063
Douglas Gregor926df6c2011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCallf85e1932011-06-15 23:02:42 +000072
Douglas Gregor926df6c2011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattner8fdf3282008-06-24 17:04:18 +000082
John McCallef072fd2010-05-22 01:48:05 +000083RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
84 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +000085 // Only the lookup mechanism and first two arguments of the method
86 // implementation vary between runtimes. We can get the receiver and
87 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +000088
John McCallf85e1932011-06-15 23:02:42 +000089 bool isDelegateInit = E->isDelegateInitCall();
90
91 // We don't retain the receiver in delegate init calls, and this is
92 // safe because the receiver value is always loaded from 'self',
93 // which we zero out. We don't want to Block_copy block receivers,
94 // though.
95 bool retainSelf =
96 (!isDelegateInit &&
97 CGM.getLangOptions().ObjCAutoRefCount &&
98 E->getMethodDecl() &&
99 E->getMethodDecl()->hasAttr<NSConsumesSelfAttr>());
100
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000101 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000102 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000103 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000104 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000105 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000106 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000107 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000108 switch (E->getReceiverKind()) {
109 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000110 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000111 if (retainSelf) {
112 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
113 E->getInstanceReceiver());
114 Receiver = ter.getPointer();
115 if (!ter.getInt())
116 Receiver = EmitARCRetainNonBlock(Receiver);
117 } else
118 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000119 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000120
Douglas Gregor04badcf2010-04-21 00:45:42 +0000121 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000122 ReceiverType = E->getClassReceiver();
123 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000124 assert(ObjTy && "Invalid Objective-C class message send");
125 OID = ObjTy->getInterface();
126 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000127 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000128 isClassMessage = true;
John McCallf85e1932011-06-15 23:02:42 +0000129
130 if (retainSelf)
131 Receiver = EmitARCRetainNonBlock(Receiver);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000132 break;
133 }
134
135 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000136 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000137 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000138 isSuperMessage = true;
John McCallf85e1932011-06-15 23:02:42 +0000139
140 if (retainSelf)
141 Receiver = EmitARCRetainNonBlock(Receiver);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000142 break;
143
144 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000145 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000146 Receiver = LoadObjCSelf();
147 isSuperMessage = true;
148 isClassMessage = true;
John McCallf85e1932011-06-15 23:02:42 +0000149
150 if (retainSelf)
151 Receiver = EmitARCRetainNonBlock(Receiver);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000152 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000153 }
154
John McCallf85e1932011-06-15 23:02:42 +0000155 QualType ResultType =
156 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
157
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000158 CallArgList Args;
Anders Carlsson131038e2009-04-18 20:29:27 +0000159 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000160
John McCallf85e1932011-06-15 23:02:42 +0000161 // For delegate init calls in ARC, do an unsafe store of null into
162 // self. This represents the call taking direct ownership of that
163 // value. We have to do this after emitting the other call
164 // arguments because they might also reference self, but we don't
165 // have to worry about any of them modifying self because that would
166 // be an undefined read and write of an object in unordered
167 // expressions.
168 if (isDelegateInit) {
169 assert(getLangOptions().ObjCAutoRefCount &&
170 "delegate init calls should only be marked in ARC");
171
172 // Do an unsafe store of null into self.
173 llvm::Value *selfAddr =
174 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
175 assert(selfAddr && "no self entry for a delegate init call?");
176
177 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
178 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000179
Douglas Gregor926df6c2011-06-11 01:09:30 +0000180 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000181 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000182 // super is only valid in an Objective-C method
183 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000184 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000185 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
186 E->getSelector(),
187 OMD->getClassInterface(),
188 isCategoryImpl,
189 Receiver,
190 isClassMessage,
191 Args,
192 E->getMethodDecl());
193 } else {
194 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
195 E->getSelector(),
196 Receiver, Args, OID,
197 E->getMethodDecl());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000198 }
John McCallf85e1932011-06-15 23:02:42 +0000199
200 // For delegate init calls in ARC, implicitly store the result of
201 // the call back into self. This takes ownership of the value.
202 if (isDelegateInit) {
203 llvm::Value *selfAddr =
204 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
205 llvm::Value *newSelf = result.getScalarVal();
206
207 // The delegate return type isn't necessarily a matching type; in
208 // fact, it's quite likely to be 'id'.
209 const llvm::Type *selfTy =
210 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
211 newSelf = Builder.CreateBitCast(newSelf, selfTy);
212
213 Builder.CreateStore(newSelf, selfAddr);
214 }
215
Douglas Gregor926df6c2011-06-11 01:09:30 +0000216 return AdjustRelatedResultType(*this, E, E->getMethodDecl(), result);
Anders Carlsson55085182007-08-21 17:43:55 +0000217}
218
John McCallf85e1932011-06-15 23:02:42 +0000219namespace {
220struct FinishARCDealloc : EHScopeStack::Cleanup {
221 void Emit(CodeGenFunction &CGF, bool isForEH) {
222 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
223 const ObjCImplementationDecl *impl
224 = cast<ObjCImplementationDecl>(method->getDeclContext());
225 const ObjCInterfaceDecl *iface = impl->getClassInterface();
226 if (!iface->getSuperClass()) return;
227
228 // Call [super dealloc] if we have a superclass.
229 llvm::Value *self = CGF.LoadObjCSelf();
230
231 CallArgList args;
232 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
233 CGF.getContext().VoidTy,
234 method->getSelector(),
235 iface,
236 /*is category*/ false,
237 self,
238 /*is class msg*/ false,
239 args,
240 method);
241 }
242};
243}
244
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000245/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
246/// the LLVM function and sets the other context used by
247/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000248void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000249 const ObjCContainerDecl *CD,
250 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000251 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000252 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000253 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
254 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000255
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000256 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000257
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000258 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
259 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000260
John McCalld26bc762011-03-09 04:27:21 +0000261 args.push_back(OMD->getSelfDecl());
262 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000263
Chris Lattner89951a82009-02-20 18:43:26 +0000264 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
265 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000266 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000267
Peter Collingbourne14110472011-01-13 18:57:25 +0000268 CurGD = OMD;
269
Devang Patel8d3f8972011-05-19 23:37:41 +0000270 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000271
272 // In ARC, certain methods get an extra cleanup.
273 if (CGM.getLangOptions().ObjCAutoRefCount &&
274 OMD->isInstanceMethod() &&
275 OMD->getSelector().isUnarySelector()) {
276 const IdentifierInfo *ident =
277 OMD->getSelector().getIdentifierInfoForSlot(0);
278 if (ident->isStr("dealloc"))
279 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
280 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000281}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000282
John McCallf85e1932011-06-15 23:02:42 +0000283static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
284 LValue lvalue, QualType type);
285
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000286void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
287 bool IsAtomic, bool IsStrong) {
288 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
289 Ivar, 0);
290 llvm::Value *GetCopyStructFn =
291 CGM.getObjCRuntime().GetGetStructFunction();
292 CodeGenTypes &Types = CGM.getTypes();
293 // objc_copyStruct (ReturnValue, &structIvar,
294 // sizeof (Type of Ivar), isAtomic, false);
295 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000296 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000297 Args.add(RV, getContext().VoidPtrTy);
John McCall0774cb82011-05-15 01:53:33 +0000298 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000299 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000300 // sizeof (Type of Ivar)
301 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
302 llvm::Value *SizeVal =
John McCall0774cb82011-05-15 01:53:33 +0000303 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000304 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000305 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000306 llvm::Value *isAtomic =
307 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
308 IsAtomic ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000309 Args.add(RValue::get(isAtomic), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000310 llvm::Value *hasStrong =
311 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
312 IsStrong ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000313 Args.add(RValue::get(hasStrong), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000314 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
315 FunctionType::ExtInfo()),
316 GetCopyStructFn, ReturnValueSlot(), Args);
317}
318
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000319/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000320/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000321void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000322 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000323 EmitStmt(OMD->getBody());
324 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000325}
326
Mike Stumpf5408fe2009-05-16 07:57:57 +0000327// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
328// AST for the whole body we can just fall back to having a GenerateFunction
329// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000330
331/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000332/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
333/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000334void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
335 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000336 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000337 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000338 bool IsAtomic =
339 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000340 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
341 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000342 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000343
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000344 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000345 // this. Non-atomic properties are directly evaluated.
346 // atomic 'copy' and 'retain' properties are also directly
347 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000348 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000349 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000350 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
351 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000352 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000353 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000354
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000355 if (!GetPropertyFn) {
356 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
357 FinishFunction();
358 return;
359 }
360
361 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
362 // FIXME: Can't this be simpler? This might even be worse than the
363 // corresponding gcc code.
364 CodeGenTypes &Types = CGM.getTypes();
365 ValueDecl *Cmd = OMD->getCmdDecl();
366 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
367 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000368 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000369 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000370 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000371 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000372 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000373 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000374 Args.add(RValue::get(SelfAsId), IdTy);
375 Args.add(RValue::get(CmdVal), Cmd->getType());
376 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
377 Args.add(RValue::get(True), getContext().BoolTy);
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000378 // FIXME: We shouldn't need to get the function info here, the
379 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000380 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000381 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000382 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000383 // We need to fix the type here. Ivars with copy & retain are
384 // always objects so we don't need to worry about complex or
385 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000386 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000387 Types.ConvertType(PD->getType())));
388 EmitReturnOfRValue(RV, PD->getType());
John McCallf85e1932011-06-15 23:02:42 +0000389
390 // objc_getProperty does an autorelease, so we should suppress ours.
391 AutoreleaseResult = false;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000392 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000393 const llvm::Triple &Triple = getContext().Target.getTriple();
394 QualType IVART = Ivar->getType();
395 if (IsAtomic &&
396 IVART->isScalarType() &&
397 (Triple.getArch() == llvm::Triple::arm ||
398 Triple.getArch() == llvm::Triple::thumb) &&
399 (getContext().getTypeSizeInChars(IVART)
400 > CharUnits::fromQuantity(4)) &&
401 CGM.getObjCRuntime().GetGetStructFunction()) {
402 GenerateObjCGetterBody(Ivar, true, false);
403 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000404 else if (IsAtomic &&
405 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
406 Triple.getArch() == llvm::Triple::x86 &&
407 (getContext().getTypeSizeInChars(IVART)
408 > CharUnits::fromQuantity(4)) &&
409 CGM.getObjCRuntime().GetGetStructFunction()) {
410 GenerateObjCGetterBody(Ivar, true, false);
411 }
412 else if (IsAtomic &&
413 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
414 Triple.getArch() == llvm::Triple::x86_64 &&
415 (getContext().getTypeSizeInChars(IVART)
416 > CharUnits::fromQuantity(8)) &&
417 CGM.getObjCRuntime().GetGetStructFunction()) {
418 GenerateObjCGetterBody(Ivar, true, false);
419 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000420 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000421 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
422 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000423 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
424 LV.isVolatileQualified());
425 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
426 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000427 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000428 bool IsStrong = false;
Fariborz Jahanian5fb65092011-04-05 23:01:27 +0000429 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000430 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000431 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000432 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000433 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000434 else {
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000435 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
436
437 if (PID->getGetterCXXConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +0000438 classDecl && !classDecl->hasTrivialDefaultConstructor()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000439 ReturnStmt *Stmt =
440 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000441 PID->getGetterCXXConstructor(),
442 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000443 EmitReturnStmt(*Stmt);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000444 } else if (IsAtomic &&
445 !IVART->isAnyComplexType() &&
446 Triple.getArch() == llvm::Triple::x86 &&
447 (getContext().getTypeSizeInChars(IVART)
448 > CharUnits::fromQuantity(4)) &&
449 CGM.getObjCRuntime().GetGetStructFunction()) {
450 GenerateObjCGetterBody(Ivar, true, false);
451 }
452 else if (IsAtomic &&
453 !IVART->isAnyComplexType() &&
454 Triple.getArch() == llvm::Triple::x86_64 &&
455 (getContext().getTypeSizeInChars(IVART)
456 > CharUnits::fromQuantity(8)) &&
457 CGM.getObjCRuntime().GetGetStructFunction()) {
458 GenerateObjCGetterBody(Ivar, true, false);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000459 }
460 else {
461 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
462 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000463 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000464 }
465 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000466 }
467 else {
468 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
John McCall545d9962011-06-25 02:11:03 +0000469 Ivar, 0);
John McCallf85e1932011-06-15 23:02:42 +0000470 QualType propType = PD->getType();
471
472 llvm::Value *value;
473 if (propType->isReferenceType()) {
474 value = LV.getAddress();
475 } else {
476 // In ARC, we want to emit this retained.
477 if (getLangOptions().ObjCAutoRefCount &&
478 PD->getType()->isObjCRetainableType())
479 value = emitARCRetainLoadOfScalar(*this, LV, IVART);
480 else
John McCall545d9962011-06-25 02:11:03 +0000481 value = EmitLoadOfLValue(LV).getScalarVal();
John McCallf85e1932011-06-15 23:02:42 +0000482
483 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian14086762011-03-28 23:47:18 +0000484 }
John McCallf85e1932011-06-15 23:02:42 +0000485
486 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000487 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000488 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000489
490 FinishFunction();
491}
492
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000493void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
494 ObjCIvarDecl *Ivar) {
495 // objc_copyStruct (&structIvar, &Arg,
496 // sizeof (struct something), true, false);
497 llvm::Value *GetCopyStructFn =
498 CGM.getObjCRuntime().GetSetStructFunction();
499 CodeGenTypes &Types = CGM.getTypes();
500 CallArgList Args;
501 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
502 RValue RV =
503 RValue::get(Builder.CreateBitCast(LV.getAddress(),
504 Types.ConvertType(getContext().VoidPtrTy)));
Eli Friedman04c9a492011-05-02 17:57:46 +0000505 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000506 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
507 llvm::Value *ArgAsPtrTy =
508 Builder.CreateBitCast(Arg,
509 Types.ConvertType(getContext().VoidPtrTy));
510 RV = RValue::get(ArgAsPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +0000511 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000512 // sizeof (Type of Ivar)
513 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
514 llvm::Value *SizeVal =
515 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
516 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000517 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000518 llvm::Value *True =
519 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Eli Friedman04c9a492011-05-02 17:57:46 +0000520 Args.add(RValue::get(True), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000521 llvm::Value *False =
522 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000523 Args.add(RValue::get(False), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000524 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
525 FunctionType::ExtInfo()),
526 GetCopyStructFn, ReturnValueSlot(), Args);
527}
528
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000529static bool
530IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID,
531 QualType IvarT) {
532 bool HasTrvialAssignment = true;
533 if (PID->getSetterCXXAssignment()) {
534 const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl();
535 HasTrvialAssignment =
536 (!classDecl || classDecl->hasTrivialCopyAssignment());
537 }
538 return HasTrvialAssignment;
539}
540
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000541/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000542/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
543/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000544void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
545 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000546 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000547 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
548 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
549 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000550 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000551 const llvm::Triple &Triple = getContext().Target.getTriple();
552 QualType IVART = Ivar->getType();
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000553 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump1eb44332009-09-09 15:08:12 +0000554 bool IsAtomic =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000555 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
556
557 // Determine if we should use an objc_setProperty call for
558 // this. Properties with 'copy' semantics always use it, as do
559 // non-atomic properties with 'release' semantics as long as we are
560 // not in gc-only mode.
561 if (IsCopy ||
562 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
563 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000564 llvm::Value *SetPropertyFn =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000565 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000567 if (!SetPropertyFn) {
568 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
569 FinishFunction();
570 return;
571 }
Mike Stump1eb44332009-09-09 15:08:12 +0000572
573 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000574 // <is-atomic>, <is-copy>).
575 // FIXME: Can't this be simpler? This might even be worse than the
576 // corresponding gcc code.
577 CodeGenTypes &Types = CGM.getTypes();
578 ValueDecl *Cmd = OMD->getCmdDecl();
579 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
580 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000581 llvm::Value *SelfAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000582 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000583 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattner89951a82009-02-20 18:43:26 +0000584 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump1eb44332009-09-09 15:08:12 +0000585 llvm::Value *ArgAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000586 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
587 Types.ConvertType(IdTy));
588 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000589 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000590 llvm::Value *False =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000591 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000592 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000593 Args.add(RValue::get(SelfAsId), IdTy);
594 Args.add(RValue::get(CmdVal), Cmd->getType());
595 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
596 Args.add(RValue::get(ArgAsId), IdTy);
597 Args.add(RValue::get(IsAtomic ? True : False), getContext().BoolTy);
598 Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy);
Mike Stumpf5408fe2009-05-16 07:57:57 +0000599 // FIXME: We shouldn't need to get the function info here, the runtime
600 // already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000601 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000602 FunctionType::ExtInfo()),
603 SetPropertyFn,
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000604 ReturnValueSlot(), Args);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000605 } else if (IsAtomic && hasAggregateLLVMType(IVART) &&
606 !IVART->isAnyComplexType() &&
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000607 IvarAssignHasTrvialAssignment(PID, IVART) &&
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000608 ((Triple.getArch() == llvm::Triple::x86 &&
609 (getContext().getTypeSizeInChars(IVART)
610 > CharUnits::fromQuantity(4))) ||
611 (Triple.getArch() == llvm::Triple::x86_64 &&
612 (getContext().getTypeSizeInChars(IVART)
613 > CharUnits::fromQuantity(8))))
David Chisnall8fac25d2010-12-26 22:13:16 +0000614 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000615 // objc_copyStruct (&structIvar, &Arg,
616 // sizeof (struct something), true, false);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000617 GenerateObjCAtomicSetterBody(OMD, Ivar);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000618 } else if (PID->getSetterCXXAssignment()) {
John McCall2a416372010-12-05 02:00:02 +0000619 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000620 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000621 if (IsAtomic &&
622 IVART->isScalarType() &&
623 (Triple.getArch() == llvm::Triple::arm ||
624 Triple.getArch() == llvm::Triple::thumb) &&
625 (getContext().getTypeSizeInChars(IVART)
626 > CharUnits::fromQuantity(4)) &&
627 CGM.getObjCRuntime().GetGetStructFunction()) {
628 GenerateObjCAtomicSetterBody(OMD, Ivar);
629 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000630 else if (IsAtomic &&
631 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
632 Triple.getArch() == llvm::Triple::x86 &&
633 (getContext().getTypeSizeInChars(IVART)
634 > CharUnits::fromQuantity(4)) &&
635 CGM.getObjCRuntime().GetGetStructFunction()) {
636 GenerateObjCAtomicSetterBody(OMD, Ivar);
637 }
638 else if (IsAtomic &&
639 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
640 Triple.getArch() == llvm::Triple::x86_64 &&
641 (getContext().getTypeSizeInChars(IVART)
642 > CharUnits::fromQuantity(8)) &&
643 CGM.getObjCRuntime().GetGetStructFunction()) {
644 GenerateObjCAtomicSetterBody(OMD, Ivar);
645 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000646 else {
647 // FIXME: Find a clean way to avoid AST node creation.
Devang Patel8d3f8972011-05-19 23:37:41 +0000648 SourceLocation Loc = PID->getLocStart();
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000649 ValueDecl *Self = OMD->getSelfDecl();
650 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
651 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
652 ParmVarDecl *ArgDecl = *OMD->param_begin();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000653 QualType T = ArgDecl->getType();
654 if (T->isReferenceType())
655 T = cast<ReferenceType>(T)->getPointeeType();
656 DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000657 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000658
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000659 // The property type can differ from the ivar type in some situations with
660 // Objective-C pointer types, we can always bit cast the RHS in these cases.
661 if (getContext().getCanonicalType(Ivar->getType()) !=
662 getContext().getCanonicalType(ArgDecl->getType())) {
663 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
664 Ivar->getType(), CK_BitCast, &Arg,
665 VK_RValue);
666 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
667 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
668 EmitStmt(&Assign);
669 } else {
670 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
671 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
672 EmitStmt(&Assign);
673 }
Daniel Dunbar45e84232009-10-27 19:21:30 +0000674 }
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000675 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000676
677 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000678}
679
John McCalle81ac692011-03-22 07:05:39 +0000680// FIXME: these are stolen from CGClass.cpp, which is lame.
681namespace {
682 struct CallArrayIvarDtor : EHScopeStack::Cleanup {
683 const ObjCIvarDecl *ivar;
684 llvm::Value *self;
685 CallArrayIvarDtor(const ObjCIvarDecl *ivar, llvm::Value *self)
686 : ivar(ivar), self(self) {}
687
688 void Emit(CodeGenFunction &CGF, bool IsForEH) {
689 LValue lvalue =
690 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), self, ivar, 0);
691
692 QualType type = ivar->getType();
693 const ConstantArrayType *arrayType
694 = CGF.getContext().getAsConstantArrayType(type);
695 QualType baseType = CGF.getContext().getBaseElementType(arrayType);
696 const CXXRecordDecl *classDecl = baseType->getAsCXXRecordDecl();
697
698 llvm::Value *base
699 = CGF.Builder.CreateBitCast(lvalue.getAddress(),
700 CGF.ConvertType(baseType)->getPointerTo());
701 CGF.EmitCXXAggrDestructorCall(classDecl->getDestructor(),
702 arrayType, base);
703 }
704 };
705
706 struct CallIvarDtor : EHScopeStack::Cleanup {
707 const ObjCIvarDecl *ivar;
708 llvm::Value *self;
709 CallIvarDtor(const ObjCIvarDecl *ivar, llvm::Value *self)
710 : ivar(ivar), self(self) {}
711
712 void Emit(CodeGenFunction &CGF, bool IsForEH) {
713 LValue lvalue =
714 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), self, ivar, 0);
715
716 QualType type = ivar->getType();
717 const CXXRecordDecl *classDecl = type->getAsCXXRecordDecl();
718
719 CGF.EmitCXXDestructorCall(classDecl->getDestructor(),
720 Dtor_Complete, /*ForVirtualBase=*/false,
721 lvalue.getAddress());
722 }
723 };
724}
725
John McCallf85e1932011-06-15 23:02:42 +0000726static void pushReleaseForIvar(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
727 llvm::Value *self);
728static void pushWeakReleaseForIvar(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
729 llvm::Value *self);
730
John McCalle81ac692011-03-22 07:05:39 +0000731static void emitCXXDestructMethod(CodeGenFunction &CGF,
732 ObjCImplementationDecl *impl) {
733 CodeGenFunction::RunCleanupsScope scope(CGF);
734
735 llvm::Value *self = CGF.LoadObjCSelf();
736
737 ObjCInterfaceDecl *iface
738 = const_cast<ObjCInterfaceDecl*>(impl->getClassInterface());
739 for (ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
740 ivar; ivar = ivar->getNextIvar()) {
741 QualType type = ivar->getType();
742
743 // Drill down to the base element type.
744 QualType baseType = type;
745 const ConstantArrayType *arrayType =
746 CGF.getContext().getAsConstantArrayType(baseType);
747 if (arrayType) baseType = CGF.getContext().getBaseElementType(arrayType);
748
749 // Check whether the ivar is a destructible type.
750 QualType::DestructionKind destructKind = baseType.isDestructedType();
751 assert(destructKind == type.isDestructedType());
752
753 switch (destructKind) {
754 case QualType::DK_none:
755 continue;
756
757 case QualType::DK_cxx_destructor:
758 if (arrayType)
759 CGF.EHStack.pushCleanup<CallArrayIvarDtor>(NormalAndEHCleanup,
760 ivar, self);
761 else
762 CGF.EHStack.pushCleanup<CallIvarDtor>(NormalAndEHCleanup,
763 ivar, self);
764 break;
John McCallf85e1932011-06-15 23:02:42 +0000765
766 case QualType::DK_objc_strong_lifetime:
767 pushReleaseForIvar(CGF, ivar, self);
768 break;
769
770 case QualType::DK_objc_weak_lifetime:
771 pushWeakReleaseForIvar(CGF, ivar, self);
772 break;
John McCalle81ac692011-03-22 07:05:39 +0000773 }
774 }
775
776 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
777}
778
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000779void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
780 ObjCMethodDecl *MD,
781 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000782 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +0000783 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +0000784
785 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000786 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +0000787 // Suppress the final autorelease in ARC.
788 AutoreleaseResult = false;
789
John McCalle81ac692011-03-22 07:05:39 +0000790 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
791 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
792 E = IMP->init_end(); B != E; ++B) {
793 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +0000794 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000795 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000796 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
797 LoadObjCSelf(), Ivar, 0);
John McCall558d2ab2010-09-15 10:14:12 +0000798 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000799 }
800 // constructor returns 'self'.
801 CodeGenTypes &Types = CGM.getTypes();
802 QualType IdTy(CGM.getContext().getObjCIdType());
803 llvm::Value *SelfAsId =
804 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
805 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +0000806
807 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000808 } else {
John McCalle81ac692011-03-22 07:05:39 +0000809 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000810 }
811 FinishFunction();
812}
813
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000814bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
815 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
816 it++; it++;
817 const ABIArgInfo &AI = it->info;
818 // FIXME. Is this sufficient check?
819 return (AI.getKind() == ABIArgInfo::Indirect);
820}
821
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000822bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
823 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
824 return false;
825 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
826 return FDTTy->getDecl()->hasObjectMember();
827 return false;
828}
829
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000830llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000831 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
832 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000833}
834
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000835QualType CodeGenFunction::TypeOfSelfObject() {
836 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
837 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000838 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
839 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000840 return PTy->getPointeeType();
841}
842
John McCalle68b9842010-12-04 03:11:00 +0000843LValue
844CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
845 // This is a special l-value that just issues sends when we load or
846 // store through it.
847
848 // For certain base kinds, we need to emit the base immediately.
849 llvm::Value *Base;
850 if (E->isSuperReceiver())
851 Base = LoadObjCSelf();
852 else if (E->isClassReceiver())
853 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
854 else
855 Base = EmitScalarExpr(E->getBase());
856 return LValue::MakePropertyRef(E, Base);
857}
858
859static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
860 ReturnValueSlot Return,
861 QualType ResultType,
862 Selector S,
863 llvm::Value *Receiver,
864 const CallArgList &CallArgs) {
865 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000866 bool isClassMessage = OMD->isClassMethod();
867 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000868 return CGF.CGM.getObjCRuntime()
869 .GenerateMessageSendSuper(CGF, Return, ResultType,
870 S, OMD->getClassInterface(),
871 isCategoryImpl, Receiver,
872 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000873}
874
John McCall119a1c62010-12-04 02:32:38 +0000875RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
876 ReturnValueSlot Return) {
877 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000878 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +0000879 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +0000880 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +0000881 if (E->isExplicitProperty()) {
882 const ObjCPropertyDecl *Property = E->getExplicitProperty();
883 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000884 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +0000885 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000886 method = E->getImplicitPropertyGetter();
887 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000888 }
John McCall12f78a62010-12-02 01:19:52 +0000889
John McCall119a1c62010-12-04 02:32:38 +0000890 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000891
John McCallf85e1932011-06-15 23:02:42 +0000892 if (CGM.getLangOptions().ObjCAutoRefCount) {
893 QualType receiverType;
894 if (E->isSuperReceiver())
895 receiverType = E->getSuperReceiverType();
896 else if (E->isClassReceiver())
897 receiverType = getContext().getObjCClassType();
898 else
899 receiverType = E->getBase()->getType();
900 }
901
John McCalle68b9842010-12-04 03:11:00 +0000902 // Accesses to 'super' follow a different code path.
903 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +0000904 return AdjustRelatedResultType(*this, E, method,
905 GenerateMessageSendSuper(*this, Return,
906 ResultType,
907 S, Receiver,
908 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +0000909 const ObjCInterfaceDecl *ReceiverClass
910 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000911 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +0000912 CGM.getObjCRuntime().
913 GenerateMessageSend(*this, Return, ResultType, S,
914 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000915}
916
John McCall119a1c62010-12-04 02:32:38 +0000917void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
918 LValue Dst) {
919 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000920 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000921 QualType ArgType = E->getSetterArgType();
922
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000923 // FIXME. Other than scalars, AST is not adequate for setter and
924 // getter type mismatches which require conversion.
925 if (Src.isScalar()) {
926 llvm::Value *SrcVal = Src.getScalarVal();
927 QualType DstType = getContext().getCanonicalType(ArgType);
928 const llvm::Type *DstTy = ConvertType(DstType);
929 if (SrcVal->getType() != DstTy)
930 Src =
931 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
932 }
933
John McCalle68b9842010-12-04 03:11:00 +0000934 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000935 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +0000936
937 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
938 QualType ResultType = getContext().VoidTy;
939
John McCall12f78a62010-12-02 01:19:52 +0000940 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +0000941 GenerateMessageSendSuper(*this, ReturnValueSlot(),
942 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +0000943 return;
944 }
945
John McCall119a1c62010-12-04 02:32:38 +0000946 const ObjCInterfaceDecl *ReceiverClass
947 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000948
John McCall12f78a62010-12-02 01:19:52 +0000949 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +0000950 ResultType, S, Receiver, Args,
951 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000952}
953
Chris Lattner74391b42009-03-22 21:03:39 +0000954void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +0000955 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000956 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000958 if (!EnumerationMutationFn) {
959 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
960 return;
961 }
962
Devang Patelbcbd03a2011-01-19 01:36:36 +0000963 CGDebugInfo *DI = getDebugInfo();
964 if (DI) {
965 DI->setLocation(S.getSourceRange().getBegin());
966 DI->EmitRegionStart(Builder);
967 }
968
Devang Patel9d99f2d2011-06-13 23:15:32 +0000969 // The local variable comes into scope immediately.
970 AutoVarEmission variable = AutoVarEmission::invalid();
971 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
972 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
973
John McCalld88687f2011-01-07 01:49:06 +0000974 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
975 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump1eb44332009-09-09 15:08:12 +0000976
Anders Carlssonf484c312008-08-31 02:33:12 +0000977 // Fast enumeration state.
978 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +0000979 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +0000980 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000981
Anders Carlssonf484c312008-08-31 02:33:12 +0000982 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000983 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +0000984
John McCalld88687f2011-01-07 01:49:06 +0000985 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +0000986 IdentifierInfo *II[] = {
987 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
988 &CGM.getContext().Idents.get("objects"),
989 &CGM.getContext().Idents.get("count")
990 };
991 Selector FastEnumSel =
992 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +0000993
994 QualType ItemsTy =
995 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000996 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +0000997 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +0000998 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000999
John McCalld88687f2011-01-07 01:49:06 +00001000 // Emit the collection pointer.
Anders Carlssonf484c312008-08-31 02:33:12 +00001001 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump1eb44332009-09-09 15:08:12 +00001002
John McCalld88687f2011-01-07 01:49:06 +00001003 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001004 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001005
1006 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001007 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001008
John McCalld88687f2011-01-07 01:49:06 +00001009 // The second argument is a temporary array with space for NumItems
1010 // pointers. We'll actually be loading elements from the array
1011 // pointer written into the control state; this buffer is so that
1012 // collections that *aren't* backed by arrays can still queue up
1013 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001014 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001015
John McCalld88687f2011-01-07 01:49:06 +00001016 // The third argument is the capacity of that temporary array.
Anders Carlssonf484c312008-08-31 02:33:12 +00001017 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001018 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001019 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001020
John McCalld88687f2011-01-07 01:49:06 +00001021 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001022 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001023 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001024 getContext().UnsignedLongTy,
1025 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001026 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001027
John McCalld88687f2011-01-07 01:49:06 +00001028 // The initial number of objects that were returned in the buffer.
1029 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001030
John McCalld88687f2011-01-07 01:49:06 +00001031 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1032 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001033
John McCalld88687f2011-01-07 01:49:06 +00001034 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001035
John McCalld88687f2011-01-07 01:49:06 +00001036 // If the limit pointer was zero to begin with, the collection is
1037 // empty; skip all this.
1038 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1039 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001040
John McCalld88687f2011-01-07 01:49:06 +00001041 // Otherwise, initialize the loop.
1042 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001043
John McCalld88687f2011-01-07 01:49:06 +00001044 // Save the initial mutations value. This is the value at an
1045 // address that was written into the state object by
1046 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001047 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001048 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001049 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001050 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001051
John McCalld88687f2011-01-07 01:49:06 +00001052 llvm::Value *initialMutations =
1053 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001054
John McCalld88687f2011-01-07 01:49:06 +00001055 // Start looping. This is the point we return to whenever we have a
1056 // fresh, non-empty batch of objects.
1057 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1058 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001059
John McCalld88687f2011-01-07 01:49:06 +00001060 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001061 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001062 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001063
John McCalld88687f2011-01-07 01:49:06 +00001064 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001065 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001066 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
John McCalld88687f2011-01-07 01:49:06 +00001068 // Check whether the mutations value has changed from where it was
1069 // at start. StateMutationsPtr should actually be invariant between
1070 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001071 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001072 llvm::Value *currentMutations
1073 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001074
John McCalld88687f2011-01-07 01:49:06 +00001075 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001076 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001077
John McCalld88687f2011-01-07 01:49:06 +00001078 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1079 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001080
John McCalld88687f2011-01-07 01:49:06 +00001081 // If so, call the enumeration-mutation function.
1082 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001083 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001084 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001085 ConvertType(getContext().getObjCIdType()),
1086 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001087 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001088 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001089 // FIXME: We shouldn't need to get the function info here, the runtime already
1090 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001091 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001092 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001093 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001094
John McCalld88687f2011-01-07 01:49:06 +00001095 // Otherwise, or if the mutation function returns, just continue.
1096 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001097
John McCalld88687f2011-01-07 01:49:06 +00001098 // Initialize the element variable.
1099 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001100 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001101 LValue elementLValue;
1102 QualType elementType;
1103 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001104 // Initialize the variable, in case it's a __block variable or something.
1105 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001106
John McCall57b3b6a2011-02-22 07:16:58 +00001107 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001108 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1109 VK_LValue, SourceLocation());
1110 elementLValue = EmitLValue(&tempDRE);
1111 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001112 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001113
1114 if (D->isARCPseudoStrong())
1115 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001116 } else {
1117 elementLValue = LValue(); // suppress warning
1118 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001119 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001120 }
1121 const llvm::Type *convertedElementType = ConvertType(elementType);
1122
1123 // Fetch the buffer out of the enumeration state.
1124 // TODO: this pointer should actually be invariant between
1125 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001126 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001127 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001128 llvm::Value *EnumStateItems =
1129 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001130
John McCalld88687f2011-01-07 01:49:06 +00001131 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001133 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1134 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
John McCalld88687f2011-01-07 01:49:06 +00001136 // Cast that value to the right type.
1137 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1138 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001139
John McCalld88687f2011-01-07 01:49:06 +00001140 // Make sure we have an l-value. Yes, this gets evaluated every
1141 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001142 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001143 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001144 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001145 } else {
1146 EmitScalarInit(CurrentItem, elementLValue);
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
John McCall57b3b6a2011-02-22 07:16:58 +00001149 // If we do have an element variable, this assignment is the end of
1150 // its initialization.
1151 if (elementIsVariable)
1152 EmitAutoVarCleanups(variable);
1153
John McCalld88687f2011-01-07 01:49:06 +00001154 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001155 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001156 {
1157 RunCleanupsScope Scope(*this);
1158 EmitStmt(S.getBody());
1159 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001160 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCalld88687f2011-01-07 01:49:06 +00001162 // Destroy the element variable now.
1163 elementVariableScope.ForceCleanup();
1164
1165 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001166 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001167
John McCalld88687f2011-01-07 01:49:06 +00001168 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001169
John McCalld88687f2011-01-07 01:49:06 +00001170 // First we check in the local buffer.
1171 llvm::Value *indexPlusOne
1172 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001173
John McCalld88687f2011-01-07 01:49:06 +00001174 // If we haven't overrun the buffer yet, we can continue.
1175 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1176 LoopBodyBB, FetchMoreBB);
1177
1178 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1179 count->addIncoming(count, AfterBody.getBlock());
1180
1181 // Otherwise, we have to fetch more elements.
1182 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
1184 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001185 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001186 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001187 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001188 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCalld88687f2011-01-07 01:49:06 +00001190 // If we got a zero count, we're done.
1191 llvm::Value *refetchCount = CountRV.getScalarVal();
1192
1193 // (note that the message send might split FetchMoreBB)
1194 index->addIncoming(zero, Builder.GetInsertBlock());
1195 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1196
1197 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1198 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Anders Carlssonf484c312008-08-31 02:33:12 +00001200 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001201 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001202
John McCall57b3b6a2011-02-22 07:16:58 +00001203 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001204 // If the element was not a declaration, set it to be null.
1205
John McCalld88687f2011-01-07 01:49:06 +00001206 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1207 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001208 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001209 }
1210
Devang Patelbcbd03a2011-01-19 01:36:36 +00001211 if (DI) {
1212 DI->setLocation(S.getSourceRange().getEnd());
1213 DI->EmitRegionEnd(Builder);
1214 }
1215
John McCallff8e1152010-07-23 21:56:41 +00001216 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001217}
1218
Mike Stump1eb44332009-09-09 15:08:12 +00001219void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001220 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001221}
1222
Mike Stump1eb44332009-09-09 15:08:12 +00001223void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001224 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1225}
1226
Chris Lattner10cac6f2008-11-15 21:26:17 +00001227void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001228 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001229 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001230}
1231
John McCallf85e1932011-06-15 23:02:42 +00001232/// Produce the code for a CK_ObjCProduceObject. Just does a
1233/// primitive retain.
1234llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1235 llvm::Value *value) {
1236 return EmitARCRetain(type, value);
1237}
1238
1239namespace {
1240 struct CallObjCRelease : EHScopeStack::Cleanup {
1241 CallObjCRelease(QualType type, llvm::Value *ptr, llvm::Value *condition)
1242 : type(type), ptr(ptr), condition(condition) {}
1243 QualType type;
1244 llvm::Value *ptr;
1245 llvm::Value *condition;
1246
1247 void Emit(CodeGenFunction &CGF, bool forEH) {
1248 llvm::Value *object;
1249
1250 // If we're in a conditional branch, we had to stash away in an
1251 // alloca the pointer to be released.
1252 llvm::BasicBlock *cont = 0;
1253 if (condition) {
1254 llvm::BasicBlock *release = CGF.createBasicBlock("release.yes");
1255 cont = CGF.createBasicBlock("release.cont");
1256
1257 llvm::Value *cond = CGF.Builder.CreateLoad(condition);
1258 CGF.Builder.CreateCondBr(cond, release, cont);
1259 CGF.EmitBlock(release);
1260 object = CGF.Builder.CreateLoad(ptr);
1261 } else {
1262 object = ptr;
1263 }
1264
1265 CGF.EmitARCRelease(object, /*precise*/ true);
1266
1267 if (cont) CGF.EmitBlock(cont);
1268 }
1269 };
1270}
1271
1272/// Produce the code for a CK_ObjCConsumeObject. Does a primitive
1273/// release at the end of the full-expression.
1274llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1275 llvm::Value *object) {
1276 // If we're in a conditional branch, we need to make the cleanup
1277 // conditional. FIXME: this really needs to be supported by the
1278 // environment.
1279 llvm::AllocaInst *cond;
1280 llvm::Value *ptr;
1281 if (isInConditionalBranch()) {
1282 cond = CreateTempAlloca(Builder.getInt1Ty(), "release.cond");
1283 ptr = CreateTempAlloca(object->getType(), "release.value");
1284
1285 // The alloca is false until we get here.
1286 // FIXME: er. doesn't this need to be set at the start of the condition?
1287 InitTempAlloca(cond, Builder.getFalse());
1288
1289 // Then it turns true.
1290 Builder.CreateStore(Builder.getTrue(), cond);
1291 Builder.CreateStore(object, ptr);
1292 } else {
1293 cond = 0;
1294 ptr = object;
1295 }
1296
1297 EHStack.pushCleanup<CallObjCRelease>(getARCCleanupKind(), type, ptr, cond);
1298 return object;
1299}
1300
1301llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1302 llvm::Value *value) {
1303 return EmitARCRetainAutorelease(type, value);
1304}
1305
1306
1307static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1308 const llvm::FunctionType *type,
1309 llvm::StringRef fnName) {
1310 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1311
1312 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1313 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001314 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001315 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1316 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1317
1318 return fn;
1319}
1320
1321/// Perform an operation having the signature
1322/// i8* (i8*)
1323/// where a null input causes a no-op and returns null.
1324static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1325 llvm::Value *value,
1326 llvm::Constant *&fn,
1327 llvm::StringRef fnName) {
1328 if (isa<llvm::ConstantPointerNull>(value)) return value;
1329
1330 if (!fn) {
1331 std::vector<const llvm::Type*> args(1, CGF.Int8PtrTy);
1332 const llvm::FunctionType *fnType =
1333 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1334 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1335 }
1336
1337 // Cast the argument to 'id'.
1338 const llvm::Type *origType = value->getType();
1339 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1340
1341 // Call the function.
1342 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1343 call->setDoesNotThrow();
1344
1345 // Cast the result back to the original type.
1346 return CGF.Builder.CreateBitCast(call, origType);
1347}
1348
1349/// Perform an operation having the following signature:
1350/// i8* (i8**)
1351static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1352 llvm::Value *addr,
1353 llvm::Constant *&fn,
1354 llvm::StringRef fnName) {
1355 if (!fn) {
1356 std::vector<const llvm::Type*> args(1, CGF.Int8PtrPtrTy);
1357 const llvm::FunctionType *fnType =
1358 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1359 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1360 }
1361
1362 // Cast the argument to 'id*'.
1363 const llvm::Type *origType = addr->getType();
1364 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1365
1366 // Call the function.
1367 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1368 call->setDoesNotThrow();
1369
1370 // Cast the result back to a dereference of the original type.
1371 llvm::Value *result = call;
1372 if (origType != CGF.Int8PtrPtrTy)
1373 result = CGF.Builder.CreateBitCast(result,
1374 cast<llvm::PointerType>(origType)->getElementType());
1375
1376 return result;
1377}
1378
1379/// Perform an operation having the following signature:
1380/// i8* (i8**, i8*)
1381static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1382 llvm::Value *addr,
1383 llvm::Value *value,
1384 llvm::Constant *&fn,
1385 llvm::StringRef fnName,
1386 bool ignored) {
1387 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1388 == value->getType());
1389
1390 if (!fn) {
1391 std::vector<const llvm::Type*> argTypes(2);
1392 argTypes[0] = CGF.Int8PtrPtrTy;
1393 argTypes[1] = CGF.Int8PtrTy;
1394
1395 const llvm::FunctionType *fnType
1396 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1397 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1398 }
1399
1400 const llvm::Type *origType = value->getType();
1401
1402 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1403 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1404
1405 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1406 result->setDoesNotThrow();
1407
1408 if (ignored) return 0;
1409
1410 return CGF.Builder.CreateBitCast(result, origType);
1411}
1412
1413/// Perform an operation having the following signature:
1414/// void (i8**, i8**)
1415static void emitARCCopyOperation(CodeGenFunction &CGF,
1416 llvm::Value *dst,
1417 llvm::Value *src,
1418 llvm::Constant *&fn,
1419 llvm::StringRef fnName) {
1420 assert(dst->getType() == src->getType());
1421
1422 if (!fn) {
1423 std::vector<const llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
1424 const llvm::FunctionType *fnType
1425 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1426 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1427 }
1428
1429 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1430 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1431
1432 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1433 result->setDoesNotThrow();
1434}
1435
1436/// Produce the code to do a retain. Based on the type, calls one of:
1437/// call i8* @objc_retain(i8* %value)
1438/// call i8* @objc_retainBlock(i8* %value)
1439llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1440 if (type->isBlockPointerType())
1441 return EmitARCRetainBlock(value);
1442 else
1443 return EmitARCRetainNonBlock(value);
1444}
1445
1446/// Retain the given object, with normal retain semantics.
1447/// call i8* @objc_retain(i8* %value)
1448llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1449 return emitARCValueOperation(*this, value,
1450 CGM.getARCEntrypoints().objc_retain,
1451 "objc_retain");
1452}
1453
1454/// Retain the given block, with _Block_copy semantics.
1455/// call i8* @objc_retainBlock(i8* %value)
1456llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1457 return emitARCValueOperation(*this, value,
1458 CGM.getARCEntrypoints().objc_retainBlock,
1459 "objc_retainBlock");
1460}
1461
1462/// Retain the given object which is the result of a function call.
1463/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1464///
1465/// Yes, this function name is one character away from a different
1466/// call with completely different semantics.
1467llvm::Value *
1468CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1469 // Fetch the void(void) inline asm which marks that we're going to
1470 // retain the autoreleased return value.
1471 llvm::InlineAsm *&marker
1472 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1473 if (!marker) {
1474 llvm::StringRef assembly
1475 = CGM.getTargetCodeGenInfo()
1476 .getARCRetainAutoreleasedReturnValueMarker();
1477
1478 // If we have an empty assembly string, there's nothing to do.
1479 if (assembly.empty()) {
1480
1481 // Otherwise, at -O0, build an inline asm that we're going to call
1482 // in a moment.
1483 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1484 llvm::FunctionType *type =
1485 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1486 /*variadic*/ false);
1487
1488 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1489
1490 // If we're at -O1 and above, we don't want to litter the code
1491 // with this marker yet, so leave a breadcrumb for the ARC
1492 // optimizer to pick up.
1493 } else {
1494 llvm::NamedMDNode *metadata =
1495 CGM.getModule().getOrInsertNamedMetadata(
1496 "clang.arc.retainAutoreleasedReturnValueMarker");
1497 assert(metadata->getNumOperands() <= 1);
1498 if (metadata->getNumOperands() == 0) {
1499 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1500 llvm::Value *args[] = { string };
1501 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), args));
1502 }
1503 }
1504 }
1505
1506 // Call the marker asm if we made one, which we do only at -O0.
1507 if (marker) Builder.CreateCall(marker);
1508
1509 return emitARCValueOperation(*this, value,
1510 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1511 "objc_retainAutoreleasedReturnValue");
1512}
1513
1514/// Release the given object.
1515/// call void @objc_release(i8* %value)
1516void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1517 if (isa<llvm::ConstantPointerNull>(value)) return;
1518
1519 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1520 if (!fn) {
1521 std::vector<const llvm::Type*> args(1, Int8PtrTy);
1522 const llvm::FunctionType *fnType =
1523 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1524 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1525 }
1526
1527 // Cast the argument to 'id'.
1528 value = Builder.CreateBitCast(value, Int8PtrTy);
1529
1530 // Call objc_release.
1531 llvm::CallInst *call = Builder.CreateCall(fn, value);
1532 call->setDoesNotThrow();
1533
1534 if (!precise) {
1535 llvm::SmallVector<llvm::Value*,1> args;
1536 call->setMetadata("clang.imprecise_release",
1537 llvm::MDNode::get(Builder.getContext(), args));
1538 }
1539}
1540
1541/// Store into a strong object. Always calls this:
1542/// call void @objc_storeStrong(i8** %addr, i8* %value)
1543llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1544 llvm::Value *value,
1545 bool ignored) {
1546 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1547 == value->getType());
1548
1549 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1550 if (!fn) {
1551 const llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
1552 const llvm::FunctionType *fnType
1553 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1554 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1555 }
1556
1557 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1558 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1559
1560 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1561
1562 if (ignored) return 0;
1563 return value;
1564}
1565
1566/// Store into a strong object. Sometimes calls this:
1567/// call void @objc_storeStrong(i8** %addr, i8* %value)
1568/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001569llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001570 llvm::Value *newValue,
1571 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001572 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001573 bool isBlock = type->isBlockPointerType();
1574
1575 // Use a store barrier at -O0 unless this is a block type or the
1576 // lvalue is inadequately aligned.
1577 if (shouldUseFusedARCCalls() &&
1578 !isBlock &&
1579 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1580 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1581 }
1582
1583 // Otherwise, split it out.
1584
1585 // Retain the new value.
1586 newValue = EmitARCRetain(type, newValue);
1587
1588 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001589 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001590
1591 // Store. We do this before the release so that any deallocs won't
1592 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001593 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001594
1595 // Finally, release the old value.
1596 EmitARCRelease(oldValue, /*precise*/ false);
1597
1598 return newValue;
1599}
1600
1601/// Autorelease the given object.
1602/// call i8* @objc_autorelease(i8* %value)
1603llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1604 return emitARCValueOperation(*this, value,
1605 CGM.getARCEntrypoints().objc_autorelease,
1606 "objc_autorelease");
1607}
1608
1609/// Autorelease the given object.
1610/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1611llvm::Value *
1612CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1613 return emitARCValueOperation(*this, value,
1614 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1615 "objc_autoreleaseReturnValue");
1616}
1617
1618/// Do a fused retain/autorelease of the given object.
1619/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1620llvm::Value *
1621CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1622 return emitARCValueOperation(*this, value,
1623 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1624 "objc_retainAutoreleaseReturnValue");
1625}
1626
1627/// Do a fused retain/autorelease of the given object.
1628/// call i8* @objc_retainAutorelease(i8* %value)
1629/// or
1630/// %retain = call i8* @objc_retainBlock(i8* %value)
1631/// call i8* @objc_autorelease(i8* %retain)
1632llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1633 llvm::Value *value) {
1634 if (!type->isBlockPointerType())
1635 return EmitARCRetainAutoreleaseNonBlock(value);
1636
1637 if (isa<llvm::ConstantPointerNull>(value)) return value;
1638
1639 const llvm::Type *origType = value->getType();
1640 value = Builder.CreateBitCast(value, Int8PtrTy);
1641 value = EmitARCRetainBlock(value);
1642 value = EmitARCAutorelease(value);
1643 return Builder.CreateBitCast(value, origType);
1644}
1645
1646/// Do a fused retain/autorelease of the given object.
1647/// call i8* @objc_retainAutorelease(i8* %value)
1648llvm::Value *
1649CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1650 return emitARCValueOperation(*this, value,
1651 CGM.getARCEntrypoints().objc_retainAutorelease,
1652 "objc_retainAutorelease");
1653}
1654
1655/// i8* @objc_loadWeak(i8** %addr)
1656/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1657llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1658 return emitARCLoadOperation(*this, addr,
1659 CGM.getARCEntrypoints().objc_loadWeak,
1660 "objc_loadWeak");
1661}
1662
1663/// i8* @objc_loadWeakRetained(i8** %addr)
1664llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1665 return emitARCLoadOperation(*this, addr,
1666 CGM.getARCEntrypoints().objc_loadWeakRetained,
1667 "objc_loadWeakRetained");
1668}
1669
1670/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1671/// Returns %value.
1672llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1673 llvm::Value *value,
1674 bool ignored) {
1675 return emitARCStoreOperation(*this, addr, value,
1676 CGM.getARCEntrypoints().objc_storeWeak,
1677 "objc_storeWeak", ignored);
1678}
1679
1680/// i8* @objc_initWeak(i8** %addr, i8* %value)
1681/// Returns %value. %addr is known to not have a current weak entry.
1682/// Essentially equivalent to:
1683/// *addr = nil; objc_storeWeak(addr, value);
1684void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1685 // If we're initializing to null, just write null to memory; no need
1686 // to get the runtime involved. But don't do this if optimization
1687 // is enabled, because accounting for this would make the optimizer
1688 // much more complicated.
1689 if (isa<llvm::ConstantPointerNull>(value) &&
1690 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1691 Builder.CreateStore(value, addr);
1692 return;
1693 }
1694
1695 emitARCStoreOperation(*this, addr, value,
1696 CGM.getARCEntrypoints().objc_initWeak,
1697 "objc_initWeak", /*ignored*/ true);
1698}
1699
1700/// void @objc_destroyWeak(i8** %addr)
1701/// Essentially objc_storeWeak(addr, nil).
1702void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1703 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1704 if (!fn) {
1705 std::vector<const llvm::Type*> args(1, Int8PtrPtrTy);
1706 const llvm::FunctionType *fnType =
1707 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1708 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1709 }
1710
1711 // Cast the argument to 'id*'.
1712 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1713
1714 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1715 call->setDoesNotThrow();
1716}
1717
1718/// void @objc_moveWeak(i8** %dest, i8** %src)
1719/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1720/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1721void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1722 emitARCCopyOperation(*this, dst, src,
1723 CGM.getARCEntrypoints().objc_moveWeak,
1724 "objc_moveWeak");
1725}
1726
1727/// void @objc_copyWeak(i8** %dest, i8** %src)
1728/// Disregards the current value in %dest. Essentially
1729/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1730void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1731 emitARCCopyOperation(*this, dst, src,
1732 CGM.getARCEntrypoints().objc_copyWeak,
1733 "objc_copyWeak");
1734}
1735
1736/// Produce the code to do a objc_autoreleasepool_push.
1737/// call i8* @objc_autoreleasePoolPush(void)
1738llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1739 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1740 if (!fn) {
1741 const llvm::FunctionType *fnType =
1742 llvm::FunctionType::get(Int8PtrTy, false);
1743 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1744 }
1745
1746 llvm::CallInst *call = Builder.CreateCall(fn);
1747 call->setDoesNotThrow();
1748
1749 return call;
1750}
1751
1752/// Produce the code to do a primitive release.
1753/// call void @objc_autoreleasePoolPop(i8* %ptr)
1754void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1755 assert(value->getType() == Int8PtrTy);
1756
1757 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1758 if (!fn) {
1759 std::vector<const llvm::Type*> args(1, Int8PtrTy);
1760 const llvm::FunctionType *fnType =
1761 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1762
1763 // We don't want to use a weak import here; instead we should not
1764 // fall into this path.
1765 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1766 }
1767
1768 llvm::CallInst *call = Builder.CreateCall(fn, value);
1769 call->setDoesNotThrow();
1770}
1771
1772/// Produce the code to do an MRR version objc_autoreleasepool_push.
1773/// Which is: [[NSAutoreleasePool alloc] init];
1774/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1775/// init is declared as: - (id) init; in its NSObject super class.
1776///
1777llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1778 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1779 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1780 // [NSAutoreleasePool alloc]
1781 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1782 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1783 CallArgList Args;
1784 RValue AllocRV =
1785 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1786 getContext().getObjCIdType(),
1787 AllocSel, Receiver, Args);
1788
1789 // [Receiver init]
1790 Receiver = AllocRV.getScalarVal();
1791 II = &CGM.getContext().Idents.get("init");
1792 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1793 RValue InitRV =
1794 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1795 getContext().getObjCIdType(),
1796 InitSel, Receiver, Args);
1797 return InitRV.getScalarVal();
1798}
1799
1800/// Produce the code to do a primitive release.
1801/// [tmp drain];
1802void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1803 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1804 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1805 CallArgList Args;
1806 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1807 getContext().VoidTy, DrainSel, Arg, Args);
1808}
1809
John McCallbdc4d802011-07-09 01:37:26 +00001810void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1811 llvm::Value *addr,
1812 QualType type) {
1813 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1814 CGF.EmitARCRelease(ptr, /*precise*/ true);
1815}
1816
1817void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1818 llvm::Value *addr,
1819 QualType type) {
1820 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1821 CGF.EmitARCRelease(ptr, /*precise*/ false);
1822}
1823
1824void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1825 llvm::Value *addr,
1826 QualType type) {
1827 CGF.EmitARCDestroyWeak(addr);
1828}
1829
John McCallf85e1932011-06-15 23:02:42 +00001830namespace {
1831 struct ObjCReleasingCleanup : EHScopeStack::Cleanup {
1832 private:
1833 QualType type;
1834 llvm::Value *addr;
John McCallbdc4d802011-07-09 01:37:26 +00001835 CodeGenFunction::Destroyer &destroyer;
John McCallf85e1932011-06-15 23:02:42 +00001836
1837 protected:
John McCallbdc4d802011-07-09 01:37:26 +00001838 ObjCReleasingCleanup(QualType type, llvm::Value *addr,
1839 CodeGenFunction::Destroyer *destroyer)
1840 : type(type), addr(addr), destroyer(*destroyer) {}
John McCallf85e1932011-06-15 23:02:42 +00001841
1842 virtual llvm::Value *getAddress(CodeGenFunction &CGF,
1843 llvm::Value *addr) {
1844 return addr;
1845 }
1846
John McCallf85e1932011-06-15 23:02:42 +00001847 public:
1848 void Emit(CodeGenFunction &CGF, bool isForEH) {
1849 const ArrayType *arrayType = CGF.getContext().getAsArrayType(type);
1850
1851 llvm::Value *addr = getAddress(CGF, this->addr);
1852
1853 // If we don't have an array type, this is easy.
1854 if (!arrayType)
John McCallbdc4d802011-07-09 01:37:26 +00001855 return destroyer(CGF, addr, type);
John McCallf85e1932011-06-15 23:02:42 +00001856
1857 llvm::Value *begin = addr;
1858 QualType baseType;
1859
1860 // Otherwise, this is more painful.
John McCallbdc4d802011-07-09 01:37:26 +00001861 llvm::Value *count = CGF.emitArrayLength(arrayType, baseType, begin);
John McCallf85e1932011-06-15 23:02:42 +00001862
1863 assert(baseType == CGF.getContext().getBaseElementType(arrayType));
1864
1865 llvm::BasicBlock *incomingBB = CGF.Builder.GetInsertBlock();
1866
1867 // id *cur = begin;
1868 // id *end = begin + count;
1869 llvm::Value *end =
1870 CGF.Builder.CreateInBoundsGEP(begin, count, "array.end");
1871
1872 // loopBB:
1873 llvm::BasicBlock *loopBB = CGF.createBasicBlock("release-loop");
1874 CGF.EmitBlock(loopBB);
1875
1876 llvm::PHINode *cur = CGF.Builder.CreatePHI(begin->getType(), 2, "cur");
1877 cur->addIncoming(begin, incomingBB);
1878
1879 // if (cur == end) goto endBB;
1880 llvm::Value *eq = CGF.Builder.CreateICmpEQ(cur, end, "release-loop.done");
1881 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("release-loop.body");
1882 llvm::BasicBlock *endBB = CGF.createBasicBlock("release-loop.cont");
1883 CGF.Builder.CreateCondBr(eq, endBB, bodyBB);
1884 CGF.EmitBlock(bodyBB);
1885
1886 // Release the value at 'cur'.
John McCallbdc4d802011-07-09 01:37:26 +00001887 destroyer(CGF, cur, baseType);
John McCallf85e1932011-06-15 23:02:42 +00001888
1889 // ++cur;
1890 // goto loopBB;
1891 llvm::Value *next = CGF.Builder.CreateConstInBoundsGEP1_32(cur, 1);
1892 cur->addIncoming(next, CGF.Builder.GetInsertBlock());
1893 CGF.Builder.CreateBr(loopBB);
1894
1895 // endBB:
1896 CGF.EmitBlock(endBB);
1897 }
John McCallf85e1932011-06-15 23:02:42 +00001898 };
1899
1900 /// A cleanup that calls @objc_release on all the objects to release.
1901 struct CallReleaseForObject : ObjCReleasingCleanup {
John McCallbdc4d802011-07-09 01:37:26 +00001902 CallReleaseForObject(QualType type, llvm::Value *addr,
1903 CodeGenFunction::Destroyer *destroyer)
1904 : ObjCReleasingCleanup(type, addr, destroyer) {}
John McCallf85e1932011-06-15 23:02:42 +00001905
Douglas Gregord7b23162011-06-22 16:12:01 +00001906 using ObjCReleasingCleanup::Emit;
1907 static void Emit(CodeGenFunction &CGF, bool IsForEH,
John McCallbdc4d802011-07-09 01:37:26 +00001908 QualType type, llvm::Value *addr,
1909 CodeGenFunction::Destroyer *destroyer) {
Douglas Gregord7b23162011-06-22 16:12:01 +00001910 // EHScopeStack::Cleanup objects can never have their destructors called,
1911 // so use placement new to construct our temporary object.
1912 union {
1913 void* align;
1914 char data[sizeof(CallReleaseForObject)];
1915 };
1916
1917 CallReleaseForObject *Object
John McCallbdc4d802011-07-09 01:37:26 +00001918 = new (&align) CallReleaseForObject(type, addr, destroyer);
Douglas Gregord7b23162011-06-22 16:12:01 +00001919 Object->Emit(CGF, IsForEH);
Douglas Gregor34aace82011-06-22 16:43:25 +00001920 (void)data[0];
Douglas Gregord7b23162011-06-22 16:12:01 +00001921 }
John McCallf85e1932011-06-15 23:02:42 +00001922 };
1923
1924 /// A cleanup that calls @objc_storeStrong(nil) on all the objects to
1925 /// release in an ivar.
1926 struct CallReleaseForIvar : ObjCReleasingCleanup {
1927 const ObjCIvarDecl *ivar;
1928 CallReleaseForIvar(const ObjCIvarDecl *ivar, llvm::Value *self)
John McCallbdc4d802011-07-09 01:37:26 +00001929 : ObjCReleasingCleanup(ivar->getType(), self,
1930 destroyARCStrongIvar), ivar(ivar) {}
John McCallf85e1932011-06-15 23:02:42 +00001931
1932 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *addr) {
1933 LValue lvalue
1934 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1935 return lvalue.getAddress();
1936 }
1937
John McCallbdc4d802011-07-09 01:37:26 +00001938 static void destroyARCStrongIvar(CodeGenFunction &CGF,
1939 llvm::Value *addr,
1940 QualType type) {
John McCallf85e1932011-06-15 23:02:42 +00001941 llvm::Value *null = getNullForVariable(addr);
1942 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1943 }
1944 };
1945
1946 /// A cleanup that calls @objc_release on all of the objects to release in
1947 /// a field.
1948 struct CallReleaseForField : CallReleaseForObject {
1949 const FieldDecl *Field;
1950
1951 explicit CallReleaseForField(const FieldDecl *Field)
John McCallbdc4d802011-07-09 01:37:26 +00001952 : CallReleaseForObject(Field->getType(), 0,
1953 CodeGenFunction::destroyARCStrongPrecise),
John McCallf85e1932011-06-15 23:02:42 +00001954 Field(Field) { }
1955
1956 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *) {
1957 llvm::Value *This = CGF.LoadCXXThis();
1958 LValue LV = CGF.EmitLValueForField(This, Field, 0);
1959 return LV.getAddress();
1960 }
1961 };
1962
1963 /// A cleanup that calls @objc_weak_release on all the objects to
1964 /// release in an object.
1965 struct CallWeakReleaseForObject : ObjCReleasingCleanup {
1966 CallWeakReleaseForObject(QualType type, llvm::Value *addr)
John McCallbdc4d802011-07-09 01:37:26 +00001967 : ObjCReleasingCleanup(type, addr, CodeGenFunction::destroyARCWeak) {}
John McCallf85e1932011-06-15 23:02:42 +00001968
Douglas Gregord7b23162011-06-22 16:12:01 +00001969 using ObjCReleasingCleanup::Emit;
1970 static void Emit(CodeGenFunction &CGF, bool IsForEH,
1971 QualType type, llvm::Value *addr) {
1972 // EHScopeStack::Cleanup objects can never have their destructors called,
1973 // so use placement new to construct our temporary object.
1974 union {
1975 void* align;
1976 char data[sizeof(CallWeakReleaseForObject)];
1977 };
1978
1979 CallWeakReleaseForObject *Object
1980 = new (&align) CallWeakReleaseForObject(type, addr);
1981 Object->Emit(CGF, IsForEH);
Douglas Gregor34aace82011-06-22 16:43:25 +00001982 (void)data[0];
Douglas Gregord7b23162011-06-22 16:12:01 +00001983 }
John McCallf85e1932011-06-15 23:02:42 +00001984 };
1985
1986
1987 /// A cleanup that calls @objc_weak_release on all the objects to
1988 /// release in an ivar.
1989 struct CallWeakReleaseForIvar : CallWeakReleaseForObject {
1990 const ObjCIvarDecl *ivar;
1991 CallWeakReleaseForIvar(const ObjCIvarDecl *ivar, llvm::Value *self)
1992 : CallWeakReleaseForObject(ivar->getType(), self), ivar(ivar) {}
1993
1994 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *addr) {
1995 LValue lvalue
1996 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1997 return lvalue.getAddress();
1998 }
1999 };
2000
2001 /// A cleanup that calls @objc_weak_release on all the objects to
2002 /// release in a field;
2003 struct CallWeakReleaseForField : CallWeakReleaseForObject {
2004 const FieldDecl *Field;
2005 CallWeakReleaseForField(const FieldDecl *Field)
2006 : CallWeakReleaseForObject(Field->getType(), 0), Field(Field) {}
2007
2008 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *) {
2009 llvm::Value *This = CGF.LoadCXXThis();
2010 LValue LV = CGF.EmitLValueForField(This, Field, 0);
2011 return LV.getAddress();
2012 }
2013 };
2014
2015 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2016 llvm::Value *Token;
2017
2018 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2019
2020 void Emit(CodeGenFunction &CGF, bool isForEH) {
2021 CGF.EmitObjCAutoreleasePoolPop(Token);
2022 }
2023 };
2024 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2025 llvm::Value *Token;
2026
2027 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2028
2029 void Emit(CodeGenFunction &CGF, bool isForEH) {
2030 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2031 }
2032 };
2033}
2034
2035void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2036 if (CGM.getLangOptions().ObjCAutoRefCount)
2037 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2038 else
2039 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2040}
2041
2042/// PushARCReleaseCleanup - Enter a cleanup to perform a release on a
2043/// given object or array of objects.
2044void CodeGenFunction::PushARCReleaseCleanup(CleanupKind cleanupKind,
2045 QualType type,
2046 llvm::Value *addr,
Douglas Gregord7b23162011-06-22 16:12:01 +00002047 bool precise,
2048 bool forFullExpr) {
John McCallbdc4d802011-07-09 01:37:26 +00002049 Destroyer *dtor =
2050 (precise ? destroyARCStrongPrecise : destroyARCStrongImprecise);
Douglas Gregord7b23162011-06-22 16:12:01 +00002051 if (forFullExpr)
John McCallbdc4d802011-07-09 01:37:26 +00002052 pushFullExprCleanup<CallReleaseForObject>(cleanupKind, type, addr, dtor);
Douglas Gregord7b23162011-06-22 16:12:01 +00002053 else
John McCallbdc4d802011-07-09 01:37:26 +00002054 EHStack.pushCleanup<CallReleaseForObject>(cleanupKind, type, addr, dtor);
John McCallf85e1932011-06-15 23:02:42 +00002055}
2056
2057/// PushARCWeakReleaseCleanup - Enter a cleanup to perform a weak
2058/// release on the given object or array of objects.
2059void CodeGenFunction::PushARCWeakReleaseCleanup(CleanupKind cleanupKind,
2060 QualType type,
Douglas Gregord7b23162011-06-22 16:12:01 +00002061 llvm::Value *addr,
2062 bool forFullExpr) {
2063 if (forFullExpr)
2064 pushFullExprCleanup<CallWeakReleaseForObject>(cleanupKind, type, addr);
2065 else
2066 EHStack.pushCleanup<CallWeakReleaseForObject>(cleanupKind, type, addr);
John McCallf85e1932011-06-15 23:02:42 +00002067}
2068
2069/// PushARCReleaseCleanup - Enter a cleanup to perform a release on a
2070/// given object or array of objects.
2071void CodeGenFunction::PushARCFieldReleaseCleanup(CleanupKind cleanupKind,
2072 const FieldDecl *field) {
2073 EHStack.pushCleanup<CallReleaseForField>(cleanupKind, field);
2074}
2075
2076/// PushARCWeakReleaseCleanup - Enter a cleanup to perform a weak
2077/// release on the given object or array of objects.
2078void CodeGenFunction::PushARCFieldWeakReleaseCleanup(CleanupKind cleanupKind,
2079 const FieldDecl *field) {
2080 EHStack.pushCleanup<CallWeakReleaseForField>(cleanupKind, field);
2081}
2082
2083static void pushReleaseForIvar(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
2084 llvm::Value *self) {
2085 CGF.EHStack.pushCleanup<CallReleaseForIvar>(CGF.getARCCleanupKind(),
2086 ivar, self);
2087}
2088
2089static void pushWeakReleaseForIvar(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
2090 llvm::Value *self) {
2091 CGF.EHStack.pushCleanup<CallWeakReleaseForIvar>(CGF.getARCCleanupKind(),
2092 ivar, self);
2093}
2094
2095static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2096 LValue lvalue,
2097 QualType type) {
2098 switch (type.getObjCLifetime()) {
2099 case Qualifiers::OCL_None:
2100 case Qualifiers::OCL_ExplicitNone:
2101 case Qualifiers::OCL_Strong:
2102 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002103 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002104 false);
2105
2106 case Qualifiers::OCL_Weak:
2107 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2108 true);
2109 }
2110
2111 llvm_unreachable("impossible lifetime!");
2112 return TryEmitResult();
2113}
2114
2115static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2116 const Expr *e) {
2117 e = e->IgnoreParens();
2118 QualType type = e->getType();
2119
2120 // As a very special optimization, in ARC++, if the l-value is the
2121 // result of a non-volatile assignment, do a simple retain of the
2122 // result of the call to objc_storeWeak instead of reloading.
2123 if (CGF.getLangOptions().CPlusPlus &&
2124 !type.isVolatileQualified() &&
2125 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2126 isa<BinaryOperator>(e) &&
2127 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2128 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2129
2130 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2131}
2132
2133static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2134 llvm::Value *value);
2135
2136/// Given that the given expression is some sort of call (which does
2137/// not return retained), emit a retain following it.
2138static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2139 llvm::Value *value = CGF.EmitScalarExpr(e);
2140 return emitARCRetainAfterCall(CGF, value);
2141}
2142
2143static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2144 llvm::Value *value) {
2145 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2146 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2147
2148 // Place the retain immediately following the call.
2149 CGF.Builder.SetInsertPoint(call->getParent(),
2150 ++llvm::BasicBlock::iterator(call));
2151 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2152
2153 CGF.Builder.restoreIP(ip);
2154 return value;
2155 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2156 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2157
2158 // Place the retain at the beginning of the normal destination block.
2159 llvm::BasicBlock *BB = invoke->getNormalDest();
2160 CGF.Builder.SetInsertPoint(BB, BB->begin());
2161 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2162
2163 CGF.Builder.restoreIP(ip);
2164 return value;
2165
2166 // Bitcasts can arise because of related-result returns. Rewrite
2167 // the operand.
2168 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2169 llvm::Value *operand = bitcast->getOperand(0);
2170 operand = emitARCRetainAfterCall(CGF, operand);
2171 bitcast->setOperand(0, operand);
2172 return bitcast;
2173
2174 // Generic fall-back case.
2175 } else {
2176 // Retain using the non-block variant: we never need to do a copy
2177 // of a block that's been returned to us.
2178 return CGF.EmitARCRetainNonBlock(value);
2179 }
2180}
2181
2182static TryEmitResult
2183tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002184 // The desired result type, if it differs from the type of the
2185 // ultimate opaque expression.
2186 const llvm::Type *resultType = 0;
2187
Douglas Gregord1bd98a2011-06-22 16:32:26 +00002188 // If we're loading retained from a __strong xvalue, we can avoid
2189 // an extra retain/release pair by zeroing out the source of this
2190 // "move" operation.
John McCalldf7b0912011-06-25 02:26:44 +00002191 if (e->isXValue() && !e->getType().isConstQualified() &&
Douglas Gregord1bd98a2011-06-22 16:32:26 +00002192 e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
2193 // Emit the lvalue
2194 LValue lv = CGF.EmitLValue(e);
2195
2196 // Load the object pointer and cast it to the appropriate type.
2197 QualType exprType = e->getType();
John McCall545d9962011-06-25 02:11:03 +00002198 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
Douglas Gregord1bd98a2011-06-22 16:32:26 +00002199
2200 if (resultType)
2201 result = CGF.Builder.CreateBitCast(result, resultType);
2202
2203 // Set the source pointer to NULL.
2204 llvm::Value *null
2205 = llvm::ConstantPointerNull::get(
2206 cast<llvm::PointerType>(CGF.ConvertType(exprType)));
John McCall545d9962011-06-25 02:11:03 +00002207 CGF.EmitStoreOfScalar(null, lv);
Douglas Gregord1bd98a2011-06-22 16:32:26 +00002208
2209 return TryEmitResult(result, true);
2210 }
2211
John McCallf85e1932011-06-15 23:02:42 +00002212 while (true) {
2213 e = e->IgnoreParens();
2214
2215 // There's a break at the end of this if-chain; anything
2216 // that wants to keep looping has to explicitly continue.
2217 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2218 switch (ce->getCastKind()) {
2219 // No-op casts don't change the type, so we just ignore them.
2220 case CK_NoOp:
2221 e = ce->getSubExpr();
2222 continue;
2223
2224 case CK_LValueToRValue: {
2225 TryEmitResult loadResult
2226 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2227 if (resultType) {
2228 llvm::Value *value = loadResult.getPointer();
2229 value = CGF.Builder.CreateBitCast(value, resultType);
2230 loadResult.setPointer(value);
2231 }
2232 return loadResult;
2233 }
2234
2235 // These casts can change the type, so remember that and
2236 // soldier on. We only need to remember the outermost such
2237 // cast, though.
2238 case CK_AnyPointerToObjCPointerCast:
2239 case CK_AnyPointerToBlockPointerCast:
2240 case CK_BitCast:
2241 if (!resultType)
2242 resultType = CGF.ConvertType(ce->getType());
2243 e = ce->getSubExpr();
2244 assert(e->getType()->hasPointerRepresentation());
2245 continue;
2246
2247 // For consumptions, just emit the subexpression and thus elide
2248 // the retain/release pair.
2249 case CK_ObjCConsumeObject: {
2250 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2251 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2252 return TryEmitResult(result, true);
2253 }
2254
John McCall7e5e5f42011-07-07 06:58:02 +00002255 // For reclaims, emit the subexpression as a retained call and
2256 // skip the consumption.
2257 case CK_ObjCReclaimReturnedObject: {
2258 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2259 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2260 return TryEmitResult(result, true);
2261 }
2262
John McCallf85e1932011-06-15 23:02:42 +00002263 case CK_GetObjCProperty: {
2264 llvm::Value *result = emitARCRetainCall(CGF, ce);
2265 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2266 return TryEmitResult(result, true);
2267 }
2268
2269 default:
2270 break;
2271 }
2272
2273 // Skip __extension__.
2274 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2275 if (op->getOpcode() == UO_Extension) {
2276 e = op->getSubExpr();
2277 continue;
2278 }
2279
2280 // For calls and message sends, use the retained-call logic.
2281 // Delegate inits are a special case in that they're the only
2282 // returns-retained expression that *isn't* surrounded by
2283 // a consume.
2284 } else if (isa<CallExpr>(e) ||
2285 (isa<ObjCMessageExpr>(e) &&
2286 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2287 llvm::Value *result = emitARCRetainCall(CGF, e);
2288 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2289 return TryEmitResult(result, true);
2290 }
2291
2292 // Conservatively halt the search at any other expression kind.
2293 break;
2294 }
2295
2296 // We didn't find an obvious production, so emit what we've got and
2297 // tell the caller that we didn't manage to retain.
2298 llvm::Value *result = CGF.EmitScalarExpr(e);
2299 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2300 return TryEmitResult(result, false);
2301}
2302
2303static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2304 LValue lvalue,
2305 QualType type) {
2306 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2307 llvm::Value *value = result.getPointer();
2308 if (!result.getInt())
2309 value = CGF.EmitARCRetain(type, value);
2310 return value;
2311}
2312
2313/// EmitARCRetainScalarExpr - Semantically equivalent to
2314/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2315/// best-effort attempt to peephole expressions that naturally produce
2316/// retained objects.
2317llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2318 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2319 llvm::Value *value = result.getPointer();
2320 if (!result.getInt())
2321 value = EmitARCRetain(e->getType(), value);
2322 return value;
2323}
2324
2325llvm::Value *
2326CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2327 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2328 llvm::Value *value = result.getPointer();
2329 if (result.getInt())
2330 value = EmitARCAutorelease(value);
2331 else
2332 value = EmitARCRetainAutorelease(e->getType(), value);
2333 return value;
2334}
2335
2336std::pair<LValue,llvm::Value*>
2337CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2338 bool ignored) {
2339 // Evaluate the RHS first.
2340 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2341 llvm::Value *value = result.getPointer();
2342
2343 LValue lvalue = EmitLValue(e->getLHS());
2344
2345 // If the RHS was emitted retained, expand this.
2346 if (result.getInt()) {
2347 llvm::Value *oldValue =
2348 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2349 lvalue.getAlignment(), e->getType(),
2350 lvalue.getTBAAInfo());
2351 EmitStoreOfScalar(value, lvalue.getAddress(),
2352 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2353 e->getType(), lvalue.getTBAAInfo());
2354 EmitARCRelease(oldValue, /*precise*/ false);
2355 } else {
John McCall545d9962011-06-25 02:11:03 +00002356 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002357 }
2358
2359 return std::pair<LValue,llvm::Value*>(lvalue, value);
2360}
2361
2362std::pair<LValue,llvm::Value*>
2363CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2364 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2365 LValue lvalue = EmitLValue(e->getLHS());
2366
2367 EmitStoreOfScalar(value, lvalue.getAddress(),
2368 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2369 e->getType(), lvalue.getTBAAInfo());
2370
2371 return std::pair<LValue,llvm::Value*>(lvalue, value);
2372}
2373
2374void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2375 const ObjCAutoreleasePoolStmt &ARPS) {
2376 const Stmt *subStmt = ARPS.getSubStmt();
2377 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2378
2379 CGDebugInfo *DI = getDebugInfo();
2380 if (DI) {
2381 DI->setLocation(S.getLBracLoc());
2382 DI->EmitRegionStart(Builder);
2383 }
2384
2385 // Keep track of the current cleanup stack depth.
2386 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002387 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002388 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2389 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2390 } else {
2391 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2392 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2393 }
2394
2395 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2396 E = S.body_end(); I != E; ++I)
2397 EmitStmt(*I);
2398
2399 if (DI) {
2400 DI->setLocation(S.getRBracLoc());
2401 DI->EmitRegionEnd(Builder);
2402 }
2403}
John McCall0c24c802011-06-24 23:21:27 +00002404
2405/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2406/// make sure it survives garbage collection until this point.
2407void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2408 // We just use an inline assembly.
2409 const llvm::Type *paramTypes[] = { VoidPtrTy };
2410 llvm::FunctionType *extenderType
2411 = llvm::FunctionType::get(VoidTy, paramTypes, /*variadic*/ false);
2412 llvm::Value *extender
2413 = llvm::InlineAsm::get(extenderType,
2414 /* assembly */ "",
2415 /* constraints */ "r",
2416 /* side effects */ true);
2417
2418 object = Builder.CreateBitCast(object, VoidPtrTy);
2419 Builder.CreateCall(extender, object)->setDoesNotThrow();
2420}
2421
Ted Kremenek2979ec72008-04-09 15:51:31 +00002422CGObjCRuntime::~CGObjCRuntime() {}