blob: 4beb704d1596dd8f7ae3d29ad2f4bcd28aa6f838 [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32
33/// Given the address of a variable of pointer type, find the correct
34/// null to store into it.
35static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000036 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000037 cast<llvm::PointerType>(addr->getType())->getElementType();
38 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
39}
40
Chris Lattner8fdf3282008-06-24 17:04:18 +000041/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000042llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000043{
David Chisnall0d13f6f2010-01-23 02:40:42 +000044 llvm::Constant *C =
45 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000046 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000047 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000048}
49
50/// Emit a selector.
51llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
52 // Untyped selector.
53 // Note that this implementation allows for non-constant strings to be passed
54 // as arguments to @selector(). Currently, the only thing preventing this
55 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000056 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000057}
58
Daniel Dunbared7c6182008-08-20 00:28:19 +000059llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
60 // FIXME: This should pass the Decl not the name.
61 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
62}
Chris Lattner8fdf3282008-06-24 17:04:18 +000063
Douglas Gregor926df6c2011-06-11 01:09:30 +000064/// \brief Adjust the type of the result of an Objective-C message send
65/// expression when the method has a related result type.
66static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
67 const Expr *E,
68 const ObjCMethodDecl *Method,
69 RValue Result) {
70 if (!Method)
71 return Result;
John McCallf85e1932011-06-15 23:02:42 +000072
Douglas Gregor926df6c2011-06-11 01:09:30 +000073 if (!Method->hasRelatedResultType() ||
74 CGF.getContext().hasSameType(E->getType(), Method->getResultType()) ||
75 !Result.isScalar())
76 return Result;
77
78 // We have applied a related result type. Cast the rvalue appropriately.
79 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
80 CGF.ConvertType(E->getType())));
81}
Chris Lattner8fdf3282008-06-24 17:04:18 +000082
John 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'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000209 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000210 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 {
John McCallad346f42011-07-12 20:27:29 +0000221 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000222 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000223
224 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000225 const ObjCInterfaceDecl *iface = impl->getClassInterface();
226 if (!iface->getSuperClass()) return;
227
John McCall799d34e2011-07-13 18:26:47 +0000228 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
229
John McCallf85e1932011-06-15 23:02:42 +0000230 // Call [super dealloc] if we have a superclass.
231 llvm::Value *self = CGF.LoadObjCSelf();
232
233 CallArgList args;
234 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
235 CGF.getContext().VoidTy,
236 method->getSelector(),
237 iface,
John McCall799d34e2011-07-13 18:26:47 +0000238 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000239 self,
240 /*is class msg*/ false,
241 args,
242 method);
243 }
244};
245}
246
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000247/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
248/// the LLVM function and sets the other context used by
249/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000250void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000251 const ObjCContainerDecl *CD,
252 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000253 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000254 // Check if we should generate debug info for this method.
Devang Patelaa112892011-03-07 18:45:56 +0000255 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
256 DebugInfo = CGM.getModuleDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000257
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000258 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000259
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000260 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
261 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000262
John McCalld26bc762011-03-09 04:27:21 +0000263 args.push_back(OMD->getSelfDecl());
264 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000265
Chris Lattner89951a82009-02-20 18:43:26 +0000266 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
267 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000268 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000269
Peter Collingbourne14110472011-01-13 18:57:25 +0000270 CurGD = OMD;
271
Devang Patel8d3f8972011-05-19 23:37:41 +0000272 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000273
274 // In ARC, certain methods get an extra cleanup.
275 if (CGM.getLangOptions().ObjCAutoRefCount &&
276 OMD->isInstanceMethod() &&
277 OMD->getSelector().isUnarySelector()) {
278 const IdentifierInfo *ident =
279 OMD->getSelector().getIdentifierInfoForSlot(0);
280 if (ident->isStr("dealloc"))
281 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
282 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000283}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000284
John McCallf85e1932011-06-15 23:02:42 +0000285static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
286 LValue lvalue, QualType type);
287
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000288void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
289 bool IsAtomic, bool IsStrong) {
290 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
291 Ivar, 0);
292 llvm::Value *GetCopyStructFn =
293 CGM.getObjCRuntime().GetGetStructFunction();
294 CodeGenTypes &Types = CGM.getTypes();
295 // objc_copyStruct (ReturnValue, &structIvar,
296 // sizeof (Type of Ivar), isAtomic, false);
297 CallArgList Args;
John McCall0774cb82011-05-15 01:53:33 +0000298 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue, VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000299 Args.add(RV, getContext().VoidPtrTy);
John McCall0774cb82011-05-15 01:53:33 +0000300 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(), VoidPtrTy));
Eli Friedman04c9a492011-05-02 17:57:46 +0000301 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000302 // sizeof (Type of Ivar)
303 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
304 llvm::Value *SizeVal =
John McCall0774cb82011-05-15 01:53:33 +0000305 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000306 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000307 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000308 llvm::Value *isAtomic =
309 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
310 IsAtomic ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000311 Args.add(RValue::get(isAtomic), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000312 llvm::Value *hasStrong =
313 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
314 IsStrong ? 1 : 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000315 Args.add(RValue::get(hasStrong), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000316 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
317 FunctionType::ExtInfo()),
318 GetCopyStructFn, ReturnValueSlot(), Args);
319}
320
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000321/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000322/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000323void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000324 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000325 EmitStmt(OMD->getBody());
326 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000327}
328
Mike Stumpf5408fe2009-05-16 07:57:57 +0000329// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
330// AST for the whole body we can just fall back to having a GenerateFunction
331// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000332
333/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000334/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
335/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000336void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
337 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000338 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000339 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000340 bool IsAtomic =
341 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000342 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
343 assert(OMD && "Invalid call to generate getter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000344 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000345
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000346 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000347 // this. Non-atomic properties are directly evaluated.
348 // atomic 'copy' and 'retain' properties are also directly
349 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000350 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000351 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000352 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
353 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000354 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000355 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000357 if (!GetPropertyFn) {
358 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
359 FinishFunction();
360 return;
361 }
362
363 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
364 // FIXME: Can't this be simpler? This might even be worse than the
365 // corresponding gcc code.
366 CodeGenTypes &Types = CGM.getTypes();
367 ValueDecl *Cmd = OMD->getCmdDecl();
368 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
369 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000370 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000371 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000372 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000373 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000374 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000375 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000376 Args.add(RValue::get(SelfAsId), IdTy);
377 Args.add(RValue::get(CmdVal), Cmd->getType());
378 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
379 Args.add(RValue::get(True), getContext().BoolTy);
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000380 // FIXME: We shouldn't need to get the function info here, the
381 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000382 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000383 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000384 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000385 // We need to fix the type here. Ivars with copy & retain are
386 // always objects so we don't need to worry about complex or
387 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000388 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000389 Types.ConvertType(PD->getType())));
390 EmitReturnOfRValue(RV, PD->getType());
John McCallf85e1932011-06-15 23:02:42 +0000391
392 // objc_getProperty does an autorelease, so we should suppress ours.
393 AutoreleaseResult = false;
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000394 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000395 const llvm::Triple &Triple = getContext().Target.getTriple();
396 QualType IVART = Ivar->getType();
397 if (IsAtomic &&
398 IVART->isScalarType() &&
399 (Triple.getArch() == llvm::Triple::arm ||
400 Triple.getArch() == llvm::Triple::thumb) &&
401 (getContext().getTypeSizeInChars(IVART)
402 > CharUnits::fromQuantity(4)) &&
403 CGM.getObjCRuntime().GetGetStructFunction()) {
404 GenerateObjCGetterBody(Ivar, true, false);
405 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000406 else if (IsAtomic &&
407 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
408 Triple.getArch() == llvm::Triple::x86 &&
409 (getContext().getTypeSizeInChars(IVART)
410 > CharUnits::fromQuantity(4)) &&
411 CGM.getObjCRuntime().GetGetStructFunction()) {
412 GenerateObjCGetterBody(Ivar, true, false);
413 }
414 else if (IsAtomic &&
415 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
416 Triple.getArch() == llvm::Triple::x86_64 &&
417 (getContext().getTypeSizeInChars(IVART)
418 > CharUnits::fromQuantity(8)) &&
419 CGM.getObjCRuntime().GetGetStructFunction()) {
420 GenerateObjCGetterBody(Ivar, true, false);
421 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000422 else if (IVART->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000423 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
424 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000425 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
426 LV.isVolatileQualified());
427 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
428 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000429 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000430 bool IsStrong = false;
Fariborz Jahanian5fb65092011-04-05 23:01:27 +0000431 if ((IsStrong = IvarTypeWithAggrGCObjects(IVART))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000432 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000433 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000434 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000435 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000436 else {
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000437 const CXXRecordDecl *classDecl = IVART->getAsCXXRecordDecl();
438
439 if (PID->getGetterCXXConstructor() &&
Sean Hunt023df372011-05-09 18:22:59 +0000440 classDecl && !classDecl->hasTrivialDefaultConstructor()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000441 ReturnStmt *Stmt =
442 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000443 PID->getGetterCXXConstructor(),
444 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000445 EmitReturnStmt(*Stmt);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000446 } else if (IsAtomic &&
447 !IVART->isAnyComplexType() &&
448 Triple.getArch() == llvm::Triple::x86 &&
449 (getContext().getTypeSizeInChars(IVART)
450 > CharUnits::fromQuantity(4)) &&
451 CGM.getObjCRuntime().GetGetStructFunction()) {
452 GenerateObjCGetterBody(Ivar, true, false);
453 }
454 else if (IsAtomic &&
455 !IVART->isAnyComplexType() &&
456 Triple.getArch() == llvm::Triple::x86_64 &&
457 (getContext().getTypeSizeInChars(IVART)
458 > CharUnits::fromQuantity(8)) &&
459 CGM.getObjCRuntime().GetGetStructFunction()) {
460 GenerateObjCGetterBody(Ivar, true, false);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000461 }
462 else {
463 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
464 Ivar, 0);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000465 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000466 }
467 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000468 }
469 else {
470 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
John McCall545d9962011-06-25 02:11:03 +0000471 Ivar, 0);
John McCallf85e1932011-06-15 23:02:42 +0000472 QualType propType = PD->getType();
473
474 llvm::Value *value;
475 if (propType->isReferenceType()) {
476 value = LV.getAddress();
477 } else {
478 // In ARC, we want to emit this retained.
479 if (getLangOptions().ObjCAutoRefCount &&
480 PD->getType()->isObjCRetainableType())
481 value = emitARCRetainLoadOfScalar(*this, LV, IVART);
482 else
John McCall545d9962011-06-25 02:11:03 +0000483 value = EmitLoadOfLValue(LV).getScalarVal();
John McCallf85e1932011-06-15 23:02:42 +0000484
485 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian14086762011-03-28 23:47:18 +0000486 }
John McCallf85e1932011-06-15 23:02:42 +0000487
488 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000489 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000490 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000491
492 FinishFunction();
493}
494
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000495void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
496 ObjCIvarDecl *Ivar) {
497 // objc_copyStruct (&structIvar, &Arg,
498 // sizeof (struct something), true, false);
499 llvm::Value *GetCopyStructFn =
500 CGM.getObjCRuntime().GetSetStructFunction();
501 CodeGenTypes &Types = CGM.getTypes();
502 CallArgList Args;
503 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
504 RValue RV =
505 RValue::get(Builder.CreateBitCast(LV.getAddress(),
506 Types.ConvertType(getContext().VoidPtrTy)));
Eli Friedman04c9a492011-05-02 17:57:46 +0000507 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000508 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
509 llvm::Value *ArgAsPtrTy =
510 Builder.CreateBitCast(Arg,
511 Types.ConvertType(getContext().VoidPtrTy));
512 RV = RValue::get(ArgAsPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +0000513 Args.add(RV, getContext().VoidPtrTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000514 // sizeof (Type of Ivar)
515 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
516 llvm::Value *SizeVal =
517 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
518 Size.getQuantity());
Eli Friedman04c9a492011-05-02 17:57:46 +0000519 Args.add(RValue::get(SizeVal), getContext().LongTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000520 llvm::Value *True =
521 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Eli Friedman04c9a492011-05-02 17:57:46 +0000522 Args.add(RValue::get(True), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000523 llvm::Value *False =
524 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Eli Friedman04c9a492011-05-02 17:57:46 +0000525 Args.add(RValue::get(False), getContext().BoolTy);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000526 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
527 FunctionType::ExtInfo()),
528 GetCopyStructFn, ReturnValueSlot(), Args);
529}
530
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000531static bool
532IvarAssignHasTrvialAssignment(const ObjCPropertyImplDecl *PID,
533 QualType IvarT) {
534 bool HasTrvialAssignment = true;
535 if (PID->getSetterCXXAssignment()) {
536 const CXXRecordDecl *classDecl = IvarT->getAsCXXRecordDecl();
537 HasTrvialAssignment =
538 (!classDecl || classDecl->hasTrivialCopyAssignment());
539 }
540 return HasTrvialAssignment;
541}
542
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000543/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000544/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
545/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000546void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
547 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000548 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000549 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
550 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
551 assert(OMD && "Invalid call to generate setter (empty method)");
Devang Patel8d3f8972011-05-19 23:37:41 +0000552 StartObjCMethod(OMD, IMP->getClassInterface(), PID->getLocStart());
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000553 const llvm::Triple &Triple = getContext().Target.getTriple();
554 QualType IVART = Ivar->getType();
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000555 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump1eb44332009-09-09 15:08:12 +0000556 bool IsAtomic =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000557 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
558
559 // Determine if we should use an objc_setProperty call for
560 // this. Properties with 'copy' semantics always use it, as do
561 // non-atomic properties with 'release' semantics as long as we are
562 // not in gc-only mode.
563 if (IsCopy ||
564 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
565 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000566 llvm::Value *SetPropertyFn =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000567 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000569 if (!SetPropertyFn) {
570 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
571 FinishFunction();
572 return;
573 }
Mike Stump1eb44332009-09-09 15:08:12 +0000574
575 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000576 // <is-atomic>, <is-copy>).
577 // FIXME: Can't this be simpler? This might even be worse than the
578 // corresponding gcc code.
579 CodeGenTypes &Types = CGM.getTypes();
580 ValueDecl *Cmd = OMD->getCmdDecl();
581 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
582 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000583 llvm::Value *SelfAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000584 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000585 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattner89951a82009-02-20 18:43:26 +0000586 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump1eb44332009-09-09 15:08:12 +0000587 llvm::Value *ArgAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000588 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
589 Types.ConvertType(IdTy));
590 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000591 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000592 llvm::Value *False =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000593 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000594 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000595 Args.add(RValue::get(SelfAsId), IdTy);
596 Args.add(RValue::get(CmdVal), Cmd->getType());
597 Args.add(RValue::get(Offset), getContext().getPointerDiffType());
598 Args.add(RValue::get(ArgAsId), IdTy);
599 Args.add(RValue::get(IsAtomic ? True : False), getContext().BoolTy);
600 Args.add(RValue::get(IsCopy ? True : False), getContext().BoolTy);
Mike Stumpf5408fe2009-05-16 07:57:57 +0000601 // FIXME: We shouldn't need to get the function info here, the runtime
602 // already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000603 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000604 FunctionType::ExtInfo()),
605 SetPropertyFn,
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000606 ReturnValueSlot(), Args);
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000607 } else if (IsAtomic && hasAggregateLLVMType(IVART) &&
608 !IVART->isAnyComplexType() &&
Fariborz Jahanian01cb3072011-04-06 16:05:26 +0000609 IvarAssignHasTrvialAssignment(PID, IVART) &&
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000610 ((Triple.getArch() == llvm::Triple::x86 &&
611 (getContext().getTypeSizeInChars(IVART)
612 > CharUnits::fromQuantity(4))) ||
613 (Triple.getArch() == llvm::Triple::x86_64 &&
614 (getContext().getTypeSizeInChars(IVART)
615 > CharUnits::fromQuantity(8))))
David Chisnall8fac25d2010-12-26 22:13:16 +0000616 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000617 // objc_copyStruct (&structIvar, &Arg,
618 // sizeof (struct something), true, false);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000619 GenerateObjCAtomicSetterBody(OMD, Ivar);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000620 } else if (PID->getSetterCXXAssignment()) {
John McCall2a416372010-12-05 02:00:02 +0000621 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000622 } else {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000623 if (IsAtomic &&
624 IVART->isScalarType() &&
625 (Triple.getArch() == llvm::Triple::arm ||
626 Triple.getArch() == llvm::Triple::thumb) &&
627 (getContext().getTypeSizeInChars(IVART)
628 > CharUnits::fromQuantity(4)) &&
629 CGM.getObjCRuntime().GetGetStructFunction()) {
630 GenerateObjCAtomicSetterBody(OMD, Ivar);
631 }
Fariborz Jahanian1d3a61a2011-04-05 21:41:23 +0000632 else if (IsAtomic &&
633 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
634 Triple.getArch() == llvm::Triple::x86 &&
635 (getContext().getTypeSizeInChars(IVART)
636 > CharUnits::fromQuantity(4)) &&
637 CGM.getObjCRuntime().GetGetStructFunction()) {
638 GenerateObjCAtomicSetterBody(OMD, Ivar);
639 }
640 else if (IsAtomic &&
641 (IVART->isScalarType() && !IVART->isRealFloatingType()) &&
642 Triple.getArch() == llvm::Triple::x86_64 &&
643 (getContext().getTypeSizeInChars(IVART)
644 > CharUnits::fromQuantity(8)) &&
645 CGM.getObjCRuntime().GetGetStructFunction()) {
646 GenerateObjCAtomicSetterBody(OMD, Ivar);
647 }
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000648 else {
649 // FIXME: Find a clean way to avoid AST node creation.
Devang Patel8d3f8972011-05-19 23:37:41 +0000650 SourceLocation Loc = PID->getLocStart();
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000651 ValueDecl *Self = OMD->getSelfDecl();
652 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
653 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
654 ParmVarDecl *ArgDecl = *OMD->param_begin();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000655 QualType T = ArgDecl->getType();
656 if (T->isReferenceType())
657 T = cast<ReferenceType>(T)->getPointeeType();
658 DeclRefExpr Arg(ArgDecl, T, VK_LValue, Loc);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000659 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000660
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000661 // The property type can differ from the ivar type in some situations with
662 // Objective-C pointer types, we can always bit cast the RHS in these cases.
663 if (getContext().getCanonicalType(Ivar->getType()) !=
664 getContext().getCanonicalType(ArgDecl->getType())) {
665 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
666 Ivar->getType(), CK_BitCast, &Arg,
667 VK_RValue);
668 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
669 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
670 EmitStmt(&Assign);
671 } else {
672 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
673 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
674 EmitStmt(&Assign);
675 }
Daniel Dunbar45e84232009-10-27 19:21:30 +0000676 }
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000677 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000678
679 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000680}
681
John McCalle81ac692011-03-22 07:05:39 +0000682namespace {
John McCall9928c482011-07-12 16:41:08 +0000683 struct DestroyIvar : EHScopeStack::Cleanup {
684 private:
685 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +0000686 const ObjCIvarDecl *ivar;
John McCall9928c482011-07-12 16:41:08 +0000687 CodeGenFunction::Destroyer &destroyer;
688 bool useEHCleanupForArray;
689 public:
690 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
691 CodeGenFunction::Destroyer *destroyer,
692 bool useEHCleanupForArray)
693 : addr(addr), ivar(ivar), destroyer(*destroyer),
694 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +0000695
John McCallad346f42011-07-12 20:27:29 +0000696 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000697 LValue lvalue
698 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
699 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000700 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +0000701 }
702 };
703}
704
John McCall9928c482011-07-12 16:41:08 +0000705/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
706static void destroyARCStrongWithStore(CodeGenFunction &CGF,
707 llvm::Value *addr,
708 QualType type) {
709 llvm::Value *null = getNullForVariable(addr);
710 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
711}
John McCallf85e1932011-06-15 23:02:42 +0000712
John McCalle81ac692011-03-22 07:05:39 +0000713static void emitCXXDestructMethod(CodeGenFunction &CGF,
714 ObjCImplementationDecl *impl) {
715 CodeGenFunction::RunCleanupsScope scope(CGF);
716
717 llvm::Value *self = CGF.LoadObjCSelf();
718
Jordy Rosedb8264e2011-07-22 02:08:32 +0000719 const ObjCInterfaceDecl *iface = impl->getClassInterface();
720 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +0000721 ivar; ivar = ivar->getNextIvar()) {
722 QualType type = ivar->getType();
723
John McCalle81ac692011-03-22 07:05:39 +0000724 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +0000725 QualType::DestructionKind dtorKind = type.isDestructedType();
726 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +0000727
John McCall9928c482011-07-12 16:41:08 +0000728 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +0000729
John McCall9928c482011-07-12 16:41:08 +0000730 // Use a call to objc_storeStrong to destroy strong ivars, for the
731 // general benefit of the tools.
732 if (dtorKind == QualType::DK_objc_strong_lifetime) {
733 destroyer = &destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +0000734
John McCall9928c482011-07-12 16:41:08 +0000735 // Otherwise use the default for the destruction kind.
736 } else {
737 destroyer = &CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +0000738 }
John McCall9928c482011-07-12 16:41:08 +0000739
740 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
741
742 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
743 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +0000744 }
745
746 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
747}
748
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000749void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
750 ObjCMethodDecl *MD,
751 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000752 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +0000753 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +0000754
755 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000756 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +0000757 // Suppress the final autorelease in ARC.
758 AutoreleaseResult = false;
759
John McCalle81ac692011-03-22 07:05:39 +0000760 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
761 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
762 E = IMP->init_end(); B != E; ++B) {
763 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +0000764 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000765 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000766 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
767 LoadObjCSelf(), Ivar, 0);
John McCall558d2ab2010-09-15 10:14:12 +0000768 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000769 }
770 // constructor returns 'self'.
771 CodeGenTypes &Types = CGM.getTypes();
772 QualType IdTy(CGM.getContext().getObjCIdType());
773 llvm::Value *SelfAsId =
774 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
775 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +0000776
777 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000778 } else {
John McCalle81ac692011-03-22 07:05:39 +0000779 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000780 }
781 FinishFunction();
782}
783
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000784bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
785 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
786 it++; it++;
787 const ABIArgInfo &AI = it->info;
788 // FIXME. Is this sufficient check?
789 return (AI.getKind() == ABIArgInfo::Indirect);
790}
791
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000792bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
793 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
794 return false;
795 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
796 return FDTTy->getDecl()->hasObjectMember();
797 return false;
798}
799
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000800llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000801 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
802 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000803}
804
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000805QualType CodeGenFunction::TypeOfSelfObject() {
806 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
807 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000808 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
809 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000810 return PTy->getPointeeType();
811}
812
John McCalle68b9842010-12-04 03:11:00 +0000813LValue
814CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
815 // This is a special l-value that just issues sends when we load or
816 // store through it.
817
818 // For certain base kinds, we need to emit the base immediately.
819 llvm::Value *Base;
820 if (E->isSuperReceiver())
821 Base = LoadObjCSelf();
822 else if (E->isClassReceiver())
823 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
824 else
825 Base = EmitScalarExpr(E->getBase());
826 return LValue::MakePropertyRef(E, Base);
827}
828
829static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
830 ReturnValueSlot Return,
831 QualType ResultType,
832 Selector S,
833 llvm::Value *Receiver,
834 const CallArgList &CallArgs) {
835 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000836 bool isClassMessage = OMD->isClassMethod();
837 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000838 return CGF.CGM.getObjCRuntime()
839 .GenerateMessageSendSuper(CGF, Return, ResultType,
840 S, OMD->getClassInterface(),
841 isCategoryImpl, Receiver,
842 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000843}
844
John McCall119a1c62010-12-04 02:32:38 +0000845RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
846 ReturnValueSlot Return) {
847 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000848 QualType ResultType = E->getGetterResultType();
John McCall12f78a62010-12-02 01:19:52 +0000849 Selector S;
Douglas Gregor926df6c2011-06-11 01:09:30 +0000850 const ObjCMethodDecl *method;
John McCall12f78a62010-12-02 01:19:52 +0000851 if (E->isExplicitProperty()) {
852 const ObjCPropertyDecl *Property = E->getExplicitProperty();
853 S = Property->getGetterName();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000854 method = Property->getGetterMethodDecl();
Mike Stumpb3589f42009-07-30 22:28:39 +0000855 } else {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000856 method = E->getImplicitPropertyGetter();
857 S = method->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000858 }
John McCall12f78a62010-12-02 01:19:52 +0000859
John McCall119a1c62010-12-04 02:32:38 +0000860 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000861
John McCallf85e1932011-06-15 23:02:42 +0000862 if (CGM.getLangOptions().ObjCAutoRefCount) {
863 QualType receiverType;
864 if (E->isSuperReceiver())
865 receiverType = E->getSuperReceiverType();
866 else if (E->isClassReceiver())
867 receiverType = getContext().getObjCClassType();
868 else
869 receiverType = E->getBase()->getType();
870 }
871
John McCalle68b9842010-12-04 03:11:00 +0000872 // Accesses to 'super' follow a different code path.
873 if (E->isSuperReceiver())
Douglas Gregor926df6c2011-06-11 01:09:30 +0000874 return AdjustRelatedResultType(*this, E, method,
875 GenerateMessageSendSuper(*this, Return,
876 ResultType,
877 S, Receiver,
878 CallArgList()));
John McCall119a1c62010-12-04 02:32:38 +0000879 const ObjCInterfaceDecl *ReceiverClass
880 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000881 return AdjustRelatedResultType(*this, E, method,
John McCallf85e1932011-06-15 23:02:42 +0000882 CGM.getObjCRuntime().
883 GenerateMessageSend(*this, Return, ResultType, S,
884 Receiver, CallArgList(), ReceiverClass));
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000885}
886
John McCall119a1c62010-12-04 02:32:38 +0000887void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
888 LValue Dst) {
889 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000890 Selector S = E->getSetterSelector();
Fariborz Jahanian68af13f2011-03-30 16:11:20 +0000891 QualType ArgType = E->getSetterArgType();
892
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000893 // FIXME. Other than scalars, AST is not adequate for setter and
894 // getter type mismatches which require conversion.
895 if (Src.isScalar()) {
896 llvm::Value *SrcVal = Src.getScalarVal();
897 QualType DstType = getContext().getCanonicalType(ArgType);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000898 llvm::Type *DstTy = ConvertType(DstType);
Fariborz Jahanianb19c76e2011-02-08 22:33:23 +0000899 if (SrcVal->getType() != DstTy)
900 Src =
901 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
902 }
903
John McCalle68b9842010-12-04 03:11:00 +0000904 CallArgList Args;
Eli Friedman04c9a492011-05-02 17:57:46 +0000905 Args.add(Src, ArgType);
John McCalle68b9842010-12-04 03:11:00 +0000906
907 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
908 QualType ResultType = getContext().VoidTy;
909
John McCall12f78a62010-12-02 01:19:52 +0000910 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +0000911 GenerateMessageSendSuper(*this, ReturnValueSlot(),
912 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +0000913 return;
914 }
915
John McCall119a1c62010-12-04 02:32:38 +0000916 const ObjCInterfaceDecl *ReceiverClass
917 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000918
John McCall12f78a62010-12-02 01:19:52 +0000919 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +0000920 ResultType, S, Receiver, Args,
921 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000922}
923
Chris Lattner74391b42009-03-22 21:03:39 +0000924void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +0000925 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000926 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000928 if (!EnumerationMutationFn) {
929 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
930 return;
931 }
932
Devang Patelbcbd03a2011-01-19 01:36:36 +0000933 CGDebugInfo *DI = getDebugInfo();
934 if (DI) {
935 DI->setLocation(S.getSourceRange().getBegin());
936 DI->EmitRegionStart(Builder);
937 }
938
Devang Patel9d99f2d2011-06-13 23:15:32 +0000939 // The local variable comes into scope immediately.
940 AutoVarEmission variable = AutoVarEmission::invalid();
941 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
942 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
943
John McCalld88687f2011-01-07 01:49:06 +0000944 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
945 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump1eb44332009-09-09 15:08:12 +0000946
Anders Carlssonf484c312008-08-31 02:33:12 +0000947 // Fast enumeration state.
948 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +0000949 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +0000950 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Anders Carlssonf484c312008-08-31 02:33:12 +0000952 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000953 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +0000954
John McCalld88687f2011-01-07 01:49:06 +0000955 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +0000956 IdentifierInfo *II[] = {
957 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
958 &CGM.getContext().Idents.get("objects"),
959 &CGM.getContext().Idents.get("count")
960 };
961 Selector FastEnumSel =
962 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +0000963
964 QualType ItemsTy =
965 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000966 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +0000967 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +0000968 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000969
John McCalld88687f2011-01-07 01:49:06 +0000970 // Emit the collection pointer.
Anders Carlssonf484c312008-08-31 02:33:12 +0000971 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump1eb44332009-09-09 15:08:12 +0000972
John McCalld88687f2011-01-07 01:49:06 +0000973 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +0000974 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +0000975
976 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +0000977 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000978
John McCalld88687f2011-01-07 01:49:06 +0000979 // The second argument is a temporary array with space for NumItems
980 // pointers. We'll actually be loading elements from the array
981 // pointer written into the control state; this buffer is so that
982 // collections that *aren't* backed by arrays can still queue up
983 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +0000984 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000985
John McCalld88687f2011-01-07 01:49:06 +0000986 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000987 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000988 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +0000989 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
John McCalld88687f2011-01-07 01:49:06 +0000991 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +0000992 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000993 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000994 getContext().UnsignedLongTy,
995 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000996 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +0000997
John McCalld88687f2011-01-07 01:49:06 +0000998 // The initial number of objects that were returned in the buffer.
999 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001000
John McCalld88687f2011-01-07 01:49:06 +00001001 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1002 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001003
John McCalld88687f2011-01-07 01:49:06 +00001004 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001005
John McCalld88687f2011-01-07 01:49:06 +00001006 // If the limit pointer was zero to begin with, the collection is
1007 // empty; skip all this.
1008 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1009 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001010
John McCalld88687f2011-01-07 01:49:06 +00001011 // Otherwise, initialize the loop.
1012 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001013
John McCalld88687f2011-01-07 01:49:06 +00001014 // Save the initial mutations value. This is the value at an
1015 // address that was written into the state object by
1016 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001017 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001018 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001019 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001020 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001021
John McCalld88687f2011-01-07 01:49:06 +00001022 llvm::Value *initialMutations =
1023 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001024
John McCalld88687f2011-01-07 01:49:06 +00001025 // Start looping. This is the point we return to whenever we have a
1026 // fresh, non-empty batch of objects.
1027 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1028 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001029
John McCalld88687f2011-01-07 01:49:06 +00001030 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001031 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001032 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001033
John McCalld88687f2011-01-07 01:49:06 +00001034 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001035 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001036 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001037
John McCalld88687f2011-01-07 01:49:06 +00001038 // Check whether the mutations value has changed from where it was
1039 // at start. StateMutationsPtr should actually be invariant between
1040 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001041 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001042 llvm::Value *currentMutations
1043 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001044
John McCalld88687f2011-01-07 01:49:06 +00001045 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001046 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001047
John McCalld88687f2011-01-07 01:49:06 +00001048 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1049 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001050
John McCalld88687f2011-01-07 01:49:06 +00001051 // If so, call the enumeration-mutation function.
1052 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001053 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001054 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001055 ConvertType(getContext().getObjCIdType()),
1056 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001057 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001058 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001059 // FIXME: We shouldn't need to get the function info here, the runtime already
1060 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +00001061 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +00001062 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001063 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001064
John McCalld88687f2011-01-07 01:49:06 +00001065 // Otherwise, or if the mutation function returns, just continue.
1066 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001067
John McCalld88687f2011-01-07 01:49:06 +00001068 // Initialize the element variable.
1069 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001070 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001071 LValue elementLValue;
1072 QualType elementType;
1073 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001074 // Initialize the variable, in case it's a __block variable or something.
1075 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001076
John McCall57b3b6a2011-02-22 07:16:58 +00001077 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCalld88687f2011-01-07 01:49:06 +00001078 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
1079 VK_LValue, SourceLocation());
1080 elementLValue = EmitLValue(&tempDRE);
1081 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001082 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001083
1084 if (D->isARCPseudoStrong())
1085 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001086 } else {
1087 elementLValue = LValue(); // suppress warning
1088 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001089 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001090 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001091 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001092
1093 // Fetch the buffer out of the enumeration state.
1094 // TODO: this pointer should actually be invariant between
1095 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001096 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001097 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001098 llvm::Value *EnumStateItems =
1099 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001100
John McCalld88687f2011-01-07 01:49:06 +00001101 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001102 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001103 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1104 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001105
John McCalld88687f2011-01-07 01:49:06 +00001106 // Cast that value to the right type.
1107 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1108 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001109
John McCalld88687f2011-01-07 01:49:06 +00001110 // Make sure we have an l-value. Yes, this gets evaluated every
1111 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001112 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001113 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001114 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001115 } else {
1116 EmitScalarInit(CurrentItem, elementLValue);
1117 }
Mike Stump1eb44332009-09-09 15:08:12 +00001118
John McCall57b3b6a2011-02-22 07:16:58 +00001119 // If we do have an element variable, this assignment is the end of
1120 // its initialization.
1121 if (elementIsVariable)
1122 EmitAutoVarCleanups(variable);
1123
John McCalld88687f2011-01-07 01:49:06 +00001124 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001125 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001126 {
1127 RunCleanupsScope Scope(*this);
1128 EmitStmt(S.getBody());
1129 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001130 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001131
John McCalld88687f2011-01-07 01:49:06 +00001132 // Destroy the element variable now.
1133 elementVariableScope.ForceCleanup();
1134
1135 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001136 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001137
John McCalld88687f2011-01-07 01:49:06 +00001138 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001139
John McCalld88687f2011-01-07 01:49:06 +00001140 // First we check in the local buffer.
1141 llvm::Value *indexPlusOne
1142 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001143
John McCalld88687f2011-01-07 01:49:06 +00001144 // If we haven't overrun the buffer yet, we can continue.
1145 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1146 LoopBodyBB, FetchMoreBB);
1147
1148 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1149 count->addIncoming(count, AfterBody.getBlock());
1150
1151 // Otherwise, we have to fetch more elements.
1152 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
1154 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001155 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001156 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001157 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001158 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001159
John McCalld88687f2011-01-07 01:49:06 +00001160 // If we got a zero count, we're done.
1161 llvm::Value *refetchCount = CountRV.getScalarVal();
1162
1163 // (note that the message send might split FetchMoreBB)
1164 index->addIncoming(zero, Builder.GetInsertBlock());
1165 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1166
1167 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1168 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001169
Anders Carlssonf484c312008-08-31 02:33:12 +00001170 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001171 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001172
John McCall57b3b6a2011-02-22 07:16:58 +00001173 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001174 // If the element was not a declaration, set it to be null.
1175
John McCalld88687f2011-01-07 01:49:06 +00001176 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1177 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001178 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001179 }
1180
Devang Patelbcbd03a2011-01-19 01:36:36 +00001181 if (DI) {
1182 DI->setLocation(S.getSourceRange().getEnd());
1183 DI->EmitRegionEnd(Builder);
1184 }
1185
John McCallff8e1152010-07-23 21:56:41 +00001186 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001187}
1188
Mike Stump1eb44332009-09-09 15:08:12 +00001189void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001190 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001191}
1192
Mike Stump1eb44332009-09-09 15:08:12 +00001193void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001194 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1195}
1196
Chris Lattner10cac6f2008-11-15 21:26:17 +00001197void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001198 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001199 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001200}
1201
John McCallf85e1932011-06-15 23:02:42 +00001202/// Produce the code for a CK_ObjCProduceObject. Just does a
1203/// primitive retain.
1204llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1205 llvm::Value *value) {
1206 return EmitARCRetain(type, value);
1207}
1208
1209namespace {
1210 struct CallObjCRelease : EHScopeStack::Cleanup {
1211 CallObjCRelease(QualType type, llvm::Value *ptr, llvm::Value *condition)
1212 : type(type), ptr(ptr), condition(condition) {}
1213 QualType type;
1214 llvm::Value *ptr;
1215 llvm::Value *condition;
1216
John McCallad346f42011-07-12 20:27:29 +00001217 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001218 llvm::Value *object;
1219
1220 // If we're in a conditional branch, we had to stash away in an
1221 // alloca the pointer to be released.
1222 llvm::BasicBlock *cont = 0;
1223 if (condition) {
1224 llvm::BasicBlock *release = CGF.createBasicBlock("release.yes");
1225 cont = CGF.createBasicBlock("release.cont");
1226
1227 llvm::Value *cond = CGF.Builder.CreateLoad(condition);
1228 CGF.Builder.CreateCondBr(cond, release, cont);
1229 CGF.EmitBlock(release);
1230 object = CGF.Builder.CreateLoad(ptr);
1231 } else {
1232 object = ptr;
1233 }
1234
1235 CGF.EmitARCRelease(object, /*precise*/ true);
1236
1237 if (cont) CGF.EmitBlock(cont);
1238 }
1239 };
1240}
1241
1242/// Produce the code for a CK_ObjCConsumeObject. Does a primitive
1243/// release at the end of the full-expression.
1244llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1245 llvm::Value *object) {
1246 // If we're in a conditional branch, we need to make the cleanup
1247 // conditional. FIXME: this really needs to be supported by the
1248 // environment.
1249 llvm::AllocaInst *cond;
1250 llvm::Value *ptr;
1251 if (isInConditionalBranch()) {
1252 cond = CreateTempAlloca(Builder.getInt1Ty(), "release.cond");
1253 ptr = CreateTempAlloca(object->getType(), "release.value");
1254
1255 // The alloca is false until we get here.
1256 // FIXME: er. doesn't this need to be set at the start of the condition?
1257 InitTempAlloca(cond, Builder.getFalse());
1258
1259 // Then it turns true.
1260 Builder.CreateStore(Builder.getTrue(), cond);
1261 Builder.CreateStore(object, ptr);
1262 } else {
1263 cond = 0;
1264 ptr = object;
1265 }
1266
1267 EHStack.pushCleanup<CallObjCRelease>(getARCCleanupKind(), type, ptr, cond);
1268 return object;
1269}
1270
1271llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1272 llvm::Value *value) {
1273 return EmitARCRetainAutorelease(type, value);
1274}
1275
1276
1277static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001278 llvm::FunctionType *type,
John McCallf85e1932011-06-15 23:02:42 +00001279 llvm::StringRef fnName) {
1280 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1281
1282 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1283 // support library.
John McCall9f084a32011-07-06 00:26:06 +00001284 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCallf85e1932011-06-15 23:02:42 +00001285 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1286 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1287
1288 return fn;
1289}
1290
1291/// Perform an operation having the signature
1292/// i8* (i8*)
1293/// where a null input causes a no-op and returns null.
1294static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1295 llvm::Value *value,
1296 llvm::Constant *&fn,
1297 llvm::StringRef fnName) {
1298 if (isa<llvm::ConstantPointerNull>(value)) return value;
1299
1300 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001301 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001302 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001303 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1304 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1305 }
1306
1307 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001308 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001309 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1310
1311 // Call the function.
1312 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1313 call->setDoesNotThrow();
1314
1315 // Cast the result back to the original type.
1316 return CGF.Builder.CreateBitCast(call, origType);
1317}
1318
1319/// Perform an operation having the following signature:
1320/// i8* (i8**)
1321static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1322 llvm::Value *addr,
1323 llvm::Constant *&fn,
1324 llvm::StringRef fnName) {
1325 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001326 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001327 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001328 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1329 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1330 }
1331
1332 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001333 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001334 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1335
1336 // Call the function.
1337 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1338 call->setDoesNotThrow();
1339
1340 // Cast the result back to a dereference of the original type.
1341 llvm::Value *result = call;
1342 if (origType != CGF.Int8PtrPtrTy)
1343 result = CGF.Builder.CreateBitCast(result,
1344 cast<llvm::PointerType>(origType)->getElementType());
1345
1346 return result;
1347}
1348
1349/// Perform an operation having the following signature:
1350/// i8* (i8**, i8*)
1351static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1352 llvm::Value *addr,
1353 llvm::Value *value,
1354 llvm::Constant *&fn,
1355 llvm::StringRef fnName,
1356 bool ignored) {
1357 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1358 == value->getType());
1359
1360 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001361 std::vector<llvm::Type*> argTypes(2);
John McCallf85e1932011-06-15 23:02:42 +00001362 argTypes[0] = CGF.Int8PtrPtrTy;
1363 argTypes[1] = CGF.Int8PtrTy;
1364
Chris Lattner2acc6e32011-07-18 04:24:23 +00001365 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001366 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1367 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1368 }
1369
Chris Lattner2acc6e32011-07-18 04:24:23 +00001370 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001371
1372 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1373 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1374
1375 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1376 result->setDoesNotThrow();
1377
1378 if (ignored) return 0;
1379
1380 return CGF.Builder.CreateBitCast(result, origType);
1381}
1382
1383/// Perform an operation having the following signature:
1384/// void (i8**, i8**)
1385static void emitARCCopyOperation(CodeGenFunction &CGF,
1386 llvm::Value *dst,
1387 llvm::Value *src,
1388 llvm::Constant *&fn,
1389 llvm::StringRef fnName) {
1390 assert(dst->getType() == src->getType());
1391
1392 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001393 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001394 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001395 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1396 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1397 }
1398
1399 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1400 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1401
1402 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1403 result->setDoesNotThrow();
1404}
1405
1406/// Produce the code to do a retain. Based on the type, calls one of:
1407/// call i8* @objc_retain(i8* %value)
1408/// call i8* @objc_retainBlock(i8* %value)
1409llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1410 if (type->isBlockPointerType())
1411 return EmitARCRetainBlock(value);
1412 else
1413 return EmitARCRetainNonBlock(value);
1414}
1415
1416/// Retain the given object, with normal retain semantics.
1417/// call i8* @objc_retain(i8* %value)
1418llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1419 return emitARCValueOperation(*this, value,
1420 CGM.getARCEntrypoints().objc_retain,
1421 "objc_retain");
1422}
1423
1424/// Retain the given block, with _Block_copy semantics.
1425/// call i8* @objc_retainBlock(i8* %value)
1426llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1427 return emitARCValueOperation(*this, value,
1428 CGM.getARCEntrypoints().objc_retainBlock,
1429 "objc_retainBlock");
1430}
1431
1432/// Retain the given object which is the result of a function call.
1433/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1434///
1435/// Yes, this function name is one character away from a different
1436/// call with completely different semantics.
1437llvm::Value *
1438CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1439 // Fetch the void(void) inline asm which marks that we're going to
1440 // retain the autoreleased return value.
1441 llvm::InlineAsm *&marker
1442 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1443 if (!marker) {
1444 llvm::StringRef assembly
1445 = CGM.getTargetCodeGenInfo()
1446 .getARCRetainAutoreleasedReturnValueMarker();
1447
1448 // If we have an empty assembly string, there's nothing to do.
1449 if (assembly.empty()) {
1450
1451 // Otherwise, at -O0, build an inline asm that we're going to call
1452 // in a moment.
1453 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1454 llvm::FunctionType *type =
1455 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1456 /*variadic*/ false);
1457
1458 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1459
1460 // If we're at -O1 and above, we don't want to litter the code
1461 // with this marker yet, so leave a breadcrumb for the ARC
1462 // optimizer to pick up.
1463 } else {
1464 llvm::NamedMDNode *metadata =
1465 CGM.getModule().getOrInsertNamedMetadata(
1466 "clang.arc.retainAutoreleasedReturnValueMarker");
1467 assert(metadata->getNumOperands() <= 1);
1468 if (metadata->getNumOperands() == 0) {
1469 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1470 llvm::Value *args[] = { string };
1471 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), args));
1472 }
1473 }
1474 }
1475
1476 // Call the marker asm if we made one, which we do only at -O0.
1477 if (marker) Builder.CreateCall(marker);
1478
1479 return emitARCValueOperation(*this, value,
1480 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1481 "objc_retainAutoreleasedReturnValue");
1482}
1483
1484/// Release the given object.
1485/// call void @objc_release(i8* %value)
1486void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1487 if (isa<llvm::ConstantPointerNull>(value)) return;
1488
1489 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1490 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001491 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001492 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001493 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1494 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1495 }
1496
1497 // Cast the argument to 'id'.
1498 value = Builder.CreateBitCast(value, Int8PtrTy);
1499
1500 // Call objc_release.
1501 llvm::CallInst *call = Builder.CreateCall(fn, value);
1502 call->setDoesNotThrow();
1503
1504 if (!precise) {
1505 llvm::SmallVector<llvm::Value*,1> args;
1506 call->setMetadata("clang.imprecise_release",
1507 llvm::MDNode::get(Builder.getContext(), args));
1508 }
1509}
1510
1511/// Store into a strong object. Always calls this:
1512/// call void @objc_storeStrong(i8** %addr, i8* %value)
1513llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1514 llvm::Value *value,
1515 bool ignored) {
1516 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1517 == value->getType());
1518
1519 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1520 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001521 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001522 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001523 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1524 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1525 }
1526
1527 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1528 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1529
1530 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1531
1532 if (ignored) return 0;
1533 return value;
1534}
1535
1536/// Store into a strong object. Sometimes calls this:
1537/// call void @objc_storeStrong(i8** %addr, i8* %value)
1538/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00001539llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00001540 llvm::Value *newValue,
1541 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00001542 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00001543 bool isBlock = type->isBlockPointerType();
1544
1545 // Use a store barrier at -O0 unless this is a block type or the
1546 // lvalue is inadequately aligned.
1547 if (shouldUseFusedARCCalls() &&
1548 !isBlock &&
1549 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1550 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1551 }
1552
1553 // Otherwise, split it out.
1554
1555 // Retain the new value.
1556 newValue = EmitARCRetain(type, newValue);
1557
1558 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00001559 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00001560
1561 // Store. We do this before the release so that any deallocs won't
1562 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00001563 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00001564
1565 // Finally, release the old value.
1566 EmitARCRelease(oldValue, /*precise*/ false);
1567
1568 return newValue;
1569}
1570
1571/// Autorelease the given object.
1572/// call i8* @objc_autorelease(i8* %value)
1573llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1574 return emitARCValueOperation(*this, value,
1575 CGM.getARCEntrypoints().objc_autorelease,
1576 "objc_autorelease");
1577}
1578
1579/// Autorelease the given object.
1580/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1581llvm::Value *
1582CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1583 return emitARCValueOperation(*this, value,
1584 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1585 "objc_autoreleaseReturnValue");
1586}
1587
1588/// Do a fused retain/autorelease of the given object.
1589/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1590llvm::Value *
1591CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1592 return emitARCValueOperation(*this, value,
1593 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1594 "objc_retainAutoreleaseReturnValue");
1595}
1596
1597/// Do a fused retain/autorelease of the given object.
1598/// call i8* @objc_retainAutorelease(i8* %value)
1599/// or
1600/// %retain = call i8* @objc_retainBlock(i8* %value)
1601/// call i8* @objc_autorelease(i8* %retain)
1602llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1603 llvm::Value *value) {
1604 if (!type->isBlockPointerType())
1605 return EmitARCRetainAutoreleaseNonBlock(value);
1606
1607 if (isa<llvm::ConstantPointerNull>(value)) return value;
1608
Chris Lattner2acc6e32011-07-18 04:24:23 +00001609 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001610 value = Builder.CreateBitCast(value, Int8PtrTy);
1611 value = EmitARCRetainBlock(value);
1612 value = EmitARCAutorelease(value);
1613 return Builder.CreateBitCast(value, origType);
1614}
1615
1616/// Do a fused retain/autorelease of the given object.
1617/// call i8* @objc_retainAutorelease(i8* %value)
1618llvm::Value *
1619CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1620 return emitARCValueOperation(*this, value,
1621 CGM.getARCEntrypoints().objc_retainAutorelease,
1622 "objc_retainAutorelease");
1623}
1624
1625/// i8* @objc_loadWeak(i8** %addr)
1626/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1627llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1628 return emitARCLoadOperation(*this, addr,
1629 CGM.getARCEntrypoints().objc_loadWeak,
1630 "objc_loadWeak");
1631}
1632
1633/// i8* @objc_loadWeakRetained(i8** %addr)
1634llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1635 return emitARCLoadOperation(*this, addr,
1636 CGM.getARCEntrypoints().objc_loadWeakRetained,
1637 "objc_loadWeakRetained");
1638}
1639
1640/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1641/// Returns %value.
1642llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1643 llvm::Value *value,
1644 bool ignored) {
1645 return emitARCStoreOperation(*this, addr, value,
1646 CGM.getARCEntrypoints().objc_storeWeak,
1647 "objc_storeWeak", ignored);
1648}
1649
1650/// i8* @objc_initWeak(i8** %addr, i8* %value)
1651/// Returns %value. %addr is known to not have a current weak entry.
1652/// Essentially equivalent to:
1653/// *addr = nil; objc_storeWeak(addr, value);
1654void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1655 // If we're initializing to null, just write null to memory; no need
1656 // to get the runtime involved. But don't do this if optimization
1657 // is enabled, because accounting for this would make the optimizer
1658 // much more complicated.
1659 if (isa<llvm::ConstantPointerNull>(value) &&
1660 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1661 Builder.CreateStore(value, addr);
1662 return;
1663 }
1664
1665 emitARCStoreOperation(*this, addr, value,
1666 CGM.getARCEntrypoints().objc_initWeak,
1667 "objc_initWeak", /*ignored*/ true);
1668}
1669
1670/// void @objc_destroyWeak(i8** %addr)
1671/// Essentially objc_storeWeak(addr, nil).
1672void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1673 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1674 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001675 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001676 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001677 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1678 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1679 }
1680
1681 // Cast the argument to 'id*'.
1682 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1683
1684 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1685 call->setDoesNotThrow();
1686}
1687
1688/// void @objc_moveWeak(i8** %dest, i8** %src)
1689/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1690/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1691void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1692 emitARCCopyOperation(*this, dst, src,
1693 CGM.getARCEntrypoints().objc_moveWeak,
1694 "objc_moveWeak");
1695}
1696
1697/// void @objc_copyWeak(i8** %dest, i8** %src)
1698/// Disregards the current value in %dest. Essentially
1699/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1700void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1701 emitARCCopyOperation(*this, dst, src,
1702 CGM.getARCEntrypoints().objc_copyWeak,
1703 "objc_copyWeak");
1704}
1705
1706/// Produce the code to do a objc_autoreleasepool_push.
1707/// call i8* @objc_autoreleasePoolPush(void)
1708llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1709 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1710 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001711 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001712 llvm::FunctionType::get(Int8PtrTy, false);
1713 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1714 }
1715
1716 llvm::CallInst *call = Builder.CreateCall(fn);
1717 call->setDoesNotThrow();
1718
1719 return call;
1720}
1721
1722/// Produce the code to do a primitive release.
1723/// call void @objc_autoreleasePoolPop(i8* %ptr)
1724void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1725 assert(value->getType() == Int8PtrTy);
1726
1727 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1728 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001729 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001730 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00001731 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1732
1733 // We don't want to use a weak import here; instead we should not
1734 // fall into this path.
1735 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1736 }
1737
1738 llvm::CallInst *call = Builder.CreateCall(fn, value);
1739 call->setDoesNotThrow();
1740}
1741
1742/// Produce the code to do an MRR version objc_autoreleasepool_push.
1743/// Which is: [[NSAutoreleasePool alloc] init];
1744/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1745/// init is declared as: - (id) init; in its NSObject super class.
1746///
1747llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1748 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1749 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1750 // [NSAutoreleasePool alloc]
1751 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1752 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1753 CallArgList Args;
1754 RValue AllocRV =
1755 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1756 getContext().getObjCIdType(),
1757 AllocSel, Receiver, Args);
1758
1759 // [Receiver init]
1760 Receiver = AllocRV.getScalarVal();
1761 II = &CGM.getContext().Idents.get("init");
1762 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1763 RValue InitRV =
1764 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1765 getContext().getObjCIdType(),
1766 InitSel, Receiver, Args);
1767 return InitRV.getScalarVal();
1768}
1769
1770/// Produce the code to do a primitive release.
1771/// [tmp drain];
1772void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1773 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1774 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1775 CallArgList Args;
1776 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1777 getContext().VoidTy, DrainSel, Arg, Args);
1778}
1779
John McCallbdc4d802011-07-09 01:37:26 +00001780void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
1781 llvm::Value *addr,
1782 QualType type) {
1783 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1784 CGF.EmitARCRelease(ptr, /*precise*/ true);
1785}
1786
1787void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
1788 llvm::Value *addr,
1789 QualType type) {
1790 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
1791 CGF.EmitARCRelease(ptr, /*precise*/ false);
1792}
1793
1794void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
1795 llvm::Value *addr,
1796 QualType type) {
1797 CGF.EmitARCDestroyWeak(addr);
1798}
1799
John McCallf85e1932011-06-15 23:02:42 +00001800namespace {
John McCallf85e1932011-06-15 23:02:42 +00001801 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
1802 llvm::Value *Token;
1803
1804 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1805
John McCallad346f42011-07-12 20:27:29 +00001806 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001807 CGF.EmitObjCAutoreleasePoolPop(Token);
1808 }
1809 };
1810 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
1811 llvm::Value *Token;
1812
1813 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
1814
John McCallad346f42011-07-12 20:27:29 +00001815 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001816 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
1817 }
1818 };
1819}
1820
1821void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
1822 if (CGM.getLangOptions().ObjCAutoRefCount)
1823 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
1824 else
1825 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
1826}
1827
John McCallf85e1932011-06-15 23:02:42 +00001828static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1829 LValue lvalue,
1830 QualType type) {
1831 switch (type.getObjCLifetime()) {
1832 case Qualifiers::OCL_None:
1833 case Qualifiers::OCL_ExplicitNone:
1834 case Qualifiers::OCL_Strong:
1835 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00001836 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00001837 false);
1838
1839 case Qualifiers::OCL_Weak:
1840 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
1841 true);
1842 }
1843
1844 llvm_unreachable("impossible lifetime!");
1845 return TryEmitResult();
1846}
1847
1848static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
1849 const Expr *e) {
1850 e = e->IgnoreParens();
1851 QualType type = e->getType();
1852
1853 // As a very special optimization, in ARC++, if the l-value is the
1854 // result of a non-volatile assignment, do a simple retain of the
1855 // result of the call to objc_storeWeak instead of reloading.
1856 if (CGF.getLangOptions().CPlusPlus &&
1857 !type.isVolatileQualified() &&
1858 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
1859 isa<BinaryOperator>(e) &&
1860 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
1861 return TryEmitResult(CGF.EmitScalarExpr(e), false);
1862
1863 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
1864}
1865
1866static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1867 llvm::Value *value);
1868
1869/// Given that the given expression is some sort of call (which does
1870/// not return retained), emit a retain following it.
1871static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
1872 llvm::Value *value = CGF.EmitScalarExpr(e);
1873 return emitARCRetainAfterCall(CGF, value);
1874}
1875
1876static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
1877 llvm::Value *value) {
1878 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
1879 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1880
1881 // Place the retain immediately following the call.
1882 CGF.Builder.SetInsertPoint(call->getParent(),
1883 ++llvm::BasicBlock::iterator(call));
1884 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1885
1886 CGF.Builder.restoreIP(ip);
1887 return value;
1888 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
1889 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
1890
1891 // Place the retain at the beginning of the normal destination block.
1892 llvm::BasicBlock *BB = invoke->getNormalDest();
1893 CGF.Builder.SetInsertPoint(BB, BB->begin());
1894 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1895
1896 CGF.Builder.restoreIP(ip);
1897 return value;
1898
1899 // Bitcasts can arise because of related-result returns. Rewrite
1900 // the operand.
1901 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
1902 llvm::Value *operand = bitcast->getOperand(0);
1903 operand = emitARCRetainAfterCall(CGF, operand);
1904 bitcast->setOperand(0, operand);
1905 return bitcast;
1906
1907 // Generic fall-back case.
1908 } else {
1909 // Retain using the non-block variant: we never need to do a copy
1910 // of a block that's been returned to us.
1911 return CGF.EmitARCRetainNonBlock(value);
1912 }
1913}
1914
1915static TryEmitResult
1916tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001917 // The desired result type, if it differs from the type of the
1918 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001919 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00001920
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001921 // If we're loading retained from a __strong xvalue, we can avoid
1922 // an extra retain/release pair by zeroing out the source of this
1923 // "move" operation.
John McCalldf7b0912011-06-25 02:26:44 +00001924 if (e->isXValue() && !e->getType().isConstQualified() &&
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001925 e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
1926 // Emit the lvalue
1927 LValue lv = CGF.EmitLValue(e);
1928
1929 // Load the object pointer and cast it to the appropriate type.
1930 QualType exprType = e->getType();
John McCall545d9962011-06-25 02:11:03 +00001931 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001932
1933 if (resultType)
1934 result = CGF.Builder.CreateBitCast(result, resultType);
1935
1936 // Set the source pointer to NULL.
1937 llvm::Value *null
1938 = llvm::ConstantPointerNull::get(
1939 cast<llvm::PointerType>(CGF.ConvertType(exprType)));
John McCall545d9962011-06-25 02:11:03 +00001940 CGF.EmitStoreOfScalar(null, lv);
Douglas Gregord1bd98a2011-06-22 16:32:26 +00001941
1942 return TryEmitResult(result, true);
1943 }
1944
John McCallf85e1932011-06-15 23:02:42 +00001945 while (true) {
1946 e = e->IgnoreParens();
1947
1948 // There's a break at the end of this if-chain; anything
1949 // that wants to keep looping has to explicitly continue.
1950 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
1951 switch (ce->getCastKind()) {
1952 // No-op casts don't change the type, so we just ignore them.
1953 case CK_NoOp:
1954 e = ce->getSubExpr();
1955 continue;
1956
1957 case CK_LValueToRValue: {
1958 TryEmitResult loadResult
1959 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
1960 if (resultType) {
1961 llvm::Value *value = loadResult.getPointer();
1962 value = CGF.Builder.CreateBitCast(value, resultType);
1963 loadResult.setPointer(value);
1964 }
1965 return loadResult;
1966 }
1967
1968 // These casts can change the type, so remember that and
1969 // soldier on. We only need to remember the outermost such
1970 // cast, though.
1971 case CK_AnyPointerToObjCPointerCast:
1972 case CK_AnyPointerToBlockPointerCast:
1973 case CK_BitCast:
1974 if (!resultType)
1975 resultType = CGF.ConvertType(ce->getType());
1976 e = ce->getSubExpr();
1977 assert(e->getType()->hasPointerRepresentation());
1978 continue;
1979
1980 // For consumptions, just emit the subexpression and thus elide
1981 // the retain/release pair.
1982 case CK_ObjCConsumeObject: {
1983 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
1984 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1985 return TryEmitResult(result, true);
1986 }
1987
John McCall7e5e5f42011-07-07 06:58:02 +00001988 // For reclaims, emit the subexpression as a retained call and
1989 // skip the consumption.
1990 case CK_ObjCReclaimReturnedObject: {
1991 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
1992 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1993 return TryEmitResult(result, true);
1994 }
1995
John McCallf85e1932011-06-15 23:02:42 +00001996 case CK_GetObjCProperty: {
1997 llvm::Value *result = emitARCRetainCall(CGF, ce);
1998 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
1999 return TryEmitResult(result, true);
2000 }
2001
2002 default:
2003 break;
2004 }
2005
2006 // Skip __extension__.
2007 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2008 if (op->getOpcode() == UO_Extension) {
2009 e = op->getSubExpr();
2010 continue;
2011 }
2012
2013 // For calls and message sends, use the retained-call logic.
2014 // Delegate inits are a special case in that they're the only
2015 // returns-retained expression that *isn't* surrounded by
2016 // a consume.
2017 } else if (isa<CallExpr>(e) ||
2018 (isa<ObjCMessageExpr>(e) &&
2019 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2020 llvm::Value *result = emitARCRetainCall(CGF, e);
2021 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2022 return TryEmitResult(result, true);
2023 }
2024
2025 // Conservatively halt the search at any other expression kind.
2026 break;
2027 }
2028
2029 // We didn't find an obvious production, so emit what we've got and
2030 // tell the caller that we didn't manage to retain.
2031 llvm::Value *result = CGF.EmitScalarExpr(e);
2032 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2033 return TryEmitResult(result, false);
2034}
2035
2036static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2037 LValue lvalue,
2038 QualType type) {
2039 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2040 llvm::Value *value = result.getPointer();
2041 if (!result.getInt())
2042 value = CGF.EmitARCRetain(type, value);
2043 return value;
2044}
2045
2046/// EmitARCRetainScalarExpr - Semantically equivalent to
2047/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2048/// best-effort attempt to peephole expressions that naturally produce
2049/// retained objects.
2050llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2051 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2052 llvm::Value *value = result.getPointer();
2053 if (!result.getInt())
2054 value = EmitARCRetain(e->getType(), value);
2055 return value;
2056}
2057
2058llvm::Value *
2059CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2060 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2061 llvm::Value *value = result.getPointer();
2062 if (result.getInt())
2063 value = EmitARCAutorelease(value);
2064 else
2065 value = EmitARCRetainAutorelease(e->getType(), value);
2066 return value;
2067}
2068
2069std::pair<LValue,llvm::Value*>
2070CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2071 bool ignored) {
2072 // Evaluate the RHS first.
2073 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2074 llvm::Value *value = result.getPointer();
2075
2076 LValue lvalue = EmitLValue(e->getLHS());
2077
2078 // If the RHS was emitted retained, expand this.
2079 if (result.getInt()) {
2080 llvm::Value *oldValue =
2081 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2082 lvalue.getAlignment(), e->getType(),
2083 lvalue.getTBAAInfo());
2084 EmitStoreOfScalar(value, lvalue.getAddress(),
2085 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2086 e->getType(), lvalue.getTBAAInfo());
2087 EmitARCRelease(oldValue, /*precise*/ false);
2088 } else {
John McCall545d9962011-06-25 02:11:03 +00002089 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002090 }
2091
2092 return std::pair<LValue,llvm::Value*>(lvalue, value);
2093}
2094
2095std::pair<LValue,llvm::Value*>
2096CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2097 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2098 LValue lvalue = EmitLValue(e->getLHS());
2099
2100 EmitStoreOfScalar(value, lvalue.getAddress(),
2101 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2102 e->getType(), lvalue.getTBAAInfo());
2103
2104 return std::pair<LValue,llvm::Value*>(lvalue, value);
2105}
2106
2107void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2108 const ObjCAutoreleasePoolStmt &ARPS) {
2109 const Stmt *subStmt = ARPS.getSubStmt();
2110 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2111
2112 CGDebugInfo *DI = getDebugInfo();
2113 if (DI) {
2114 DI->setLocation(S.getLBracLoc());
2115 DI->EmitRegionStart(Builder);
2116 }
2117
2118 // Keep track of the current cleanup stack depth.
2119 RunCleanupsScope Scope(*this);
John McCall9f084a32011-07-06 00:26:06 +00002120 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCallf85e1932011-06-15 23:02:42 +00002121 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2122 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2123 } else {
2124 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2125 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2126 }
2127
2128 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2129 E = S.body_end(); I != E; ++I)
2130 EmitStmt(*I);
2131
2132 if (DI) {
2133 DI->setLocation(S.getRBracLoc());
2134 DI->EmitRegionEnd(Builder);
2135 }
2136}
John McCall0c24c802011-06-24 23:21:27 +00002137
2138/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2139/// make sure it survives garbage collection until this point.
2140void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2141 // We just use an inline assembly.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002142 llvm::Type *paramTypes[] = { VoidPtrTy };
John McCall0c24c802011-06-24 23:21:27 +00002143 llvm::FunctionType *extenderType
2144 = llvm::FunctionType::get(VoidTy, paramTypes, /*variadic*/ false);
2145 llvm::Value *extender
2146 = llvm::InlineAsm::get(extenderType,
2147 /* assembly */ "",
2148 /* constraints */ "r",
2149 /* side effects */ true);
2150
2151 object = Builder.CreateBitCast(object, VoidPtrTy);
2152 Builder.CreateCall(extender, object)->setDoesNotThrow();
2153}
2154
Ted Kremenek2979ec72008-04-09 15:51:31 +00002155CGObjCRuntime::~CGObjCRuntime() {}