blob: 6ae1ac8a49c977b99737f519f45aeb433c7fa52c [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000020#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000021#include "clang/Basic/Diagnostic.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000022#include "llvm/ADT/STLExtras.h"
Daniel Dunbara08dff12008-09-24 04:04:31 +000023#include "llvm/Target/TargetData.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000024using namespace clang;
25using namespace CodeGen;
26
Chris Lattnerb1d329d2008-06-24 17:04:18 +000027/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000028llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000029{
David Chisnall481e3a82010-01-23 02:40:42 +000030 llvm::Constant *C =
31 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000032 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000033 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000034}
35
36/// Emit a selector.
37llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
38 // Untyped selector.
39 // Note that this implementation allows for non-constant strings to be passed
40 // as arguments to @selector(). Currently, the only thing preventing this
41 // behaviour is the type checking in the front end.
Daniel Dunbar45858d22010-02-03 20:11:42 +000042 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +000043}
44
Daniel Dunbar66912a12008-08-20 00:28:19 +000045llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
46 // FIXME: This should pass the Decl not the name.
47 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
48}
Chris Lattnerb1d329d2008-06-24 17:04:18 +000049
50
John McCall78a15112010-05-22 01:48:05 +000051RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
52 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +000053 // Only the lookup mechanism and first two arguments of the method
54 // implementation vary between runtimes. We can get the receiver and
55 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +000056
Daniel Dunbar8d480592008-08-11 18:12:00 +000057 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +000058 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +000059 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +000060 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +000061 // Find the receiver
Daniel Dunbarb2197802010-04-22 03:17:06 +000062 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +000063 switch (E->getReceiverKind()) {
64 case ObjCMessageExpr::Instance:
65 Receiver = EmitScalarExpr(E->getInstanceReceiver());
66 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +000067
Douglas Gregor9a129192010-04-21 00:45:42 +000068 case ObjCMessageExpr::Class: {
John McCall3e294922010-05-17 20:12:43 +000069 const ObjCObjectType *ObjTy
70 = E->getClassReceiver()->getAs<ObjCObjectType>();
71 assert(ObjTy && "Invalid Objective-C class message send");
72 OID = ObjTy->getInterface();
73 assert(OID && "Invalid Objective-C class message send");
David Chisnall01aa4672010-04-28 19:33:36 +000074 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +000075 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +000076 break;
77 }
78
79 case ObjCMessageExpr::SuperInstance:
Chris Lattnerb1d329d2008-06-24 17:04:18 +000080 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +000081 isSuperMessage = true;
82 break;
83
84 case ObjCMessageExpr::SuperClass:
85 Receiver = LoadObjCSelf();
86 isSuperMessage = true;
87 isClassMessage = true;
88 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +000089 }
90
Daniel Dunbarc722b852008-08-30 03:02:31 +000091 CallArgList Args;
Anders Carlsson623dcae2009-04-18 20:29:27 +000092 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +000093
Anders Carlsson280e61f12010-06-21 20:59:55 +000094 QualType ResultType =
95 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
96
Chris Lattnerb1d329d2008-06-24 17:04:18 +000097 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +000098 // super is only valid in an Objective-C method
99 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000100 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Anders Carlsson280e61f12010-06-21 20:59:55 +0000101 return Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
Daniel Dunbar4b8c6db2008-08-30 05:35:15 +0000102 E->getSelector(),
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000103 OMD->getClassInterface(),
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000104 isCategoryImpl,
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000105 Receiver,
Daniel Dunbarc722b852008-08-30 03:02:31 +0000106 isClassMessage,
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000107 Args,
108 E->getMethodDecl());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000109 }
Daniel Dunbaraff9fca2009-09-17 04:01:22 +0000110
Anders Carlsson280e61f12010-06-21 20:59:55 +0000111 return Runtime.GenerateMessageSend(*this, Return, ResultType,
John McCall78a15112010-05-22 01:48:05 +0000112 E->getSelector(),
David Chisnall01aa4672010-04-28 19:33:36 +0000113 Receiver, Args, OID,
Fariborz Jahanianf3648b82009-05-05 21:36:57 +0000114 E->getMethodDecl());
Anders Carlsson76f4a902007-08-21 17:43:55 +0000115}
116
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000117/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
118/// the LLVM function and sets the other context used by
119/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000120void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
121 const ObjCContainerDecl *CD) {
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000122 FunctionArgList Args;
Devang Patela2c048e2010-04-05 21:09:15 +0000123 // Check if we should generate debug info for this method.
124 if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
125 DebugInfo = CGM.getDebugInfo();
126
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000127 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000128
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000129 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
130 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000131
Mike Stump11289f42009-09-09 15:08:12 +0000132 Args.push_back(std::make_pair(OMD->getSelfDecl(),
Daniel Dunbarbc915f42008-09-09 23:14:03 +0000133 OMD->getSelfDecl()->getType()));
134 Args.push_back(std::make_pair(OMD->getCmdDecl(),
135 OMD->getCmdDecl()->getType()));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000136
Chris Lattnera4997152009-02-20 18:43:26 +0000137 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
138 E = OMD->param_end(); PI != E; ++PI)
139 Args.push_back(std::make_pair(*PI, (*PI)->getType()));
Chris Lattner5696e7b2008-06-17 18:05:57 +0000140
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000141 CurGD = OMD;
142
Tilmann Scheller454464b2011-03-02 19:36:23 +0000143 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart(),
144 CC_Default);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000145}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000146
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000147void CodeGenFunction::GenerateObjCGetterBody(ObjCIvarDecl *Ivar,
148 bool IsAtomic, bool IsStrong) {
149 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
150 Ivar, 0);
151 llvm::Value *GetCopyStructFn =
152 CGM.getObjCRuntime().GetGetStructFunction();
153 CodeGenTypes &Types = CGM.getTypes();
154 // objc_copyStruct (ReturnValue, &structIvar,
155 // sizeof (Type of Ivar), isAtomic, false);
156 CallArgList Args;
157 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
158 Types.ConvertType(getContext().VoidPtrTy)));
159 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
160 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
161 Types.ConvertType(getContext().VoidPtrTy)));
162 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
163 // sizeof (Type of Ivar)
164 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
165 llvm::Value *SizeVal =
166 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
167 Size.getQuantity());
168 Args.push_back(std::make_pair(RValue::get(SizeVal),
169 getContext().LongTy));
170 llvm::Value *isAtomic =
171 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
172 IsAtomic ? 1 : 0);
173 Args.push_back(std::make_pair(RValue::get(isAtomic),
174 getContext().BoolTy));
175 llvm::Value *hasStrong =
176 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
177 IsStrong ? 1 : 0);
178 Args.push_back(std::make_pair(RValue::get(hasStrong),
179 getContext().BoolTy));
180 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
181 FunctionType::ExtInfo()),
182 GetCopyStructFn, ReturnValueSlot(), Args);
183}
184
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000185/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000186/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000187void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000188 StartObjCMethod(OMD, OMD->getClassInterface());
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000189 EmitStmt(OMD->getBody());
190 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000191}
192
Mike Stump18bb9282009-05-16 07:57:57 +0000193// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
194// AST for the whole body we can just fall back to having a GenerateFunction
195// which takes the body Stmt.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000196
197/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff5a7dd782009-01-10 22:55:25 +0000198/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
199/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000200void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
201 const ObjCPropertyImplDecl *PID) {
Daniel Dunbara08dff12008-09-24 04:04:31 +0000202 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000203 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +0000204 bool IsAtomic =
205 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000206 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
207 assert(OMD && "Invalid call to generate getter (empty method)");
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000208 StartObjCMethod(OMD, IMP->getClassInterface());
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +0000209
Daniel Dunbara08dff12008-09-24 04:04:31 +0000210 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian8e0079c2008-12-08 23:56:17 +0000211 // this. Non-atomic properties are directly evaluated.
212 // atomic 'copy' and 'retain' properties are also directly
213 // evaluated in gc-only mode.
Daniel Dunbara08dff12008-09-24 04:04:31 +0000214 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +0000215 IsAtomic &&
Fariborz Jahanian8e0079c2008-12-08 23:56:17 +0000216 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
217 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump11289f42009-09-09 15:08:12 +0000218 llvm::Value *GetPropertyFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +0000219 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000220
Daniel Dunbara08dff12008-09-24 04:04:31 +0000221 if (!GetPropertyFn) {
222 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
223 FinishFunction();
224 return;
225 }
226
227 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
228 // FIXME: Can't this be simpler? This might even be worse than the
229 // corresponding gcc code.
230 CodeGenTypes &Types = CGM.getTypes();
231 ValueDecl *Cmd = OMD->getCmdDecl();
232 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
233 QualType IdTy = getContext().getObjCIdType();
Mike Stump11289f42009-09-09 15:08:12 +0000234 llvm::Value *SelfAsId =
Daniel Dunbara08dff12008-09-24 04:04:31 +0000235 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000236 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbara08dff12008-09-24 04:04:31 +0000237 llvm::Value *True =
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000238 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbara08dff12008-09-24 04:04:31 +0000239 CallArgList Args;
240 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
241 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
242 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
243 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000244 // FIXME: We shouldn't need to get the function info here, the
245 // runtime already should have computed it to build the function.
John McCallab26cfa2010-02-05 21:31:56 +0000246 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000247 FunctionType::ExtInfo()),
Anders Carlsson61a401c2009-12-24 19:25:24 +0000248 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbara08dff12008-09-24 04:04:31 +0000249 // We need to fix the type here. Ivars with copy & retain are
250 // always objects so we don't need to worry about complex or
251 // aggregates.
Mike Stump11289f42009-09-09 15:08:12 +0000252 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbara08dff12008-09-24 04:04:31 +0000253 Types.ConvertType(PD->getType())));
254 EmitReturnOfRValue(RV, PD->getType());
255 } else {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000256 const llvm::Triple &Triple = getContext().Target.getTriple();
257 QualType IVART = Ivar->getType();
258 if (IsAtomic &&
259 IVART->isScalarType() &&
260 (Triple.getArch() == llvm::Triple::arm ||
261 Triple.getArch() == llvm::Triple::thumb) &&
262 (getContext().getTypeSizeInChars(IVART)
263 > CharUnits::fromQuantity(4)) &&
264 CGM.getObjCRuntime().GetGetStructFunction()) {
265 GenerateObjCGetterBody(Ivar, true, false);
266 }
267 else if (IVART->isAnyComplexType()) {
Fariborz Jahanianb8993382010-05-06 15:45:36 +0000268 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
269 Ivar, 0);
Fariborz Jahanianf9c45852010-03-25 21:56:43 +0000270 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
271 LV.isVolatileQualified());
272 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
273 }
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000274 else if (hasAggregateLLVMType(IVART)) {
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +0000275 bool IsStrong = false;
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000276 if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(IVART)))
Fariborz Jahanian08b0f662010-04-13 00:38:05 +0000277 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall168b80f2010-12-26 22:13:16 +0000278 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000279 GenerateObjCGetterBody(Ivar, IsAtomic, IsStrong);
Fariborz Jahanian08b0f662010-04-13 00:38:05 +0000280 }
Fariborz Jahanianb8993382010-05-06 15:45:36 +0000281 else {
282 if (PID->getGetterCXXConstructor()) {
283 ReturnStmt *Stmt =
284 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor6fd1b182010-05-15 06:01:05 +0000285 PID->getGetterCXXConstructor(),
286 0);
Fariborz Jahanianb8993382010-05-06 15:45:36 +0000287 EmitReturnStmt(*Stmt);
288 }
289 else {
290 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
291 Ivar, 0);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000292 EmitAggregateCopy(ReturnValue, LV.getAddress(), IVART);
Fariborz Jahanianb8993382010-05-06 15:45:36 +0000293 }
294 }
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000295 }
296 else {
297 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
Fariborz Jahanianb8993382010-05-06 15:45:36 +0000298 Ivar, 0);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000299 CodeGenTypes &Types = CGM.getTypes();
300 RValue RV = EmitLoadOfLValue(LV, IVART);
301 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
302 Types.ConvertType(PD->getType())));
303 EmitReturnOfRValue(RV, PD->getType());
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000304 }
Daniel Dunbara08dff12008-09-24 04:04:31 +0000305 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000306
307 FinishFunction();
308}
309
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000310void CodeGenFunction::GenerateObjCAtomicSetterBody(ObjCMethodDecl *OMD,
311 ObjCIvarDecl *Ivar) {
312 // objc_copyStruct (&structIvar, &Arg,
313 // sizeof (struct something), true, false);
314 llvm::Value *GetCopyStructFn =
315 CGM.getObjCRuntime().GetSetStructFunction();
316 CodeGenTypes &Types = CGM.getTypes();
317 CallArgList Args;
318 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
319 RValue RV =
320 RValue::get(Builder.CreateBitCast(LV.getAddress(),
321 Types.ConvertType(getContext().VoidPtrTy)));
322 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
323 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
324 llvm::Value *ArgAsPtrTy =
325 Builder.CreateBitCast(Arg,
326 Types.ConvertType(getContext().VoidPtrTy));
327 RV = RValue::get(ArgAsPtrTy);
328 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
329 // sizeof (Type of Ivar)
330 CharUnits Size = getContext().getTypeSizeInChars(Ivar->getType());
331 llvm::Value *SizeVal =
332 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy),
333 Size.getQuantity());
334 Args.push_back(std::make_pair(RValue::get(SizeVal),
335 getContext().LongTy));
336 llvm::Value *True =
337 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
338 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
339 llvm::Value *False =
340 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
341 Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
342 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
343 FunctionType::ExtInfo()),
344 GetCopyStructFn, ReturnValueSlot(), Args);
345}
346
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000347/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff5a7dd782009-01-10 22:55:25 +0000348/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
349/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000350void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
351 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000352 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000353 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
354 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
355 assert(OMD && "Invalid call to generate setter (empty method)");
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000356 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000357
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000358 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump11289f42009-09-09 15:08:12 +0000359 bool IsAtomic =
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000360 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
361
362 // Determine if we should use an objc_setProperty call for
363 // this. Properties with 'copy' semantics always use it, as do
364 // non-atomic properties with 'release' semantics as long as we are
365 // not in gc-only mode.
366 if (IsCopy ||
367 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
368 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump11289f42009-09-09 15:08:12 +0000369 llvm::Value *SetPropertyFn =
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000370 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000371
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000372 if (!SetPropertyFn) {
373 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
374 FinishFunction();
375 return;
376 }
Mike Stump11289f42009-09-09 15:08:12 +0000377
378 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000379 // <is-atomic>, <is-copy>).
380 // FIXME: Can't this be simpler? This might even be worse than the
381 // corresponding gcc code.
382 CodeGenTypes &Types = CGM.getTypes();
383 ValueDecl *Cmd = OMD->getCmdDecl();
384 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
385 QualType IdTy = getContext().getObjCIdType();
Mike Stump11289f42009-09-09 15:08:12 +0000386 llvm::Value *SelfAsId =
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000387 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000388 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattnera4997152009-02-20 18:43:26 +0000389 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump11289f42009-09-09 15:08:12 +0000390 llvm::Value *ArgAsId =
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000391 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
392 Types.ConvertType(IdTy));
393 llvm::Value *True =
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000394 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000395 llvm::Value *False =
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000396 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000397 CallArgList Args;
398 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
399 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
400 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
401 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
Mike Stump11289f42009-09-09 15:08:12 +0000402 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000403 getContext().BoolTy));
Mike Stump11289f42009-09-09 15:08:12 +0000404 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000405 getContext().BoolTy));
Mike Stump18bb9282009-05-16 07:57:57 +0000406 // FIXME: We shouldn't need to get the function info here, the runtime
407 // already should have computed it to build the function.
John McCallab26cfa2010-02-05 21:31:56 +0000408 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000409 FunctionType::ExtInfo()),
410 SetPropertyFn,
Anders Carlsson61a401c2009-12-24 19:25:24 +0000411 ReturnValueSlot(), Args);
Fariborz Jahanian08b0f662010-04-13 00:38:05 +0000412 } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
413 !Ivar->getType()->isAnyComplexType() &&
414 IndirectObjCSetterArg(*CurFnInfo)
David Chisnall168b80f2010-12-26 22:13:16 +0000415 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian08b0f662010-04-13 00:38:05 +0000416 // objc_copyStruct (&structIvar, &Arg,
417 // sizeof (struct something), true, false);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000418 GenerateObjCAtomicSetterBody(OMD, Ivar);
Fariborz Jahanianb8993382010-05-06 15:45:36 +0000419 } else if (PID->getSetterCXXAssignment()) {
John McCalla2342eb2010-12-05 02:00:02 +0000420 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000421 } else {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000422 const llvm::Triple &Triple = getContext().Target.getTriple();
423 QualType IVART = Ivar->getType();
424 if (IsAtomic &&
425 IVART->isScalarType() &&
426 (Triple.getArch() == llvm::Triple::arm ||
427 Triple.getArch() == llvm::Triple::thumb) &&
428 (getContext().getTypeSizeInChars(IVART)
429 > CharUnits::fromQuantity(4)) &&
430 CGM.getObjCRuntime().GetGetStructFunction()) {
431 GenerateObjCAtomicSetterBody(OMD, Ivar);
432 }
433 else {
434 // FIXME: Find a clean way to avoid AST node creation.
435 SourceLocation Loc = PD->getLocation();
436 ValueDecl *Self = OMD->getSelfDecl();
437 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
438 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
439 ParmVarDecl *ArgDecl = *OMD->param_begin();
440 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
441 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
Daniel Dunbarc14753b2009-10-27 19:21:30 +0000442
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000443 // The property type can differ from the ivar type in some situations with
444 // Objective-C pointer types, we can always bit cast the RHS in these cases.
445 if (getContext().getCanonicalType(Ivar->getType()) !=
446 getContext().getCanonicalType(ArgDecl->getType())) {
447 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
448 Ivar->getType(), CK_BitCast, &Arg,
449 VK_RValue);
450 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
451 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
452 EmitStmt(&Assign);
453 } else {
454 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
455 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
456 EmitStmt(&Assign);
457 }
Daniel Dunbarc14753b2009-10-27 19:21:30 +0000458 }
Daniel Dunbar5449ce52008-09-24 06:32:09 +0000459 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000460
461 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +0000462}
463
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000464void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
465 ObjCMethodDecl *MD,
466 bool ctor) {
Alexis Hunt1d792652011-01-08 20:30:50 +0000467 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000468 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
469 StartObjCMethod(MD, IMP->getClassInterface());
470 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
471 E = IMP->init_end(); B != E; ++B) {
Alexis Hunt1d792652011-01-08 20:30:50 +0000472 CXXCtorInitializer *Member = (*B);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000473 IvarInitializers.push_back(Member);
474 }
475 if (ctor) {
476 for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) {
Alexis Hunt1d792652011-01-08 20:30:50 +0000477 CXXCtorInitializer *IvarInit = IvarInitializers[I];
Francois Pichetd583da02010-12-04 09:14:42 +0000478 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000479 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +0000480 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
481 LoadObjCSelf(), Ivar, 0);
John McCall7a626f62010-09-15 10:14:12 +0000482 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000483 }
484 // constructor returns 'self'.
485 CodeGenTypes &Types = CGM.getTypes();
486 QualType IdTy(CGM.getContext().getObjCIdType());
487 llvm::Value *SelfAsId =
488 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
489 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
Chandler Carruthf3983652010-05-06 00:20:39 +0000490 } else {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000491 // dtor
492 for (size_t i = IvarInitializers.size(); i > 0; --i) {
Francois Pichetd583da02010-12-04 09:14:42 +0000493 FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000494 QualType FieldType = Field->getType();
Fariborz Jahanian499b9022010-04-28 22:30:33 +0000495 const ConstantArrayType *Array =
496 getContext().getAsConstantArrayType(FieldType);
497 if (Array)
498 FieldType = getContext().getBaseElementType(FieldType);
499
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000500 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
501 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
502 LoadObjCSelf(), Ivar, 0);
503 const RecordType *RT = FieldType->getAs<RecordType>();
504 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Douglas Gregorbac74902010-07-01 14:13:13 +0000505 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor();
Chandler Carruthf3983652010-05-06 00:20:39 +0000506 if (!Dtor->isTrivial()) {
Fariborz Jahanian60c7e162010-05-04 19:29:32 +0000507 if (Array) {
508 const llvm::Type *BasePtr = ConvertType(FieldType);
509 BasePtr = llvm::PointerType::getUnqual(BasePtr);
510 llvm::Value *BaseAddrPtr =
511 Builder.CreateBitCast(LV.getAddress(), BasePtr);
512 EmitCXXAggrDestructorCall(Dtor,
513 Array, BaseAddrPtr);
Chandler Carruthf3983652010-05-06 00:20:39 +0000514 } else {
Fariborz Jahanian60c7e162010-05-04 19:29:32 +0000515 EmitCXXDestructorCall(Dtor,
516 Dtor_Complete, /*ForVirtualBase=*/false,
517 LV.getAddress());
Chandler Carruthf3983652010-05-06 00:20:39 +0000518 }
519 }
520 }
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +0000521 }
522 FinishFunction();
523}
524
Fariborz Jahanian08b0f662010-04-13 00:38:05 +0000525bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
526 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
527 it++; it++;
528 const ABIArgInfo &AI = it->info;
529 // FIXME. Is this sufficient check?
530 return (AI.getKind() == ABIArgInfo::Indirect);
531}
532
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +0000533bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
534 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
535 return false;
536 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
537 return FDTTy->getDecl()->hasObjectMember();
538 return false;
539}
540
Daniel Dunbara08dff12008-09-24 04:04:31 +0000541llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000542 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
543 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner5696e7b2008-06-17 18:05:57 +0000544}
545
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +0000546QualType CodeGenFunction::TypeOfSelfObject() {
547 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
548 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000549 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
550 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +0000551 return PTy->getPointeeType();
552}
553
John McCall0692a322010-12-04 03:11:00 +0000554LValue
555CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
556 // This is a special l-value that just issues sends when we load or
557 // store through it.
558
559 // For certain base kinds, we need to emit the base immediately.
560 llvm::Value *Base;
561 if (E->isSuperReceiver())
562 Base = LoadObjCSelf();
563 else if (E->isClassReceiver())
564 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
565 else
566 Base = EmitScalarExpr(E->getBase());
567 return LValue::MakePropertyRef(E, Base);
568}
569
570static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
571 ReturnValueSlot Return,
572 QualType ResultType,
573 Selector S,
574 llvm::Value *Receiver,
575 const CallArgList &CallArgs) {
576 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanian391d4fc2009-03-20 19:18:21 +0000577 bool isClassMessage = OMD->isClassMethod();
578 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCall0692a322010-12-04 03:11:00 +0000579 return CGF.CGM.getObjCRuntime()
580 .GenerateMessageSendSuper(CGF, Return, ResultType,
581 S, OMD->getClassInterface(),
582 isCategoryImpl, Receiver,
583 isClassMessage, CallArgs);
Fariborz Jahanian391d4fc2009-03-20 19:18:21 +0000584}
585
John McCallf3eb96f2010-12-04 02:32:38 +0000586RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
587 ReturnValueSlot Return) {
588 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000589 QualType ResultType;
590 Selector S;
591 if (E->isExplicitProperty()) {
592 const ObjCPropertyDecl *Property = E->getExplicitProperty();
593 S = Property->getGetterName();
594 ResultType = E->getType();
Mike Stump658fe022009-07-30 22:28:39 +0000595 } else {
John McCallb7bd14f2010-12-02 01:19:52 +0000596 const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
597 S = Getter->getSelector();
598 ResultType = Getter->getResultType(); // with reference!
Fariborz Jahanian9ac53512008-11-22 22:30:21 +0000599 }
John McCallb7bd14f2010-12-02 01:19:52 +0000600
John McCallf3eb96f2010-12-04 02:32:38 +0000601 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCall0692a322010-12-04 03:11:00 +0000602
603 // Accesses to 'super' follow a different code path.
604 if (E->isSuperReceiver())
605 return GenerateMessageSendSuper(*this, Return, ResultType,
606 S, Receiver, CallArgList());
607
John McCallf3eb96f2010-12-04 02:32:38 +0000608 const ObjCInterfaceDecl *ReceiverClass
609 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCallb7bd14f2010-12-02 01:19:52 +0000610 return CGM.getObjCRuntime().
611 GenerateMessageSend(*this, Return, ResultType, S,
612 Receiver, CallArgList(), ReceiverClass);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000613}
614
John McCallf3eb96f2010-12-04 02:32:38 +0000615void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
616 LValue Dst) {
617 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCallb7bd14f2010-12-02 01:19:52 +0000618 Selector S = E->getSetterSelector();
619 QualType ArgType;
620 if (E->isImplicitProperty()) {
621 const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
622 ObjCMethodDecl::param_iterator P = Setter->param_begin();
623 ArgType = (*P)->getType();
624 } else {
625 ArgType = E->getType();
626 }
Fariborz Jahanian701f0942011-02-08 22:33:23 +0000627 // FIXME. Other than scalars, AST is not adequate for setter and
628 // getter type mismatches which require conversion.
629 if (Src.isScalar()) {
630 llvm::Value *SrcVal = Src.getScalarVal();
631 QualType DstType = getContext().getCanonicalType(ArgType);
632 const llvm::Type *DstTy = ConvertType(DstType);
633 if (SrcVal->getType() != DstTy)
634 Src =
635 RValue::get(EmitScalarConversion(SrcVal, E->getType(), DstType));
636 }
637
John McCall0692a322010-12-04 03:11:00 +0000638 CallArgList Args;
639 Args.push_back(std::make_pair(Src, ArgType));
640
641 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
642 QualType ResultType = getContext().VoidTy;
643
John McCallb7bd14f2010-12-02 01:19:52 +0000644 if (E->isSuperReceiver()) {
John McCall0692a322010-12-04 03:11:00 +0000645 GenerateMessageSendSuper(*this, ReturnValueSlot(),
646 ResultType, S, Receiver, Args);
John McCallb7bd14f2010-12-02 01:19:52 +0000647 return;
648 }
649
John McCallf3eb96f2010-12-04 02:32:38 +0000650 const ObjCInterfaceDecl *ReceiverClass
651 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCallb7bd14f2010-12-02 01:19:52 +0000652
John McCallb7bd14f2010-12-02 01:19:52 +0000653 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCall0692a322010-12-04 03:11:00 +0000654 ResultType, S, Receiver, Args,
655 ReceiverClass);
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +0000656}
657
Chris Lattnerd4808922009-03-22 21:03:39 +0000658void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +0000659 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +0000660 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +0000661
Daniel Dunbara08dff12008-09-24 04:04:31 +0000662 if (!EnumerationMutationFn) {
663 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
664 return;
665 }
666
John McCall9e2e22f2011-02-22 07:16:58 +0000667 // The local variable comes into scope immediately.
668 AutoVarEmission variable = AutoVarEmission::invalid();
669 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
670 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
671
Devang Pateld2d66652011-01-19 01:36:36 +0000672 CGDebugInfo *DI = getDebugInfo();
673 if (DI) {
674 DI->setLocation(S.getSourceRange().getBegin());
675 DI->EmitRegionStart(Builder);
676 }
677
John McCall1c926b72011-01-07 01:49:06 +0000678 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
679 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump11289f42009-09-09 15:08:12 +0000680
Anders Carlsson75658592008-08-31 02:33:12 +0000681 // Fast enumeration state.
682 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +0000683 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +0000684 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +0000685
Anders Carlsson75658592008-08-31 02:33:12 +0000686 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +0000687 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +0000688
John McCall1c926b72011-01-07 01:49:06 +0000689 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +0000690 IdentifierInfo *II[] = {
691 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
692 &CGM.getContext().Idents.get("objects"),
693 &CGM.getContext().Idents.get("count")
694 };
695 Selector FastEnumSel =
696 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +0000697
698 QualType ItemsTy =
699 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +0000700 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +0000701 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000702 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +0000703
John McCall1c926b72011-01-07 01:49:06 +0000704 // Emit the collection pointer.
Anders Carlsson75658592008-08-31 02:33:12 +0000705 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump11289f42009-09-09 15:08:12 +0000706
John McCall1c926b72011-01-07 01:49:06 +0000707 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +0000708 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +0000709
710 // The first argument is a temporary of the enumeration-state type.
Mike Stump11289f42009-09-09 15:08:12 +0000711 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlsson75658592008-08-31 02:33:12 +0000712 getContext().getPointerType(StateTy)));
Mike Stump11289f42009-09-09 15:08:12 +0000713
John McCall1c926b72011-01-07 01:49:06 +0000714 // The second argument is a temporary array with space for NumItems
715 // pointers. We'll actually be loading elements from the array
716 // pointer written into the control state; this buffer is so that
717 // collections that *aren't* backed by arrays can still queue up
718 // batches of elements.
Mike Stump11289f42009-09-09 15:08:12 +0000719 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlsson75658592008-08-31 02:33:12 +0000720 getContext().getPointerType(ItemsTy)));
Mike Stump11289f42009-09-09 15:08:12 +0000721
John McCall1c926b72011-01-07 01:49:06 +0000722 // The third argument is the capacity of that temporary array.
Anders Carlsson75658592008-08-31 02:33:12 +0000723 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000724 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Mike Stump11289f42009-09-09 15:08:12 +0000725 Args.push_back(std::make_pair(RValue::get(Count),
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000726 getContext().UnsignedLongTy));
Mike Stump11289f42009-09-09 15:08:12 +0000727
John McCall1c926b72011-01-07 01:49:06 +0000728 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +0000729 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +0000730 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +0000731 getContext().UnsignedLongTy,
732 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +0000733 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +0000734
John McCall1c926b72011-01-07 01:49:06 +0000735 // The initial number of objects that were returned in the buffer.
736 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +0000737
John McCall1c926b72011-01-07 01:49:06 +0000738 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
739 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +0000740
John McCall1c926b72011-01-07 01:49:06 +0000741 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +0000742
John McCall1c926b72011-01-07 01:49:06 +0000743 // If the limit pointer was zero to begin with, the collection is
744 // empty; skip all this.
745 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
746 EmptyBB, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +0000747
John McCall1c926b72011-01-07 01:49:06 +0000748 // Otherwise, initialize the loop.
749 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +0000750
John McCall1c926b72011-01-07 01:49:06 +0000751 // Save the initial mutations value. This is the value at an
752 // address that was written into the state object by
753 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +0000754 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +0000755 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +0000756 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +0000757 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +0000758
John McCall1c926b72011-01-07 01:49:06 +0000759 llvm::Value *initialMutations =
760 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +0000761
John McCall1c926b72011-01-07 01:49:06 +0000762 // Start looping. This is the point we return to whenever we have a
763 // fresh, non-empty batch of objects.
764 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
765 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +0000766
John McCall1c926b72011-01-07 01:49:06 +0000767 // The current index into the buffer.
768 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
769 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +0000770
John McCall1c926b72011-01-07 01:49:06 +0000771 // The current buffer size.
772 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
773 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +0000774
John McCall1c926b72011-01-07 01:49:06 +0000775 // Check whether the mutations value has changed from where it was
776 // at start. StateMutationsPtr should actually be invariant between
777 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +0000778 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +0000779 llvm::Value *currentMutations
780 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +0000781
John McCall1c926b72011-01-07 01:49:06 +0000782 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
783 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +0000784
John McCall1c926b72011-01-07 01:49:06 +0000785 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
786 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +0000787
John McCall1c926b72011-01-07 01:49:06 +0000788 // If so, call the enumeration-mutation function.
789 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +0000790 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +0000791 Builder.CreateBitCast(Collection,
Anders Carlsson3f35a262008-08-31 04:05:03 +0000792 ConvertType(getContext().getObjCIdType()),
793 "tmp");
Daniel Dunbar84388bf2009-02-03 23:55:40 +0000794 CallArgList Args2;
Mike Stump11289f42009-09-09 15:08:12 +0000795 Args2.push_back(std::make_pair(RValue::get(V),
Daniel Dunbar84388bf2009-02-03 23:55:40 +0000796 getContext().getObjCIdType()));
Mike Stump18bb9282009-05-16 07:57:57 +0000797 // FIXME: We shouldn't need to get the function info here, the runtime already
798 // should have computed it to build the function.
John McCallab26cfa2010-02-05 21:31:56 +0000799 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindolac50c27c2010-03-30 20:24:48 +0000800 FunctionType::ExtInfo()),
Anders Carlsson61a401c2009-12-24 19:25:24 +0000801 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +0000802
John McCall1c926b72011-01-07 01:49:06 +0000803 // Otherwise, or if the mutation function returns, just continue.
804 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +0000805
John McCall1c926b72011-01-07 01:49:06 +0000806 // Initialize the element variable.
807 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +0000808 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +0000809 LValue elementLValue;
810 QualType elementType;
811 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +0000812 // Initialize the variable, in case it's a __block variable or something.
813 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +0000814
John McCall9e2e22f2011-02-22 07:16:58 +0000815 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall1c926b72011-01-07 01:49:06 +0000816 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
817 VK_LValue, SourceLocation());
818 elementLValue = EmitLValue(&tempDRE);
819 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +0000820 elementIsVariable = true;
John McCall1c926b72011-01-07 01:49:06 +0000821 } else {
822 elementLValue = LValue(); // suppress warning
823 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +0000824 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +0000825 }
826 const llvm::Type *convertedElementType = ConvertType(elementType);
827
828 // Fetch the buffer out of the enumeration state.
829 // TODO: this pointer should actually be invariant between
830 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +0000831 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +0000832 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +0000833 llvm::Value *EnumStateItems =
834 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +0000835
John McCall1c926b72011-01-07 01:49:06 +0000836 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +0000837 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +0000838 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
839 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000840
John McCall1c926b72011-01-07 01:49:06 +0000841 // Cast that value to the right type.
842 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
843 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +0000844
John McCall1c926b72011-01-07 01:49:06 +0000845 // Make sure we have an l-value. Yes, this gets evaluated every
846 // time through the loop.
John McCall9e2e22f2011-02-22 07:16:58 +0000847 if (!elementIsVariable)
John McCall1c926b72011-01-07 01:49:06 +0000848 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
Mike Stump11289f42009-09-09 15:08:12 +0000849
John McCall1c926b72011-01-07 01:49:06 +0000850 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
Mike Stump11289f42009-09-09 15:08:12 +0000851
John McCall9e2e22f2011-02-22 07:16:58 +0000852 // If we do have an element variable, this assignment is the end of
853 // its initialization.
854 if (elementIsVariable)
855 EmitAutoVarCleanups(variable);
856
John McCall1c926b72011-01-07 01:49:06 +0000857 // Perform the loop body, setting up break and continue labels.
Anders Carlsson33747b62009-02-10 05:52:02 +0000858 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +0000859 {
860 RunCleanupsScope Scope(*this);
861 EmitStmt(S.getBody());
862 }
Anders Carlsson75658592008-08-31 02:33:12 +0000863 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +0000864
John McCall1c926b72011-01-07 01:49:06 +0000865 // Destroy the element variable now.
866 elementVariableScope.ForceCleanup();
867
868 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +0000869 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +0000870
John McCall1c926b72011-01-07 01:49:06 +0000871 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +0000872
John McCall1c926b72011-01-07 01:49:06 +0000873 // First we check in the local buffer.
874 llvm::Value *indexPlusOne
875 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +0000876
John McCall1c926b72011-01-07 01:49:06 +0000877 // If we haven't overrun the buffer yet, we can continue.
878 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
879 LoopBodyBB, FetchMoreBB);
880
881 index->addIncoming(indexPlusOne, AfterBody.getBlock());
882 count->addIncoming(count, AfterBody.getBlock());
883
884 // Otherwise, we have to fetch more elements.
885 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +0000886
887 CountRV =
John McCall78a15112010-05-22 01:48:05 +0000888 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +0000889 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +0000890 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +0000891 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +0000892
John McCall1c926b72011-01-07 01:49:06 +0000893 // If we got a zero count, we're done.
894 llvm::Value *refetchCount = CountRV.getScalarVal();
895
896 // (note that the message send might split FetchMoreBB)
897 index->addIncoming(zero, Builder.GetInsertBlock());
898 count->addIncoming(refetchCount, Builder.GetInsertBlock());
899
900 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
901 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +0000902
Anders Carlsson75658592008-08-31 02:33:12 +0000903 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +0000904 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +0000905
John McCall9e2e22f2011-02-22 07:16:58 +0000906 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +0000907 // If the element was not a declaration, set it to be null.
908
John McCall1c926b72011-01-07 01:49:06 +0000909 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
910 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
911 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
Anders Carlsson75658592008-08-31 02:33:12 +0000912 }
913
Devang Pateld2d66652011-01-19 01:36:36 +0000914 if (DI) {
915 DI->setLocation(S.getSourceRange().getEnd());
916 DI->EmitRegionEnd(Builder);
917 }
918
John McCallad5d61e2010-07-23 21:56:41 +0000919 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +0000920}
921
Mike Stump11289f42009-09-09 15:08:12 +0000922void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +0000923 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000924}
925
Mike Stump11289f42009-09-09 15:08:12 +0000926void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +0000927 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
928}
929
Chris Lattnere132e242008-11-15 21:26:17 +0000930void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +0000931 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +0000932 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +0000933}
934
Ted Kremenek43e06332008-04-09 15:51:31 +0000935CGObjCRuntime::~CGObjCRuntime() {}