blob: 62ee03c089f91fc657b9dd0c2d6a0dd017227e71 [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 McCall7acddac2011-06-17 06:42:21 +00001113
1114 if (D->isARCPseudoStrong())
1115 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001116 } else {
1117 elementLValue = LValue(); // suppress warning
1118 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001119 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001120 }
1121 const llvm::Type *convertedElementType = ConvertType(elementType);
1122
1123 // Fetch the buffer out of the enumeration state.
1124 // TODO: this pointer should actually be invariant between
1125 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001126 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001127 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001128 llvm::Value *EnumStateItems =
1129 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001130
John McCalld88687f2011-01-07 01:49:06 +00001131 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001133 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1134 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001135
John McCalld88687f2011-01-07 01:49:06 +00001136 // Cast that value to the right type.
1137 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1138 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001139
John McCalld88687f2011-01-07 01:49:06 +00001140 // Make sure we have an l-value. Yes, this gets evaluated every
1141 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001142 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001143 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall7acddac2011-06-17 06:42:21 +00001144 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
1145 } else {
1146 EmitScalarInit(CurrentItem, elementLValue);
1147 }
Mike Stump1eb44332009-09-09 15:08:12 +00001148
John McCall57b3b6a2011-02-22 07:16:58 +00001149 // If we do have an element variable, this assignment is the end of
1150 // its initialization.
1151 if (elementIsVariable)
1152 EmitAutoVarCleanups(variable);
1153
John McCalld88687f2011-01-07 01:49:06 +00001154 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001155 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001156 {
1157 RunCleanupsScope Scope(*this);
1158 EmitStmt(S.getBody());
1159 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001160 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001161
John McCalld88687f2011-01-07 01:49:06 +00001162 // Destroy the element variable now.
1163 elementVariableScope.ForceCleanup();
1164
1165 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001166 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001167
John McCalld88687f2011-01-07 01:49:06 +00001168 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001169
John McCalld88687f2011-01-07 01:49:06 +00001170 // First we check in the local buffer.
1171 llvm::Value *indexPlusOne
1172 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001173
John McCalld88687f2011-01-07 01:49:06 +00001174 // If we haven't overrun the buffer yet, we can continue.
1175 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1176 LoopBodyBB, FetchMoreBB);
1177
1178 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1179 count->addIncoming(count, AfterBody.getBlock());
1180
1181 // Otherwise, we have to fetch more elements.
1182 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
1184 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001185 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001186 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001187 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001188 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCalld88687f2011-01-07 01:49:06 +00001190 // If we got a zero count, we're done.
1191 llvm::Value *refetchCount = CountRV.getScalarVal();
1192
1193 // (note that the message send might split FetchMoreBB)
1194 index->addIncoming(zero, Builder.GetInsertBlock());
1195 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1196
1197 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1198 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001199
Anders Carlssonf484c312008-08-31 02:33:12 +00001200 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001201 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001202
John McCall57b3b6a2011-02-22 07:16:58 +00001203 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001204 // If the element was not a declaration, set it to be null.
1205
John McCalld88687f2011-01-07 01:49:06 +00001206 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1207 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1208 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
Anders Carlssonf484c312008-08-31 02:33:12 +00001209 }
1210
Devang Patelbcbd03a2011-01-19 01:36:36 +00001211 if (DI) {
1212 DI->setLocation(S.getSourceRange().getEnd());
1213 DI->EmitRegionEnd(Builder);
1214 }
1215
John McCallff8e1152010-07-23 21:56:41 +00001216 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001217}
1218
Mike Stump1eb44332009-09-09 15:08:12 +00001219void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001220 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001221}
1222
Mike Stump1eb44332009-09-09 15:08:12 +00001223void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001224 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1225}
1226
Chris Lattner10cac6f2008-11-15 21:26:17 +00001227void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001228 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001229 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001230}
1231
John McCallf85e1932011-06-15 23:02:42 +00001232/// Produce the code for a CK_ObjCProduceObject. Just does a
1233/// primitive retain.
1234llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1235 llvm::Value *value) {
1236 return EmitARCRetain(type, value);
1237}
1238
1239namespace {
1240 struct CallObjCRelease : EHScopeStack::Cleanup {
1241 CallObjCRelease(QualType type, llvm::Value *ptr, llvm::Value *condition)
1242 : type(type), ptr(ptr), condition(condition) {}
1243 QualType type;
1244 llvm::Value *ptr;
1245 llvm::Value *condition;
1246
1247 void Emit(CodeGenFunction &CGF, bool forEH) {
1248 llvm::Value *object;
1249
1250 // If we're in a conditional branch, we had to stash away in an
1251 // alloca the pointer to be released.
1252 llvm::BasicBlock *cont = 0;
1253 if (condition) {
1254 llvm::BasicBlock *release = CGF.createBasicBlock("release.yes");
1255 cont = CGF.createBasicBlock("release.cont");
1256
1257 llvm::Value *cond = CGF.Builder.CreateLoad(condition);
1258 CGF.Builder.CreateCondBr(cond, release, cont);
1259 CGF.EmitBlock(release);
1260 object = CGF.Builder.CreateLoad(ptr);
1261 } else {
1262 object = ptr;
1263 }
1264
1265 CGF.EmitARCRelease(object, /*precise*/ true);
1266
1267 if (cont) CGF.EmitBlock(cont);
1268 }
1269 };
1270}
1271
1272/// Produce the code for a CK_ObjCConsumeObject. Does a primitive
1273/// release at the end of the full-expression.
1274llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1275 llvm::Value *object) {
1276 // If we're in a conditional branch, we need to make the cleanup
1277 // conditional. FIXME: this really needs to be supported by the
1278 // environment.
1279 llvm::AllocaInst *cond;
1280 llvm::Value *ptr;
1281 if (isInConditionalBranch()) {
1282 cond = CreateTempAlloca(Builder.getInt1Ty(), "release.cond");
1283 ptr = CreateTempAlloca(object->getType(), "release.value");
1284
1285 // The alloca is false until we get here.
1286 // FIXME: er. doesn't this need to be set at the start of the condition?
1287 InitTempAlloca(cond, Builder.getFalse());
1288
1289 // Then it turns true.
1290 Builder.CreateStore(Builder.getTrue(), cond);
1291 Builder.CreateStore(object, ptr);
1292 } else {
1293 cond = 0;
1294 ptr = object;
1295 }
1296
1297 EHStack.pushCleanup<CallObjCRelease>(getARCCleanupKind(), type, ptr, cond);
1298 return object;
1299}
1300
1301llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1302 llvm::Value *value) {
1303 return EmitARCRetainAutorelease(type, value);
1304}
1305
1306
1307static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1308 const llvm::FunctionType *type,
1309 llvm::StringRef fnName) {
1310 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1311
1312 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1313 // support library.
1314 if (CGM.getLangOptions().ObjCNoAutoRefCountRuntime)
1315 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1316 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1317
1318 return fn;
1319}
1320
1321/// Perform an operation having the signature
1322/// i8* (i8*)
1323/// where a null input causes a no-op and returns null.
1324static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1325 llvm::Value *value,
1326 llvm::Constant *&fn,
1327 llvm::StringRef fnName) {
1328 if (isa<llvm::ConstantPointerNull>(value)) return value;
1329
1330 if (!fn) {
1331 std::vector<const llvm::Type*> args(1, CGF.Int8PtrTy);
1332 const llvm::FunctionType *fnType =
1333 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1334 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1335 }
1336
1337 // Cast the argument to 'id'.
1338 const llvm::Type *origType = value->getType();
1339 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1340
1341 // Call the function.
1342 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1343 call->setDoesNotThrow();
1344
1345 // Cast the result back to the original type.
1346 return CGF.Builder.CreateBitCast(call, origType);
1347}
1348
1349/// Perform an operation having the following signature:
1350/// i8* (i8**)
1351static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1352 llvm::Value *addr,
1353 llvm::Constant *&fn,
1354 llvm::StringRef fnName) {
1355 if (!fn) {
1356 std::vector<const llvm::Type*> args(1, CGF.Int8PtrPtrTy);
1357 const llvm::FunctionType *fnType =
1358 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1359 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1360 }
1361
1362 // Cast the argument to 'id*'.
1363 const llvm::Type *origType = addr->getType();
1364 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1365
1366 // Call the function.
1367 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1368 call->setDoesNotThrow();
1369
1370 // Cast the result back to a dereference of the original type.
1371 llvm::Value *result = call;
1372 if (origType != CGF.Int8PtrPtrTy)
1373 result = CGF.Builder.CreateBitCast(result,
1374 cast<llvm::PointerType>(origType)->getElementType());
1375
1376 return result;
1377}
1378
1379/// Perform an operation having the following signature:
1380/// i8* (i8**, i8*)
1381static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1382 llvm::Value *addr,
1383 llvm::Value *value,
1384 llvm::Constant *&fn,
1385 llvm::StringRef fnName,
1386 bool ignored) {
1387 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1388 == value->getType());
1389
1390 if (!fn) {
1391 std::vector<const llvm::Type*> argTypes(2);
1392 argTypes[0] = CGF.Int8PtrPtrTy;
1393 argTypes[1] = CGF.Int8PtrTy;
1394
1395 const llvm::FunctionType *fnType
1396 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1397 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1398 }
1399
1400 const llvm::Type *origType = value->getType();
1401
1402 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1403 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1404
1405 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1406 result->setDoesNotThrow();
1407
1408 if (ignored) return 0;
1409
1410 return CGF.Builder.CreateBitCast(result, origType);
1411}
1412
1413/// Perform an operation having the following signature:
1414/// void (i8**, i8**)
1415static void emitARCCopyOperation(CodeGenFunction &CGF,
1416 llvm::Value *dst,
1417 llvm::Value *src,
1418 llvm::Constant *&fn,
1419 llvm::StringRef fnName) {
1420 assert(dst->getType() == src->getType());
1421
1422 if (!fn) {
1423 std::vector<const llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
1424 const llvm::FunctionType *fnType
1425 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1426 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1427 }
1428
1429 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1430 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1431
1432 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1433 result->setDoesNotThrow();
1434}
1435
1436/// Produce the code to do a retain. Based on the type, calls one of:
1437/// call i8* @objc_retain(i8* %value)
1438/// call i8* @objc_retainBlock(i8* %value)
1439llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1440 if (type->isBlockPointerType())
1441 return EmitARCRetainBlock(value);
1442 else
1443 return EmitARCRetainNonBlock(value);
1444}
1445
1446/// Retain the given object, with normal retain semantics.
1447/// call i8* @objc_retain(i8* %value)
1448llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1449 return emitARCValueOperation(*this, value,
1450 CGM.getARCEntrypoints().objc_retain,
1451 "objc_retain");
1452}
1453
1454/// Retain the given block, with _Block_copy semantics.
1455/// call i8* @objc_retainBlock(i8* %value)
1456llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value) {
1457 return emitARCValueOperation(*this, value,
1458 CGM.getARCEntrypoints().objc_retainBlock,
1459 "objc_retainBlock");
1460}
1461
1462/// Retain the given object which is the result of a function call.
1463/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1464///
1465/// Yes, this function name is one character away from a different
1466/// call with completely different semantics.
1467llvm::Value *
1468CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1469 // Fetch the void(void) inline asm which marks that we're going to
1470 // retain the autoreleased return value.
1471 llvm::InlineAsm *&marker
1472 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1473 if (!marker) {
1474 llvm::StringRef assembly
1475 = CGM.getTargetCodeGenInfo()
1476 .getARCRetainAutoreleasedReturnValueMarker();
1477
1478 // If we have an empty assembly string, there's nothing to do.
1479 if (assembly.empty()) {
1480
1481 // Otherwise, at -O0, build an inline asm that we're going to call
1482 // in a moment.
1483 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1484 llvm::FunctionType *type =
1485 llvm::FunctionType::get(llvm::Type::getVoidTy(getLLVMContext()),
1486 /*variadic*/ false);
1487
1488 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1489
1490 // If we're at -O1 and above, we don't want to litter the code
1491 // with this marker yet, so leave a breadcrumb for the ARC
1492 // optimizer to pick up.
1493 } else {
1494 llvm::NamedMDNode *metadata =
1495 CGM.getModule().getOrInsertNamedMetadata(
1496 "clang.arc.retainAutoreleasedReturnValueMarker");
1497 assert(metadata->getNumOperands() <= 1);
1498 if (metadata->getNumOperands() == 0) {
1499 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1500 llvm::Value *args[] = { string };
1501 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), args));
1502 }
1503 }
1504 }
1505
1506 // Call the marker asm if we made one, which we do only at -O0.
1507 if (marker) Builder.CreateCall(marker);
1508
1509 return emitARCValueOperation(*this, value,
1510 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1511 "objc_retainAutoreleasedReturnValue");
1512}
1513
1514/// Release the given object.
1515/// call void @objc_release(i8* %value)
1516void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1517 if (isa<llvm::ConstantPointerNull>(value)) return;
1518
1519 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1520 if (!fn) {
1521 std::vector<const llvm::Type*> args(1, Int8PtrTy);
1522 const llvm::FunctionType *fnType =
1523 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1524 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1525 }
1526
1527 // Cast the argument to 'id'.
1528 value = Builder.CreateBitCast(value, Int8PtrTy);
1529
1530 // Call objc_release.
1531 llvm::CallInst *call = Builder.CreateCall(fn, value);
1532 call->setDoesNotThrow();
1533
1534 if (!precise) {
1535 llvm::SmallVector<llvm::Value*,1> args;
1536 call->setMetadata("clang.imprecise_release",
1537 llvm::MDNode::get(Builder.getContext(), args));
1538 }
1539}
1540
1541/// Store into a strong object. Always calls this:
1542/// call void @objc_storeStrong(i8** %addr, i8* %value)
1543llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1544 llvm::Value *value,
1545 bool ignored) {
1546 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1547 == value->getType());
1548
1549 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1550 if (!fn) {
1551 const llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
1552 const llvm::FunctionType *fnType
1553 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1554 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1555 }
1556
1557 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1558 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1559
1560 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1561
1562 if (ignored) return 0;
1563 return value;
1564}
1565
1566/// Store into a strong object. Sometimes calls this:
1567/// call void @objc_storeStrong(i8** %addr, i8* %value)
1568/// Other times, breaks it down into components.
1569llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst, QualType type,
1570 llvm::Value *newValue,
1571 bool ignored) {
1572 bool isBlock = type->isBlockPointerType();
1573
1574 // Use a store barrier at -O0 unless this is a block type or the
1575 // lvalue is inadequately aligned.
1576 if (shouldUseFusedARCCalls() &&
1577 !isBlock &&
1578 !(dst.getAlignment() && dst.getAlignment() < PointerAlignInBytes)) {
1579 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1580 }
1581
1582 // Otherwise, split it out.
1583
1584 // Retain the new value.
1585 newValue = EmitARCRetain(type, newValue);
1586
1587 // Read the old value.
1588 llvm::Value *oldValue =
1589 EmitLoadOfScalar(dst.getAddress(), dst.isVolatileQualified(),
1590 dst.getAlignment(), type, dst.getTBAAInfo());
1591
1592 // Store. We do this before the release so that any deallocs won't
1593 // see the old value.
1594 EmitStoreOfScalar(newValue, dst.getAddress(),
1595 dst.isVolatileQualified(), dst.getAlignment(),
1596 type, dst.getTBAAInfo());
1597
1598 // Finally, release the old value.
1599 EmitARCRelease(oldValue, /*precise*/ false);
1600
1601 return newValue;
1602}
1603
1604/// Autorelease the given object.
1605/// call i8* @objc_autorelease(i8* %value)
1606llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
1607 return emitARCValueOperation(*this, value,
1608 CGM.getARCEntrypoints().objc_autorelease,
1609 "objc_autorelease");
1610}
1611
1612/// Autorelease the given object.
1613/// call i8* @objc_autoreleaseReturnValue(i8* %value)
1614llvm::Value *
1615CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
1616 return emitARCValueOperation(*this, value,
1617 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
1618 "objc_autoreleaseReturnValue");
1619}
1620
1621/// Do a fused retain/autorelease of the given object.
1622/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
1623llvm::Value *
1624CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
1625 return emitARCValueOperation(*this, value,
1626 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
1627 "objc_retainAutoreleaseReturnValue");
1628}
1629
1630/// Do a fused retain/autorelease of the given object.
1631/// call i8* @objc_retainAutorelease(i8* %value)
1632/// or
1633/// %retain = call i8* @objc_retainBlock(i8* %value)
1634/// call i8* @objc_autorelease(i8* %retain)
1635llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
1636 llvm::Value *value) {
1637 if (!type->isBlockPointerType())
1638 return EmitARCRetainAutoreleaseNonBlock(value);
1639
1640 if (isa<llvm::ConstantPointerNull>(value)) return value;
1641
1642 const llvm::Type *origType = value->getType();
1643 value = Builder.CreateBitCast(value, Int8PtrTy);
1644 value = EmitARCRetainBlock(value);
1645 value = EmitARCAutorelease(value);
1646 return Builder.CreateBitCast(value, origType);
1647}
1648
1649/// Do a fused retain/autorelease of the given object.
1650/// call i8* @objc_retainAutorelease(i8* %value)
1651llvm::Value *
1652CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
1653 return emitARCValueOperation(*this, value,
1654 CGM.getARCEntrypoints().objc_retainAutorelease,
1655 "objc_retainAutorelease");
1656}
1657
1658/// i8* @objc_loadWeak(i8** %addr)
1659/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
1660llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
1661 return emitARCLoadOperation(*this, addr,
1662 CGM.getARCEntrypoints().objc_loadWeak,
1663 "objc_loadWeak");
1664}
1665
1666/// i8* @objc_loadWeakRetained(i8** %addr)
1667llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
1668 return emitARCLoadOperation(*this, addr,
1669 CGM.getARCEntrypoints().objc_loadWeakRetained,
1670 "objc_loadWeakRetained");
1671}
1672
1673/// i8* @objc_storeWeak(i8** %addr, i8* %value)
1674/// Returns %value.
1675llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
1676 llvm::Value *value,
1677 bool ignored) {
1678 return emitARCStoreOperation(*this, addr, value,
1679 CGM.getARCEntrypoints().objc_storeWeak,
1680 "objc_storeWeak", ignored);
1681}
1682
1683/// i8* @objc_initWeak(i8** %addr, i8* %value)
1684/// Returns %value. %addr is known to not have a current weak entry.
1685/// Essentially equivalent to:
1686/// *addr = nil; objc_storeWeak(addr, value);
1687void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
1688 // If we're initializing to null, just write null to memory; no need
1689 // to get the runtime involved. But don't do this if optimization
1690 // is enabled, because accounting for this would make the optimizer
1691 // much more complicated.
1692 if (isa<llvm::ConstantPointerNull>(value) &&
1693 CGM.getCodeGenOpts().OptimizationLevel == 0) {
1694 Builder.CreateStore(value, addr);
1695 return;
1696 }
1697
1698 emitARCStoreOperation(*this, addr, value,
1699 CGM.getARCEntrypoints().objc_initWeak,
1700 "objc_initWeak", /*ignored*/ true);
1701}
1702
1703/// void @objc_destroyWeak(i8** %addr)
1704/// Essentially objc_storeWeak(addr, nil).
1705void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
1706 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
1707 if (!fn) {
1708 std::vector<const llvm::Type*> args(1, Int8PtrPtrTy);
1709 const llvm::FunctionType *fnType =
1710 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1711 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
1712 }
1713
1714 // Cast the argument to 'id*'.
1715 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1716
1717 llvm::CallInst *call = Builder.CreateCall(fn, addr);
1718 call->setDoesNotThrow();
1719}
1720
1721/// void @objc_moveWeak(i8** %dest, i8** %src)
1722/// Disregards the current value in %dest. Leaves %src pointing to nothing.
1723/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
1724void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
1725 emitARCCopyOperation(*this, dst, src,
1726 CGM.getARCEntrypoints().objc_moveWeak,
1727 "objc_moveWeak");
1728}
1729
1730/// void @objc_copyWeak(i8** %dest, i8** %src)
1731/// Disregards the current value in %dest. Essentially
1732/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
1733void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
1734 emitARCCopyOperation(*this, dst, src,
1735 CGM.getARCEntrypoints().objc_copyWeak,
1736 "objc_copyWeak");
1737}
1738
1739/// Produce the code to do a objc_autoreleasepool_push.
1740/// call i8* @objc_autoreleasePoolPush(void)
1741llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
1742 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
1743 if (!fn) {
1744 const llvm::FunctionType *fnType =
1745 llvm::FunctionType::get(Int8PtrTy, false);
1746 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
1747 }
1748
1749 llvm::CallInst *call = Builder.CreateCall(fn);
1750 call->setDoesNotThrow();
1751
1752 return call;
1753}
1754
1755/// Produce the code to do a primitive release.
1756/// call void @objc_autoreleasePoolPop(i8* %ptr)
1757void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
1758 assert(value->getType() == Int8PtrTy);
1759
1760 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
1761 if (!fn) {
1762 std::vector<const llvm::Type*> args(1, Int8PtrTy);
1763 const llvm::FunctionType *fnType =
1764 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1765
1766 // We don't want to use a weak import here; instead we should not
1767 // fall into this path.
1768 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
1769 }
1770
1771 llvm::CallInst *call = Builder.CreateCall(fn, value);
1772 call->setDoesNotThrow();
1773}
1774
1775/// Produce the code to do an MRR version objc_autoreleasepool_push.
1776/// Which is: [[NSAutoreleasePool alloc] init];
1777/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
1778/// init is declared as: - (id) init; in its NSObject super class.
1779///
1780llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
1781 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
1782 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
1783 // [NSAutoreleasePool alloc]
1784 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
1785 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
1786 CallArgList Args;
1787 RValue AllocRV =
1788 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1789 getContext().getObjCIdType(),
1790 AllocSel, Receiver, Args);
1791
1792 // [Receiver init]
1793 Receiver = AllocRV.getScalarVal();
1794 II = &CGM.getContext().Idents.get("init");
1795 Selector InitSel = getContext().Selectors.getSelector(0, &II);
1796 RValue InitRV =
1797 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
1798 getContext().getObjCIdType(),
1799 InitSel, Receiver, Args);
1800 return InitRV.getScalarVal();
1801}
1802
1803/// Produce the code to do a primitive release.
1804/// [tmp drain];
1805void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
1806 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
1807 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
1808 CallArgList Args;
1809 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1810 getContext().VoidTy, DrainSel, Arg, Args);
1811}
1812
1813namespace {
1814 struct ObjCReleasingCleanup : EHScopeStack::Cleanup {
1815 private:
1816 QualType type;
1817 llvm::Value *addr;
1818
1819 protected:
1820 ObjCReleasingCleanup(QualType type, llvm::Value *addr)
1821 : type(type), addr(addr) {}
1822
1823 virtual llvm::Value *getAddress(CodeGenFunction &CGF,
1824 llvm::Value *addr) {
1825 return addr;
1826 }
1827
1828 virtual void release(CodeGenFunction &CGF,
1829 QualType type,
1830 llvm::Value *addr) = 0;
1831
1832 public:
1833 void Emit(CodeGenFunction &CGF, bool isForEH) {
1834 const ArrayType *arrayType = CGF.getContext().getAsArrayType(type);
1835
1836 llvm::Value *addr = getAddress(CGF, this->addr);
1837
1838 // If we don't have an array type, this is easy.
1839 if (!arrayType)
1840 return release(CGF, type, addr);
1841
1842 llvm::Value *begin = addr;
1843 QualType baseType;
1844
1845 // Otherwise, this is more painful.
1846 llvm::Value *count = emitArrayLength(CGF, arrayType, baseType,
1847 begin);
1848
1849 assert(baseType == CGF.getContext().getBaseElementType(arrayType));
1850
1851 llvm::BasicBlock *incomingBB = CGF.Builder.GetInsertBlock();
1852
1853 // id *cur = begin;
1854 // id *end = begin + count;
1855 llvm::Value *end =
1856 CGF.Builder.CreateInBoundsGEP(begin, count, "array.end");
1857
1858 // loopBB:
1859 llvm::BasicBlock *loopBB = CGF.createBasicBlock("release-loop");
1860 CGF.EmitBlock(loopBB);
1861
1862 llvm::PHINode *cur = CGF.Builder.CreatePHI(begin->getType(), 2, "cur");
1863 cur->addIncoming(begin, incomingBB);
1864
1865 // if (cur == end) goto endBB;
1866 llvm::Value *eq = CGF.Builder.CreateICmpEQ(cur, end, "release-loop.done");
1867 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("release-loop.body");
1868 llvm::BasicBlock *endBB = CGF.createBasicBlock("release-loop.cont");
1869 CGF.Builder.CreateCondBr(eq, endBB, bodyBB);
1870 CGF.EmitBlock(bodyBB);
1871
1872 // Release the value at 'cur'.
1873 release(CGF, baseType, cur);
1874
1875 // ++cur;
1876 // goto loopBB;
1877 llvm::Value *next = CGF.Builder.CreateConstInBoundsGEP1_32(cur, 1);
1878 cur->addIncoming(next, CGF.Builder.GetInsertBlock());
1879 CGF.Builder.CreateBr(loopBB);
1880
1881 // endBB:
1882 CGF.EmitBlock(endBB);
1883 }
1884
1885 private:
1886 /// Computes the length of an array in elements, as well
1887 /// as the base
1888 static llvm::Value *emitArrayLength(CodeGenFunction &CGF,
1889 const ArrayType *origArrayType,
1890 QualType &baseType,
1891 llvm::Value *&addr) {
1892 ASTContext &Ctx = CGF.getContext();
1893 const ArrayType *arrayType = origArrayType;
1894
1895 // If it's a VLA, we have to load the stored size. Note that
1896 // this is the size of the VLA in bytes, not its size in elements.
John McCallbc8d40d2011-06-24 21:55:10 +00001897 llvm::Value *numVLAElements = 0;
John McCallf85e1932011-06-15 23:02:42 +00001898 if (isa<VariableArrayType>(arrayType)) {
John McCallbc8d40d2011-06-24 21:55:10 +00001899 numVLAElements =
1900 CGF.getVLASize(cast<VariableArrayType>(arrayType)).first;
John McCallf85e1932011-06-15 23:02:42 +00001901
1902 // Walk into all VLAs. This doesn't require changes to addr,
1903 // which has type T* where T is the first non-VLA element type.
1904 do {
1905 QualType elementType = arrayType->getElementType();
1906 arrayType = Ctx.getAsArrayType(elementType);
1907
1908 // If we only have VLA components, 'addr' requires no adjustment.
1909 if (!arrayType) {
1910 baseType = elementType;
John McCallbc8d40d2011-06-24 21:55:10 +00001911 return numVLAElements;
John McCallf85e1932011-06-15 23:02:42 +00001912 }
1913 } while (isa<VariableArrayType>(arrayType));
1914
1915 // We get out here only if we find a constant array type
1916 // inside the VLA.
1917 }
1918
1919 // We have some number of constant-length arrays, so addr should
1920 // have LLVM type [M x [N x [...]]]*. Build a GEP that walks
1921 // down to the first element of addr.
1922 llvm::SmallVector<llvm::Value*, 8> gepIndices;
1923
1924 // GEP down to the array type.
1925 llvm::ConstantInt *zero = CGF.Builder.getInt32(0);
1926 gepIndices.push_back(zero);
1927
1928 // It's more efficient to calculate the count from the LLVM
1929 // constant-length arrays than to re-evaluate the array bounds.
1930 uint64_t countFromCLAs = 1;
1931
1932 const llvm::ArrayType *llvmArrayType =
1933 cast<llvm::ArrayType>(
1934 cast<llvm::PointerType>(addr->getType())->getElementType());
1935 while (true) {
1936 assert(isa<ConstantArrayType>(arrayType));
1937 assert(cast<ConstantArrayType>(arrayType)->getSize().getZExtValue()
1938 == llvmArrayType->getNumElements());
1939
1940 gepIndices.push_back(zero);
1941 countFromCLAs *= llvmArrayType->getNumElements();
1942
1943 llvmArrayType =
1944 dyn_cast<llvm::ArrayType>(llvmArrayType->getElementType());
1945 if (!llvmArrayType) break;
1946
1947 arrayType = Ctx.getAsArrayType(arrayType->getElementType());
1948 assert(arrayType && "LLVM and Clang types are out-of-synch");
1949 }
1950
John McCallbc8d40d2011-06-24 21:55:10 +00001951 baseType = arrayType->getElementType();
1952
John McCallf85e1932011-06-15 23:02:42 +00001953 // Create the actual GEP.
1954 addr = CGF.Builder.CreateInBoundsGEP(addr, gepIndices.begin(),
1955 gepIndices.end(), "array.begin");
1956
John McCallbc8d40d2011-06-24 21:55:10 +00001957 llvm::Value *numElements
1958 = llvm::ConstantInt::get(CGF.IntPtrTy, countFromCLAs);
John McCallf85e1932011-06-15 23:02:42 +00001959
John McCallbc8d40d2011-06-24 21:55:10 +00001960 // If we had any VLA dimensions, factor them in.
1961 if (numVLAElements)
1962 numElements = CGF.Builder.CreateNUWMul(numVLAElements, numElements);
John McCallf85e1932011-06-15 23:02:42 +00001963
John McCallbc8d40d2011-06-24 21:55:10 +00001964 return numElements;
John McCallf85e1932011-06-15 23:02:42 +00001965 }
1966
1967 static llvm::Value *divideVLASizeByBaseType(CodeGenFunction &CGF,
1968 llvm::Value *vlaSizeInBytes,
1969 QualType baseType) {
1970 // Divide the base type size back out of the
1971 CharUnits baseSize = CGF.getContext().getTypeSizeInChars(baseType);
1972 llvm::Value *baseSizeInBytes =
1973 llvm::ConstantInt::get(vlaSizeInBytes->getType(),
1974 baseSize.getQuantity());
1975
1976 return CGF.Builder.CreateUDiv(vlaSizeInBytes, baseSizeInBytes,
1977 "array.vla-count");
1978 }
1979 };
1980
1981 /// A cleanup that calls @objc_release on all the objects to release.
1982 struct CallReleaseForObject : ObjCReleasingCleanup {
1983 bool precise;
1984 CallReleaseForObject(QualType type, llvm::Value *addr, bool precise)
1985 : ObjCReleasingCleanup(type, addr), precise(precise) {}
1986
Douglas Gregord7b23162011-06-22 16:12:01 +00001987 using ObjCReleasingCleanup::Emit;
1988 static void Emit(CodeGenFunction &CGF, bool IsForEH,
1989 QualType type, llvm::Value *addr, bool precise) {
1990 // EHScopeStack::Cleanup objects can never have their destructors called,
1991 // so use placement new to construct our temporary object.
1992 union {
1993 void* align;
1994 char data[sizeof(CallReleaseForObject)];
1995 };
1996
1997 CallReleaseForObject *Object
1998 = new (&align) CallReleaseForObject(type, addr, precise);
1999 Object->Emit(CGF, IsForEH);
Douglas Gregor34aace82011-06-22 16:43:25 +00002000 (void)data[0];
Douglas Gregord7b23162011-06-22 16:12:01 +00002001 }
2002
John McCallf85e1932011-06-15 23:02:42 +00002003 void release(CodeGenFunction &CGF, QualType type, llvm::Value *addr) {
2004 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "tmp");
2005 CGF.EmitARCRelease(ptr, precise);
2006 }
2007 };
2008
2009 /// A cleanup that calls @objc_storeStrong(nil) on all the objects to
2010 /// release in an ivar.
2011 struct CallReleaseForIvar : ObjCReleasingCleanup {
2012 const ObjCIvarDecl *ivar;
2013 CallReleaseForIvar(const ObjCIvarDecl *ivar, llvm::Value *self)
2014 : ObjCReleasingCleanup(ivar->getType(), self), ivar(ivar) {}
2015
2016 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *addr) {
2017 LValue lvalue
2018 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
2019 return lvalue.getAddress();
2020 }
2021
2022 void release(CodeGenFunction &CGF, QualType type, llvm::Value *addr) {
2023 // Release ivars by storing nil into them; it just makes things easier.
2024 llvm::Value *null = getNullForVariable(addr);
2025 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2026 }
2027 };
2028
2029 /// A cleanup that calls @objc_release on all of the objects to release in
2030 /// a field.
2031 struct CallReleaseForField : CallReleaseForObject {
2032 const FieldDecl *Field;
2033
2034 explicit CallReleaseForField(const FieldDecl *Field)
2035 : CallReleaseForObject(Field->getType(), 0, /*precise=*/true),
2036 Field(Field) { }
2037
2038 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *) {
2039 llvm::Value *This = CGF.LoadCXXThis();
2040 LValue LV = CGF.EmitLValueForField(This, Field, 0);
2041 return LV.getAddress();
2042 }
2043 };
2044
2045 /// A cleanup that calls @objc_weak_release on all the objects to
2046 /// release in an object.
2047 struct CallWeakReleaseForObject : ObjCReleasingCleanup {
2048 CallWeakReleaseForObject(QualType type, llvm::Value *addr)
2049 : ObjCReleasingCleanup(type, addr) {}
2050
Douglas Gregord7b23162011-06-22 16:12:01 +00002051 using ObjCReleasingCleanup::Emit;
2052 static void Emit(CodeGenFunction &CGF, bool IsForEH,
2053 QualType type, llvm::Value *addr) {
2054 // EHScopeStack::Cleanup objects can never have their destructors called,
2055 // so use placement new to construct our temporary object.
2056 union {
2057 void* align;
2058 char data[sizeof(CallWeakReleaseForObject)];
2059 };
2060
2061 CallWeakReleaseForObject *Object
2062 = new (&align) CallWeakReleaseForObject(type, addr);
2063 Object->Emit(CGF, IsForEH);
Douglas Gregor34aace82011-06-22 16:43:25 +00002064 (void)data[0];
Douglas Gregord7b23162011-06-22 16:12:01 +00002065 }
2066
John McCallf85e1932011-06-15 23:02:42 +00002067 void release(CodeGenFunction &CGF, QualType type, llvm::Value *addr) {
2068 CGF.EmitARCDestroyWeak(addr);
2069 }
2070 };
2071
2072
2073 /// A cleanup that calls @objc_weak_release on all the objects to
2074 /// release in an ivar.
2075 struct CallWeakReleaseForIvar : CallWeakReleaseForObject {
2076 const ObjCIvarDecl *ivar;
2077 CallWeakReleaseForIvar(const ObjCIvarDecl *ivar, llvm::Value *self)
2078 : CallWeakReleaseForObject(ivar->getType(), self), ivar(ivar) {}
2079
2080 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *addr) {
2081 LValue lvalue
2082 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
2083 return lvalue.getAddress();
2084 }
2085 };
2086
2087 /// A cleanup that calls @objc_weak_release on all the objects to
2088 /// release in a field;
2089 struct CallWeakReleaseForField : CallWeakReleaseForObject {
2090 const FieldDecl *Field;
2091 CallWeakReleaseForField(const FieldDecl *Field)
2092 : CallWeakReleaseForObject(Field->getType(), 0), Field(Field) {}
2093
2094 llvm::Value *getAddress(CodeGenFunction &CGF, llvm::Value *) {
2095 llvm::Value *This = CGF.LoadCXXThis();
2096 LValue LV = CGF.EmitLValueForField(This, Field, 0);
2097 return LV.getAddress();
2098 }
2099 };
2100
2101 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2102 llvm::Value *Token;
2103
2104 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2105
2106 void Emit(CodeGenFunction &CGF, bool isForEH) {
2107 CGF.EmitObjCAutoreleasePoolPop(Token);
2108 }
2109 };
2110 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2111 llvm::Value *Token;
2112
2113 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2114
2115 void Emit(CodeGenFunction &CGF, bool isForEH) {
2116 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2117 }
2118 };
2119}
2120
2121void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2122 if (CGM.getLangOptions().ObjCAutoRefCount)
2123 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2124 else
2125 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2126}
2127
2128/// PushARCReleaseCleanup - Enter a cleanup to perform a release on a
2129/// given object or array of objects.
2130void CodeGenFunction::PushARCReleaseCleanup(CleanupKind cleanupKind,
2131 QualType type,
2132 llvm::Value *addr,
Douglas Gregord7b23162011-06-22 16:12:01 +00002133 bool precise,
2134 bool forFullExpr) {
2135 if (forFullExpr)
2136 pushFullExprCleanup<CallReleaseForObject>(cleanupKind, type, addr, precise);
2137 else
2138 EHStack.pushCleanup<CallReleaseForObject>(cleanupKind, type, addr, precise);
John McCallf85e1932011-06-15 23:02:42 +00002139}
2140
2141/// PushARCWeakReleaseCleanup - Enter a cleanup to perform a weak
2142/// release on the given object or array of objects.
2143void CodeGenFunction::PushARCWeakReleaseCleanup(CleanupKind cleanupKind,
2144 QualType type,
Douglas Gregord7b23162011-06-22 16:12:01 +00002145 llvm::Value *addr,
2146 bool forFullExpr) {
2147 if (forFullExpr)
2148 pushFullExprCleanup<CallWeakReleaseForObject>(cleanupKind, type, addr);
2149 else
2150 EHStack.pushCleanup<CallWeakReleaseForObject>(cleanupKind, type, addr);
John McCallf85e1932011-06-15 23:02:42 +00002151}
2152
2153/// PushARCReleaseCleanup - Enter a cleanup to perform a release on a
2154/// given object or array of objects.
2155void CodeGenFunction::PushARCFieldReleaseCleanup(CleanupKind cleanupKind,
2156 const FieldDecl *field) {
2157 EHStack.pushCleanup<CallReleaseForField>(cleanupKind, field);
2158}
2159
2160/// PushARCWeakReleaseCleanup - Enter a cleanup to perform a weak
2161/// release on the given object or array of objects.
2162void CodeGenFunction::PushARCFieldWeakReleaseCleanup(CleanupKind cleanupKind,
2163 const FieldDecl *field) {
2164 EHStack.pushCleanup<CallWeakReleaseForField>(cleanupKind, field);
2165}
2166
2167static void pushReleaseForIvar(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
2168 llvm::Value *self) {
2169 CGF.EHStack.pushCleanup<CallReleaseForIvar>(CGF.getARCCleanupKind(),
2170 ivar, self);
2171}
2172
2173static void pushWeakReleaseForIvar(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
2174 llvm::Value *self) {
2175 CGF.EHStack.pushCleanup<CallWeakReleaseForIvar>(CGF.getARCCleanupKind(),
2176 ivar, self);
2177}
2178
2179static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2180 LValue lvalue,
2181 QualType type) {
2182 switch (type.getObjCLifetime()) {
2183 case Qualifiers::OCL_None:
2184 case Qualifiers::OCL_ExplicitNone:
2185 case Qualifiers::OCL_Strong:
2186 case Qualifiers::OCL_Autoreleasing:
2187 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue, type).getScalarVal(),
2188 false);
2189
2190 case Qualifiers::OCL_Weak:
2191 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2192 true);
2193 }
2194
2195 llvm_unreachable("impossible lifetime!");
2196 return TryEmitResult();
2197}
2198
2199static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2200 const Expr *e) {
2201 e = e->IgnoreParens();
2202 QualType type = e->getType();
2203
2204 // As a very special optimization, in ARC++, if the l-value is the
2205 // result of a non-volatile assignment, do a simple retain of the
2206 // result of the call to objc_storeWeak instead of reloading.
2207 if (CGF.getLangOptions().CPlusPlus &&
2208 !type.isVolatileQualified() &&
2209 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2210 isa<BinaryOperator>(e) &&
2211 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2212 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2213
2214 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2215}
2216
2217static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2218 llvm::Value *value);
2219
2220/// Given that the given expression is some sort of call (which does
2221/// not return retained), emit a retain following it.
2222static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2223 llvm::Value *value = CGF.EmitScalarExpr(e);
2224 return emitARCRetainAfterCall(CGF, value);
2225}
2226
2227static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2228 llvm::Value *value) {
2229 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2230 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2231
2232 // Place the retain immediately following the call.
2233 CGF.Builder.SetInsertPoint(call->getParent(),
2234 ++llvm::BasicBlock::iterator(call));
2235 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2236
2237 CGF.Builder.restoreIP(ip);
2238 return value;
2239 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2240 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2241
2242 // Place the retain at the beginning of the normal destination block.
2243 llvm::BasicBlock *BB = invoke->getNormalDest();
2244 CGF.Builder.SetInsertPoint(BB, BB->begin());
2245 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2246
2247 CGF.Builder.restoreIP(ip);
2248 return value;
2249
2250 // Bitcasts can arise because of related-result returns. Rewrite
2251 // the operand.
2252 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2253 llvm::Value *operand = bitcast->getOperand(0);
2254 operand = emitARCRetainAfterCall(CGF, operand);
2255 bitcast->setOperand(0, operand);
2256 return bitcast;
2257
2258 // Generic fall-back case.
2259 } else {
2260 // Retain using the non-block variant: we never need to do a copy
2261 // of a block that's been returned to us.
2262 return CGF.EmitARCRetainNonBlock(value);
2263 }
2264}
2265
2266static TryEmitResult
2267tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002268 // The desired result type, if it differs from the type of the
2269 // ultimate opaque expression.
2270 const llvm::Type *resultType = 0;
2271
Douglas Gregord1bd98a2011-06-22 16:32:26 +00002272 // If we're loading retained from a __strong xvalue, we can avoid
2273 // an extra retain/release pair by zeroing out the source of this
2274 // "move" operation.
2275 if (e->isXValue() &&
2276 e->getType().getObjCLifetime() == Qualifiers::OCL_Strong) {
2277 // Emit the lvalue
2278 LValue lv = CGF.EmitLValue(e);
2279
2280 // Load the object pointer and cast it to the appropriate type.
2281 QualType exprType = e->getType();
2282 llvm::Value *result = CGF.EmitLoadOfLValue(lv, exprType).getScalarVal();
2283
2284 if (resultType)
2285 result = CGF.Builder.CreateBitCast(result, resultType);
2286
2287 // Set the source pointer to NULL.
2288 llvm::Value *null
2289 = llvm::ConstantPointerNull::get(
2290 cast<llvm::PointerType>(CGF.ConvertType(exprType)));
2291 CGF.EmitStoreOfScalar(null, lv.getAddress(), lv.isVolatileQualified(),
2292 lv.getAlignment(), exprType);
2293
2294 return TryEmitResult(result, true);
2295 }
2296
John McCallf85e1932011-06-15 23:02:42 +00002297 while (true) {
2298 e = e->IgnoreParens();
2299
2300 // There's a break at the end of this if-chain; anything
2301 // that wants to keep looping has to explicitly continue.
2302 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2303 switch (ce->getCastKind()) {
2304 // No-op casts don't change the type, so we just ignore them.
2305 case CK_NoOp:
2306 e = ce->getSubExpr();
2307 continue;
2308
2309 case CK_LValueToRValue: {
2310 TryEmitResult loadResult
2311 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2312 if (resultType) {
2313 llvm::Value *value = loadResult.getPointer();
2314 value = CGF.Builder.CreateBitCast(value, resultType);
2315 loadResult.setPointer(value);
2316 }
2317 return loadResult;
2318 }
2319
2320 // These casts can change the type, so remember that and
2321 // soldier on. We only need to remember the outermost such
2322 // cast, though.
2323 case CK_AnyPointerToObjCPointerCast:
2324 case CK_AnyPointerToBlockPointerCast:
2325 case CK_BitCast:
2326 if (!resultType)
2327 resultType = CGF.ConvertType(ce->getType());
2328 e = ce->getSubExpr();
2329 assert(e->getType()->hasPointerRepresentation());
2330 continue;
2331
2332 // For consumptions, just emit the subexpression and thus elide
2333 // the retain/release pair.
2334 case CK_ObjCConsumeObject: {
2335 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2336 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2337 return TryEmitResult(result, true);
2338 }
2339
2340 case CK_GetObjCProperty: {
2341 llvm::Value *result = emitARCRetainCall(CGF, ce);
2342 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2343 return TryEmitResult(result, true);
2344 }
2345
2346 default:
2347 break;
2348 }
2349
2350 // Skip __extension__.
2351 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2352 if (op->getOpcode() == UO_Extension) {
2353 e = op->getSubExpr();
2354 continue;
2355 }
2356
2357 // For calls and message sends, use the retained-call logic.
2358 // Delegate inits are a special case in that they're the only
2359 // returns-retained expression that *isn't* surrounded by
2360 // a consume.
2361 } else if (isa<CallExpr>(e) ||
2362 (isa<ObjCMessageExpr>(e) &&
2363 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2364 llvm::Value *result = emitARCRetainCall(CGF, e);
2365 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2366 return TryEmitResult(result, true);
2367 }
2368
2369 // Conservatively halt the search at any other expression kind.
2370 break;
2371 }
2372
2373 // We didn't find an obvious production, so emit what we've got and
2374 // tell the caller that we didn't manage to retain.
2375 llvm::Value *result = CGF.EmitScalarExpr(e);
2376 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2377 return TryEmitResult(result, false);
2378}
2379
2380static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2381 LValue lvalue,
2382 QualType type) {
2383 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2384 llvm::Value *value = result.getPointer();
2385 if (!result.getInt())
2386 value = CGF.EmitARCRetain(type, value);
2387 return value;
2388}
2389
2390/// EmitARCRetainScalarExpr - Semantically equivalent to
2391/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2392/// best-effort attempt to peephole expressions that naturally produce
2393/// retained objects.
2394llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2395 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2396 llvm::Value *value = result.getPointer();
2397 if (!result.getInt())
2398 value = EmitARCRetain(e->getType(), value);
2399 return value;
2400}
2401
2402llvm::Value *
2403CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2404 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2405 llvm::Value *value = result.getPointer();
2406 if (result.getInt())
2407 value = EmitARCAutorelease(value);
2408 else
2409 value = EmitARCRetainAutorelease(e->getType(), value);
2410 return value;
2411}
2412
2413std::pair<LValue,llvm::Value*>
2414CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2415 bool ignored) {
2416 // Evaluate the RHS first.
2417 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2418 llvm::Value *value = result.getPointer();
2419
2420 LValue lvalue = EmitLValue(e->getLHS());
2421
2422 // If the RHS was emitted retained, expand this.
2423 if (result.getInt()) {
2424 llvm::Value *oldValue =
2425 EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatileQualified(),
2426 lvalue.getAlignment(), e->getType(),
2427 lvalue.getTBAAInfo());
2428 EmitStoreOfScalar(value, lvalue.getAddress(),
2429 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2430 e->getType(), lvalue.getTBAAInfo());
2431 EmitARCRelease(oldValue, /*precise*/ false);
2432 } else {
2433 value = EmitARCStoreStrong(lvalue, e->getType(), value, ignored);
2434 }
2435
2436 return std::pair<LValue,llvm::Value*>(lvalue, value);
2437}
2438
2439std::pair<LValue,llvm::Value*>
2440CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2441 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2442 LValue lvalue = EmitLValue(e->getLHS());
2443
2444 EmitStoreOfScalar(value, lvalue.getAddress(),
2445 lvalue.isVolatileQualified(), lvalue.getAlignment(),
2446 e->getType(), lvalue.getTBAAInfo());
2447
2448 return std::pair<LValue,llvm::Value*>(lvalue, value);
2449}
2450
2451void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2452 const ObjCAutoreleasePoolStmt &ARPS) {
2453 const Stmt *subStmt = ARPS.getSubStmt();
2454 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2455
2456 CGDebugInfo *DI = getDebugInfo();
2457 if (DI) {
2458 DI->setLocation(S.getLBracLoc());
2459 DI->EmitRegionStart(Builder);
2460 }
2461
2462 // Keep track of the current cleanup stack depth.
2463 RunCleanupsScope Scope(*this);
2464 const llvm::Triple Triple = getContext().Target.getTriple();
2465 if (CGM.getLangOptions().ObjCAutoRefCount ||
2466 (CGM.isTargetDarwin() &&
2467 ((Triple.getArch() == llvm::Triple::x86_64 &&
2468 Triple.getDarwinMajorNumber() >= 11)
2469 || (Triple.getEnvironmentName() == "iphoneos" &&
2470 Triple.getDarwinMajorNumber() >= 5)))) {
2471 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2472 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2473 } else {
2474 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2475 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2476 }
2477
2478 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2479 E = S.body_end(); I != E; ++I)
2480 EmitStmt(*I);
2481
2482 if (DI) {
2483 DI->setLocation(S.getRBracLoc());
2484 DI->EmitRegionEnd(Builder);
2485 }
2486}
John McCall0c24c802011-06-24 23:21:27 +00002487
2488/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2489/// make sure it survives garbage collection until this point.
2490void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2491 // We just use an inline assembly.
2492 const llvm::Type *paramTypes[] = { VoidPtrTy };
2493 llvm::FunctionType *extenderType
2494 = llvm::FunctionType::get(VoidTy, paramTypes, /*variadic*/ false);
2495 llvm::Value *extender
2496 = llvm::InlineAsm::get(extenderType,
2497 /* assembly */ "",
2498 /* constraints */ "r",
2499 /* side effects */ true);
2500
2501 object = Builder.CreateBitCast(object, VoidPtrTy);
2502 Builder.CreateCall(extender, object)->setDoesNotThrow();
2503}
2504
Ted Kremenek2979ec72008-04-09 15:51:31 +00002505CGObjCRuntime::~CGObjCRuntime() {}