blob: 845d5ff00ccec4f5557df61caf797b3809d0d3ed [file] [log] [blame]
Anders Carlssona66cad42007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Carlssona66cad42007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekfa4ebab2008-04-09 15:51:31 +000014#include "CGObjCRuntime.h"
Anders Carlssona66cad42007-08-21 17:43:55 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Daniel Dunbare6c31752008-08-29 08:11:39 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbarcc37ac52008-09-03 00:27:26 +000019#include "clang/Basic/Diagnostic.h"
Anders Carlsson82b0d0c2008-08-30 19:51:14 +000020#include "llvm/ADT/STLExtras.h"
Daniel Dunbard82223f2008-09-24 04:04:31 +000021#include "llvm/Target/TargetData.h"
Chris Lattner8c7c6a12008-06-17 18:05:57 +000022
Anders Carlssona66cad42007-08-21 17:43:55 +000023using namespace clang;
24using namespace CodeGen;
25
Chris Lattner6ee20e32008-06-24 17:04:18 +000026/// Emits an instance of NSConstantString representing the object.
Daniel Dunbard76c2ff2008-11-25 21:53:21 +000027llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
28{
29 std::string String(E->getString()->getStrData(),
30 E->getString()->getByteLength());
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000031 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(String);
Daniel Dunbarf1f7f192008-08-20 00:28:19 +000032 // FIXME: This bitcast should just be made an invariant on the Runtime.
Daniel Dunbardaf4ad42008-08-12 00:12:39 +000033 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner6ee20e32008-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 Dunbarfc69bde2008-08-11 18:12:00 +000042 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner6ee20e32008-06-24 17:04:18 +000043}
44
Daniel Dunbarf1f7f192008-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 Lattner6ee20e32008-06-24 17:04:18 +000049
50
Daniel Dunbara04840b2008-08-23 03:46:30 +000051RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
Chris Lattner6ee20e32008-06-24 17:04:18 +000052 // Only the lookup mechanism and first two arguments of the method
53 // implementation vary between runtimes. We can get the receiver and
54 // arguments in generic code.
55
Daniel Dunbarfc69bde2008-08-11 18:12:00 +000056 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner6ee20e32008-06-24 17:04:18 +000057 const Expr *ReceiverExpr = E->getReceiver();
58 bool isSuperMessage = false;
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +000059 bool isClassMessage = false;
Chris Lattner6ee20e32008-06-24 17:04:18 +000060 // Find the receiver
61 llvm::Value *Receiver;
62 if (!ReceiverExpr) {
Daniel Dunbar434627a2008-08-16 00:25:02 +000063 const ObjCInterfaceDecl *OID = E->getClassInfo().first;
64
65 // Very special case, super send in class method. The receiver is
66 // self (the class object) and the send uses super semantics.
67 if (!OID) {
Chris Lattner05fb7c82008-11-20 04:42:34 +000068 assert(E->getClassName()->isStr("super") &&
Daniel Dunbar434627a2008-08-16 00:25:02 +000069 "Unexpected missing class interface in message send.");
Daniel Dunbar434627a2008-08-16 00:25:02 +000070 isSuperMessage = true;
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +000071 Receiver = LoadObjCSelf();
72 } else {
73 Receiver = Runtime.GetClass(Builder, OID);
Chris Lattner6ee20e32008-06-24 17:04:18 +000074 }
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +000075
76 isClassMessage = true;
Douglas Gregord8606632008-11-04 14:56:14 +000077 } else if (isa<ObjCSuperExpr>(E->getReceiver())) {
Chris Lattner6ee20e32008-06-24 17:04:18 +000078 isSuperMessage = true;
79 Receiver = LoadObjCSelf();
80 } else {
Daniel Dunbar6fa3daf2008-08-12 05:28:47 +000081 Receiver = EmitScalarExpr(E->getReceiver());
Chris Lattner6ee20e32008-06-24 17:04:18 +000082 }
83
Daniel Dunbar0ed60b02008-08-30 03:02:31 +000084 CallArgList Args;
85 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
86 i != e; ++i)
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +000087 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i), (*i)->getType()));
Daniel Dunbar0ed60b02008-08-30 03:02:31 +000088
Chris Lattner6ee20e32008-06-24 17:04:18 +000089 if (isSuperMessage) {
Chris Lattner8384c142008-06-26 04:42:20 +000090 // super is only valid in an Objective-C method
91 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Daniel Dunbardd851282008-08-30 05:35:15 +000092 return Runtime.GenerateMessageSendSuper(*this, E->getType(),
93 E->getSelector(),
Daniel Dunbarb1ee5d62008-08-25 08:19:24 +000094 OMD->getClassInterface(),
95 Receiver,
Daniel Dunbar0ed60b02008-08-30 03:02:31 +000096 isClassMessage,
97 Args);
Chris Lattner6ee20e32008-06-24 17:04:18 +000098 }
Daniel Dunbardd851282008-08-30 05:35:15 +000099 return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
100 Receiver, isClassMessage, Args);
Anders Carlssona66cad42007-08-21 17:43:55 +0000101}
102
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000103/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
104/// the LLVM function and sets the other context used by
105/// CodeGenFunction.
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000106void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbar96816832008-09-09 23:14:03 +0000107 FunctionArgList Args;
108 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD);
Daniel Dunbarf2787002008-09-04 23:41:35 +0000109
Daniel Dunbar96816832008-09-09 23:14:03 +0000110 CGM.SetMethodAttributes(OMD, Fn);
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000111
Daniel Dunbar96816832008-09-09 23:14:03 +0000112 Args.push_back(std::make_pair(OMD->getSelfDecl(),
113 OMD->getSelfDecl()->getType()));
114 Args.push_back(std::make_pair(OMD->getCmdDecl(),
115 OMD->getCmdDecl()->getType()));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000116
Daniel Dunbar96816832008-09-09 23:14:03 +0000117 for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i) {
118 ParmVarDecl *IPD = OMD->getParamDecl(i);
119 Args.push_back(std::make_pair(IPD, IPD->getType()));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000120 }
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000121
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000122 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocEnd());
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000123}
Daniel Dunbarace33292008-08-16 03:19:19 +0000124
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000125/// Generate an Objective-C method. An Objective-C method is a C function with
126/// its pointer, name, and types registered in the class struture.
127void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
128 StartObjCMethod(OMD);
129 EmitStmt(OMD->getBody());
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000130 FinishFunction(cast<CompoundStmt>(OMD->getBody())->getRBracLoc());
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000131}
132
133// FIXME: I wasn't sure about the synthesis approach. If we end up
134// generating an AST for the whole body we can just fall back to
135// having a GenerateFunction which takes the body Stmt.
136
137/// GenerateObjCGetter - Generate an Objective-C property getter
138/// function. The given Decl must be either an ObjCCategoryImplDecl
139/// or an ObjCImplementationDecl.
140void CodeGenFunction::GenerateObjCGetter(const ObjCPropertyImplDecl *PID) {
Daniel Dunbard82223f2008-09-24 04:04:31 +0000141 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000142 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
143 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
144 assert(OMD && "Invalid call to generate getter (empty method)");
145 // FIXME: This is rather murky, we create this here since they will
146 // not have been created by Sema for us.
147 OMD->createImplicitParams(getContext());
148 StartObjCMethod(OMD);
149
Daniel Dunbard82223f2008-09-24 04:04:31 +0000150 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian32849782008-12-08 23:56:17 +0000151 // this. Non-atomic properties are directly evaluated.
152 // atomic 'copy' and 'retain' properties are also directly
153 // evaluated in gc-only mode.
Daniel Dunbard82223f2008-09-24 04:04:31 +0000154 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian32849782008-12-08 23:56:17 +0000155 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
156 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
157 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Daniel Dunbard82223f2008-09-24 04:04:31 +0000158 llvm::Value *GetPropertyFn =
159 CGM.getObjCRuntime().GetPropertyGetFunction();
160
161 if (!GetPropertyFn) {
162 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
163 FinishFunction();
164 return;
165 }
166
167 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
168 // FIXME: Can't this be simpler? This might even be worse than the
169 // corresponding gcc code.
170 CodeGenTypes &Types = CGM.getTypes();
171 ValueDecl *Cmd = OMD->getCmdDecl();
172 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
173 QualType IdTy = getContext().getObjCIdType();
174 llvm::Value *SelfAsId =
175 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
176 llvm::Value *Offset = EmitIvarOffset(OMD->getClassInterface(), Ivar);
177 llvm::Value *True =
178 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
179 CallArgList Args;
180 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
181 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
182 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
183 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
184 RValue RV = EmitCall(GetPropertyFn, PD->getType(), Args);
185 // We need to fix the type here. Ivars with copy & retain are
186 // always objects so we don't need to worry about complex or
187 // aggregates.
188 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
189 Types.ConvertType(PD->getType())));
190 EmitReturnOfRValue(RV, PD->getType());
191 } else {
Fariborz Jahaniand70b09c2008-11-26 22:36:09 +0000192 LValue LV = EmitLValueForIvar(LoadObjCSelf(), Ivar, 0);
193 if (hasAggregateLLVMType(Ivar->getType())) {
194 EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType());
195 }
196 else
197 EmitReturnOfRValue(EmitLoadOfLValue(LV, Ivar->getType()),
198 PD->getType());
Daniel Dunbard82223f2008-09-24 04:04:31 +0000199 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000200
201 FinishFunction();
202}
203
204/// GenerateObjCSetter - Generate an Objective-C property setter
205/// function. The given Decl must be either an ObjCCategoryImplDecl
206/// or an ObjCImplementationDecl.
207void CodeGenFunction::GenerateObjCSetter(const ObjCPropertyImplDecl *PID) {
Daniel Dunbarf7f6c7b2008-09-24 06:32:09 +0000208 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000209 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
210 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
211 assert(OMD && "Invalid call to generate setter (empty method)");
212 // FIXME: This is rather murky, we create this here since they will
213 // not have been created by Sema for us.
214 OMD->createImplicitParams(getContext());
215 StartObjCMethod(OMD);
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000216
Daniel Dunbarf7f6c7b2008-09-24 06:32:09 +0000217 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
218 bool IsAtomic =
219 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
220
221 // Determine if we should use an objc_setProperty call for
222 // this. Properties with 'copy' semantics always use it, as do
223 // non-atomic properties with 'release' semantics as long as we are
224 // not in gc-only mode.
225 if (IsCopy ||
226 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
227 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
228 llvm::Value *SetPropertyFn =
229 CGM.getObjCRuntime().GetPropertySetFunction();
230
231 if (!SetPropertyFn) {
232 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
233 FinishFunction();
234 return;
235 }
236
237 // Emit objc_setProperty((id) self, _cmd, offset, arg,
238 // <is-atomic>, <is-copy>).
239 // FIXME: Can't this be simpler? This might even be worse than the
240 // corresponding gcc code.
241 CodeGenTypes &Types = CGM.getTypes();
242 ValueDecl *Cmd = OMD->getCmdDecl();
243 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
244 QualType IdTy = getContext().getObjCIdType();
245 llvm::Value *SelfAsId =
246 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
247 llvm::Value *Offset = EmitIvarOffset(OMD->getClassInterface(), Ivar);
248 llvm::Value *Arg = LocalDeclMap[OMD->getParamDecl(0)];
249 llvm::Value *ArgAsId =
250 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
251 Types.ConvertType(IdTy));
252 llvm::Value *True =
253 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
254 llvm::Value *False =
255 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 0);
256 CallArgList Args;
257 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
258 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
259 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
260 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
261 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
262 getContext().BoolTy));
263 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
264 getContext().BoolTy));
265 EmitCall(SetPropertyFn, PD->getType(), Args);
266 } else {
267 SourceLocation Loc = PD->getLocation();
268 ValueDecl *Self = OMD->getSelfDecl();
269 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
270 DeclRefExpr Base(Self, Self->getType(), Loc);
271 ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
272 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
273 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
274 true, true);
275 BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
276 Ivar->getType(), Loc);
277 EmitStmt(&Assign);
278 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000279
280 FinishFunction();
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000281}
282
Daniel Dunbard82223f2008-09-24 04:04:31 +0000283llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarace33292008-08-16 03:19:19 +0000284 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
285 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000286}
287
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +0000288RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) {
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000289 // FIXME: Split it into two separate routines.
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +0000290 if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
291 Selector S = E->getProperty()->getGetterName();
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +0000292 return CGM.getObjCRuntime().
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000293 GenerateMessageSend(*this, Exp->getType(), S,
294 EmitScalarExpr(E->getBase()),
295 false, CallArgList());
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +0000296 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000297 else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
298 Selector S = E->getGetterMethod()->getSelector();
299 return CGM.getObjCRuntime().
300 GenerateMessageSend(*this, Exp->getType(), S,
301 EmitScalarExpr(E->getBase()),
302 false, CallArgList());
303 }
304 else
305 assert (0 && "bad expression node in EmitObjCPropertyGet");
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000306}
307
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000308void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp,
Daniel Dunbare6c31752008-08-29 08:11:39 +0000309 RValue Src) {
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000310 // FIXME: Split it into two separate routines.
311 if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
312 Selector S = E->getProperty()->getSetterName();
313 CallArgList Args;
314 Args.push_back(std::make_pair(Src, E->getType()));
315 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
316 EmitScalarExpr(E->getBase()),
317 false, Args);
318 }
319 else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
320 Selector S = E->getSetterMethod()->getSelector();
321 CallArgList Args;
322 Args.push_back(std::make_pair(Src, E->getType()));
323 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
324 EmitScalarExpr(E->getBase()),
325 false, Args);
326 }
327 else
328 assert (0 && "bad expression node in EmitObjCPropertySet");
Daniel Dunbare6c31752008-08-29 08:11:39 +0000329}
330
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000331void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
332{
Daniel Dunbard82223f2008-09-24 04:04:31 +0000333 llvm::Function *EnumerationMutationFn =
334 CGM.getObjCRuntime().EnumerationMutationFunction();
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000335 llvm::Value *DeclAddress;
336 QualType ElementTy;
337
Daniel Dunbard82223f2008-09-24 04:04:31 +0000338 if (!EnumerationMutationFn) {
339 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
340 return;
341 }
342
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000343 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
344 EmitStmt(SD);
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +0000345 assert(HaveInsertPoint() && "DeclStmt destroyed insert point!");
Ted Kremenek2ac10d02008-10-06 20:59:48 +0000346 const ScopedDecl* D = SD->getSolitaryDecl();
347 ElementTy = cast<ValueDecl>(D)->getType();
348 DeclAddress = LocalDeclMap[D];
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000349 } else {
350 ElementTy = cast<Expr>(S.getElement())->getType();
351 DeclAddress = 0;
352 }
353
354 // Fast enumeration state.
355 QualType StateTy = getContext().getObjCFastEnumerationStateType();
356 llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
357 "state.ptr");
358 StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
Anders Carlsson58d16242008-08-31 04:05:03 +0000359 EmitMemSetToZero(StatePtr, StateTy);
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000360
361 // Number of elements in the items array.
Anders Carlsson58d16242008-08-31 04:05:03 +0000362 static const unsigned NumItems = 16;
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000363
364 // Get selector
365 llvm::SmallVector<IdentifierInfo*, 3> II;
366 II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
367 II.push_back(&CGM.getContext().Idents.get("objects"));
368 II.push_back(&CGM.getContext().Idents.get("count"));
369 Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
370 &II[0]);
371
372 QualType ItemsTy =
373 getContext().getConstantArrayType(getContext().getObjCIdType(),
374 llvm::APInt(32, NumItems),
375 ArrayType::Normal, 0);
376 llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
377
378 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
379
380 CallArgList Args;
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000381 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000382 getContext().getPointerType(StateTy)));
383
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000384 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000385 getContext().getPointerType(ItemsTy)));
386
387 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
388 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Daniel Dunbar0a2da0f2008-09-09 01:06:48 +0000389 Args.push_back(std::make_pair(RValue::get(Count),
390 getContext().UnsignedLongTy));
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000391
392 RValue CountRV =
393 CGM.getObjCRuntime().GenerateMessageSend(*this,
394 getContext().UnsignedLongTy,
395 FastEnumSel,
396 Collection, false, Args);
397
398 llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
399 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
400
Daniel Dunbar72f96552008-11-11 02:29:29 +0000401 llvm::BasicBlock *NoElements = createBasicBlock("noelements");
402 llvm::BasicBlock *SetStartMutations = createBasicBlock("setstartmutations");
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000403
404 llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
405 llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
406
407 llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
Anders Carlsson58d16242008-08-31 04:05:03 +0000408 Builder.CreateCondBr(IsZero, NoElements, SetStartMutations);
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000409
Anders Carlsson58d16242008-08-31 04:05:03 +0000410 EmitBlock(SetStartMutations);
411
412 llvm::Value *StartMutationsPtr =
413 CreateTempAlloca(UnsignedLongLTy);
414
415 llvm::Value *StateMutationsPtrPtr =
416 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
417 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
418 "mutationsptr");
419
420 llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr,
421 "mutations");
422
423 Builder.CreateStore(StateMutations, StartMutationsPtr);
424
Daniel Dunbar72f96552008-11-11 02:29:29 +0000425 llvm::BasicBlock *LoopStart = createBasicBlock("loopstart");
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000426 EmitBlock(LoopStart);
427
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000428 llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
429 Builder.CreateStore(Zero, CounterPtr);
430
Daniel Dunbar72f96552008-11-11 02:29:29 +0000431 llvm::BasicBlock *LoopBody = createBasicBlock("loopbody");
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000432 EmitBlock(LoopBody);
433
Anders Carlsson58d16242008-08-31 04:05:03 +0000434 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
435 StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations");
436
437 llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr,
438 "mutations");
439 llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations,
440 StartMutations,
441 "tobool");
442
443
Daniel Dunbar72f96552008-11-11 02:29:29 +0000444 llvm::BasicBlock *WasMutated = createBasicBlock("wasmutated");
445 llvm::BasicBlock *WasNotMutated = createBasicBlock("wasnotmutated");
Anders Carlsson58d16242008-08-31 04:05:03 +0000446
447 Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated);
448
449 EmitBlock(WasMutated);
450 llvm::Value *V =
451 Builder.CreateBitCast(Collection,
452 ConvertType(getContext().getObjCIdType()),
453 "tmp");
Daniel Dunbard82223f2008-09-24 04:04:31 +0000454 Builder.CreateCall(EnumerationMutationFn, V);
Anders Carlsson58d16242008-08-31 04:05:03 +0000455
456 EmitBlock(WasNotMutated);
457
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000458 llvm::Value *StateItemsPtr =
459 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
460
461 llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
462
463 llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
464 "stateitems");
465
466 llvm::Value *CurrentItemPtr =
467 Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
468
469 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
470
471 // Cast the item to the right type.
472 CurrentItem = Builder.CreateBitCast(CurrentItem,
473 ConvertType(ElementTy), "tmp");
474
475 if (!DeclAddress) {
476 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
477
478 // Set the value to null.
479 Builder.CreateStore(CurrentItem, LV.getAddress());
480 } else
481 Builder.CreateStore(CurrentItem, DeclAddress);
482
483 // Increment the counter.
484 Counter = Builder.CreateAdd(Counter,
485 llvm::ConstantInt::get(UnsignedLongLTy, 1));
486 Builder.CreateStore(Counter, CounterPtr);
487
Daniel Dunbar72f96552008-11-11 02:29:29 +0000488 llvm::BasicBlock *LoopEnd = createBasicBlock("loopend");
489 llvm::BasicBlock *AfterBody = createBasicBlock("afterbody");
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000490
491 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
492
493 EmitStmt(S.getBody());
494
495 BreakContinueStack.pop_back();
496
497 EmitBlock(AfterBody);
498
Daniel Dunbar72f96552008-11-11 02:29:29 +0000499 llvm::BasicBlock *FetchMore = createBasicBlock("fetchmore");
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000500
501 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
Daniel Dunbar35bd6192008-09-04 21:54:37 +0000502 Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
Anders Carlsson6bdf32d2008-08-31 02:33:12 +0000503
504 // Fetch more elements.
505 EmitBlock(FetchMore);
506
507 CountRV =
508 CGM.getObjCRuntime().GenerateMessageSend(*this,
509 getContext().UnsignedLongTy,
510 FastEnumSel,
511 Collection, false, Args);
512 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
513 Limit = Builder.CreateLoad(LimitPtr);
514
515 IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
516 Builder.CreateCondBr(IsZero, NoElements, LoopStart);
517
518 // No more elements.
519 EmitBlock(NoElements);
520
521 if (!DeclAddress) {
522 // If the element was not a declaration, set it to be null.
523
524 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
525
526 // Set the value to null.
527 Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
528 LV.getAddress());
529 }
530
531 EmitBlock(LoopEnd);
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000532}
533
Anders Carlssonb01a2112008-09-09 10:04:29 +0000534void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
535{
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000536 CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
Anders Carlssonb01a2112008-09-09 10:04:29 +0000537}
538
539void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
540{
541 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
542}
543
Chris Lattnerdd978702008-11-15 21:26:17 +0000544void CodeGenFunction::EmitObjCAtSynchronizedStmt(
545 const ObjCAtSynchronizedStmt &S)
546{
Fariborz Jahanianfbeda7b2008-11-21 00:49:24 +0000547 CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
Chris Lattnerdd978702008-11-15 21:26:17 +0000548}
549
Ted Kremenekfa4ebab2008-04-09 15:51:31 +0000550CGObjCRuntime::~CGObjCRuntime() {}