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