blob: e605065848d478e6bcc628a7237cd49beba7a7b2 [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
Ted Kremenek2979ec72008-04-09 15:51:31 +000014#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000015#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000019#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000020#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000021#include "llvm/Target/TargetData.h"
Chris Lattner41110242008-06-17 18:05:57 +000022
Anders Carlsson55085182007-08-21 17:43:55 +000023using namespace clang;
24using namespace CodeGen;
25
Chris Lattner8fdf3282008-06-24 17:04:18 +000026/// Emits an instance of NSConstantString representing the object.
Daniel Dunbar71fcec92008-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 Dunbarbbce49b2008-08-12 00:12:39 +000031 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(String);
Daniel Dunbared7c6182008-08-20 00:28:19 +000032 // FIXME: This bitcast should just be made an invariant on the Runtime.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000033 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-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 Dunbar208ff5e2008-08-11 18:12:00 +000042 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000043}
44
Daniel Dunbared7c6182008-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 Lattner8fdf3282008-06-24 17:04:18 +000049
50
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000051RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
Chris Lattner8fdf3282008-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 Dunbar208ff5e2008-08-11 18:12:00 +000056 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +000057 const Expr *ReceiverExpr = E->getReceiver();
58 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000059 bool isClassMessage = false;
Chris Lattner8fdf3282008-06-24 17:04:18 +000060 // Find the receiver
61 llvm::Value *Receiver;
62 if (!ReceiverExpr) {
Daniel Dunbarddb2a3d2008-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 Lattner92e62b02008-11-20 04:42:34 +000068 assert(E->getClassName()->isStr("super") &&
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000069 "Unexpected missing class interface in message send.");
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000070 isSuperMessage = true;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000071 Receiver = LoadObjCSelf();
72 } else {
73 Receiver = Runtime.GetClass(Builder, OID);
Chris Lattner8fdf3282008-06-24 17:04:18 +000074 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +000075
76 isClassMessage = true;
Douglas Gregorcd9b46e2008-11-04 14:56:14 +000077 } else if (isa<ObjCSuperExpr>(E->getReceiver())) {
Chris Lattner8fdf3282008-06-24 17:04:18 +000078 isSuperMessage = true;
79 Receiver = LoadObjCSelf();
80 } else {
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000081 Receiver = EmitScalarExpr(E->getReceiver());
Chris Lattner8fdf3282008-06-24 17:04:18 +000082 }
83
Daniel Dunbar19cd87e2008-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 Dunbar46f45b92008-09-09 01:06:48 +000087 Args.push_back(std::make_pair(EmitAnyExprToTemp(*i), (*i)->getType()));
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000088
Chris Lattner8fdf3282008-06-24 17:04:18 +000089 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +000090 // super is only valid in an Objective-C method
91 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000092 return Runtime.GenerateMessageSendSuper(*this, E->getType(),
93 E->getSelector(),
Daniel Dunbarf56f1912008-08-25 08:19:24 +000094 OMD->getClassInterface(),
95 Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000096 isClassMessage,
97 Args);
Chris Lattner8fdf3282008-06-24 17:04:18 +000098 }
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000099 return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
100 Receiver, isClassMessage, Args);
Anders Carlsson55085182007-08-21 17:43:55 +0000101}
102
Daniel Dunbaraf05bb92008-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 Dunbaraf05bb92008-08-26 08:29:31 +0000106void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000107 FunctionArgList Args;
108 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000109
Daniel Dunbar7c086512008-09-09 23:14:03 +0000110 CGM.SetMethodAttributes(OMD, Fn);
Chris Lattner41110242008-06-17 18:05:57 +0000111
Daniel Dunbar7c086512008-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 Lattner41110242008-06-17 18:05:57 +0000116
Daniel Dunbar7c086512008-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 Lattner41110242008-06-17 18:05:57 +0000120 }
Chris Lattner41110242008-06-17 18:05:57 +0000121
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000122 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocEnd());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000123}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000124
Daniel Dunbaraf05bb92008-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 Dunbar2284ac92008-10-18 18:22:23 +0000130 FinishFunction(cast<CompoundStmt>(OMD->getBody())->getRBracLoc());
Daniel Dunbaraf05bb92008-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.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000140void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
141 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000142 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000143 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
144 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
145 assert(OMD && "Invalid call to generate getter (empty method)");
146 // FIXME: This is rather murky, we create this here since they will
147 // not have been created by Sema for us.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000148 OMD->createImplicitParams(getContext(), IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000149 StartObjCMethod(OMD);
150
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000151 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000152 // this. Non-atomic properties are directly evaluated.
153 // atomic 'copy' and 'retain' properties are also directly
154 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000155 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000156 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
157 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
158 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000159 llvm::Value *GetPropertyFn =
160 CGM.getObjCRuntime().GetPropertyGetFunction();
161
162 if (!GetPropertyFn) {
163 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
164 FinishFunction();
165 return;
166 }
167
168 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
169 // FIXME: Can't this be simpler? This might even be worse than the
170 // corresponding gcc code.
171 CodeGenTypes &Types = CGM.getTypes();
172 ValueDecl *Cmd = OMD->getCmdDecl();
173 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
174 QualType IdTy = getContext().getObjCIdType();
175 llvm::Value *SelfAsId =
176 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000177 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000178 llvm::Value *True =
179 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
180 CallArgList Args;
181 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
182 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
183 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
184 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
185 RValue RV = EmitCall(GetPropertyFn, PD->getType(), Args);
186 // We need to fix the type here. Ivars with copy & retain are
187 // always objects so we don't need to worry about complex or
188 // aggregates.
189 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
190 Types.ConvertType(PD->getType())));
191 EmitReturnOfRValue(RV, PD->getType());
192 } else {
Fariborz Jahanian6010bca2008-11-26 22:36:09 +0000193 LValue LV = EmitLValueForIvar(LoadObjCSelf(), Ivar, 0);
194 if (hasAggregateLLVMType(Ivar->getType())) {
195 EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType());
196 }
197 else
198 EmitReturnOfRValue(EmitLoadOfLValue(LV, Ivar->getType()),
199 PD->getType());
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000200 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000201
202 FinishFunction();
203}
204
205/// GenerateObjCSetter - Generate an Objective-C property setter
206/// function. The given Decl must be either an ObjCCategoryImplDecl
207/// or an ObjCImplementationDecl.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000208void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
209 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000210 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000211 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
212 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
213 assert(OMD && "Invalid call to generate setter (empty method)");
214 // FIXME: This is rather murky, we create this here since they will
215 // not have been created by Sema for us.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000216 OMD->createImplicitParams(getContext(), IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000217 StartObjCMethod(OMD);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000218
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000219 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
220 bool IsAtomic =
221 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
222
223 // Determine if we should use an objc_setProperty call for
224 // this. Properties with 'copy' semantics always use it, as do
225 // non-atomic properties with 'release' semantics as long as we are
226 // not in gc-only mode.
227 if (IsCopy ||
228 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
229 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
230 llvm::Value *SetPropertyFn =
231 CGM.getObjCRuntime().GetPropertySetFunction();
232
233 if (!SetPropertyFn) {
234 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
235 FinishFunction();
236 return;
237 }
238
239 // Emit objc_setProperty((id) self, _cmd, offset, arg,
240 // <is-atomic>, <is-copy>).
241 // FIXME: Can't this be simpler? This might even be worse than the
242 // corresponding gcc code.
243 CodeGenTypes &Types = CGM.getTypes();
244 ValueDecl *Cmd = OMD->getCmdDecl();
245 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
246 QualType IdTy = getContext().getObjCIdType();
247 llvm::Value *SelfAsId =
248 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000249 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000250 llvm::Value *Arg = LocalDeclMap[OMD->getParamDecl(0)];
251 llvm::Value *ArgAsId =
252 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
253 Types.ConvertType(IdTy));
254 llvm::Value *True =
255 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
256 llvm::Value *False =
257 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 0);
258 CallArgList Args;
259 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
260 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
261 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
262 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
263 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
264 getContext().BoolTy));
265 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
266 getContext().BoolTy));
267 EmitCall(SetPropertyFn, PD->getType(), Args);
268 } else {
269 SourceLocation Loc = PD->getLocation();
270 ValueDecl *Self = OMD->getSelfDecl();
271 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
272 DeclRefExpr Base(Self, Self->getType(), Loc);
273 ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
274 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
275 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
276 true, true);
277 BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
278 Ivar->getType(), Loc);
279 EmitStmt(&Assign);
280 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000281
282 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000283}
284
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000285llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000286 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
287 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000288}
289
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000290RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000291 // FIXME: Split it into two separate routines.
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000292 if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
293 Selector S = E->getProperty()->getGetterName();
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000294 return CGM.getObjCRuntime().
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000295 GenerateMessageSend(*this, Exp->getType(), S,
296 EmitScalarExpr(E->getBase()),
297 false, CallArgList());
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000298 }
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000299 else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
300 Selector S = E->getGetterMethod()->getSelector();
301 return CGM.getObjCRuntime().
302 GenerateMessageSend(*this, Exp->getType(), S,
303 EmitScalarExpr(E->getBase()),
304 false, CallArgList());
305 }
306 else
307 assert (0 && "bad expression node in EmitObjCPropertyGet");
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000308}
309
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000310void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp,
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000311 RValue Src) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000312 // FIXME: Split it into two separate routines.
313 if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
314 Selector S = E->getProperty()->getSetterName();
315 CallArgList Args;
316 Args.push_back(std::make_pair(Src, E->getType()));
317 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
318 EmitScalarExpr(E->getBase()),
319 false, Args);
320 }
321 else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
322 Selector S = E->getSetterMethod()->getSelector();
323 CallArgList Args;
324 Args.push_back(std::make_pair(Src, E->getType()));
325 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
326 EmitScalarExpr(E->getBase()),
327 false, Args);
328 }
329 else
330 assert (0 && "bad expression node in EmitObjCPropertySet");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000331}
332
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000333void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
334{
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000335 llvm::Function *EnumerationMutationFn =
336 CGM.getObjCRuntime().EnumerationMutationFunction();
Anders Carlssonf484c312008-08-31 02:33:12 +0000337 llvm::Value *DeclAddress;
338 QualType ElementTy;
339
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000340 if (!EnumerationMutationFn) {
341 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
342 return;
343 }
344
Anders Carlssonf484c312008-08-31 02:33:12 +0000345 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
346 EmitStmt(SD);
Daniel Dunbara448fb22008-11-11 23:11:34 +0000347 assert(HaveInsertPoint() && "DeclStmt destroyed insert point!");
Ted Kremenek39741ce2008-10-06 20:59:48 +0000348 const ScopedDecl* D = SD->getSolitaryDecl();
349 ElementTy = cast<ValueDecl>(D)->getType();
350 DeclAddress = LocalDeclMap[D];
Anders Carlssonf484c312008-08-31 02:33:12 +0000351 } else {
352 ElementTy = cast<Expr>(S.getElement())->getType();
353 DeclAddress = 0;
354 }
355
356 // Fast enumeration state.
357 QualType StateTy = getContext().getObjCFastEnumerationStateType();
358 llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
359 "state.ptr");
360 StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000361 EmitMemSetToZero(StatePtr, StateTy);
Anders Carlssonf484c312008-08-31 02:33:12 +0000362
363 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000364 static const unsigned NumItems = 16;
Anders Carlssonf484c312008-08-31 02:33:12 +0000365
366 // Get selector
367 llvm::SmallVector<IdentifierInfo*, 3> II;
368 II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
369 II.push_back(&CGM.getContext().Idents.get("objects"));
370 II.push_back(&CGM.getContext().Idents.get("count"));
371 Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
372 &II[0]);
373
374 QualType ItemsTy =
375 getContext().getConstantArrayType(getContext().getObjCIdType(),
376 llvm::APInt(32, NumItems),
377 ArrayType::Normal, 0);
378 llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
379
380 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
381
382 CallArgList Args;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000383 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000384 getContext().getPointerType(StateTy)));
385
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000386 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000387 getContext().getPointerType(ItemsTy)));
388
389 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
390 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000391 Args.push_back(std::make_pair(RValue::get(Count),
392 getContext().UnsignedLongTy));
Anders Carlssonf484c312008-08-31 02:33:12 +0000393
394 RValue CountRV =
395 CGM.getObjCRuntime().GenerateMessageSend(*this,
396 getContext().UnsignedLongTy,
397 FastEnumSel,
398 Collection, false, Args);
399
400 llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
401 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
402
Daniel Dunbar55e87422008-11-11 02:29:29 +0000403 llvm::BasicBlock *NoElements = createBasicBlock("noelements");
404 llvm::BasicBlock *SetStartMutations = createBasicBlock("setstartmutations");
Anders Carlssonf484c312008-08-31 02:33:12 +0000405
406 llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
407 llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
408
409 llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000410 Builder.CreateCondBr(IsZero, NoElements, SetStartMutations);
Anders Carlssonf484c312008-08-31 02:33:12 +0000411
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000412 EmitBlock(SetStartMutations);
413
414 llvm::Value *StartMutationsPtr =
415 CreateTempAlloca(UnsignedLongLTy);
416
417 llvm::Value *StateMutationsPtrPtr =
418 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
419 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
420 "mutationsptr");
421
422 llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr,
423 "mutations");
424
425 Builder.CreateStore(StateMutations, StartMutationsPtr);
426
Daniel Dunbar55e87422008-11-11 02:29:29 +0000427 llvm::BasicBlock *LoopStart = createBasicBlock("loopstart");
Anders Carlssonf484c312008-08-31 02:33:12 +0000428 EmitBlock(LoopStart);
429
Anders Carlssonf484c312008-08-31 02:33:12 +0000430 llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
431 Builder.CreateStore(Zero, CounterPtr);
432
Daniel Dunbar55e87422008-11-11 02:29:29 +0000433 llvm::BasicBlock *LoopBody = createBasicBlock("loopbody");
Anders Carlssonf484c312008-08-31 02:33:12 +0000434 EmitBlock(LoopBody);
435
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000436 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
437 StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations");
438
439 llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr,
440 "mutations");
441 llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations,
442 StartMutations,
443 "tobool");
444
445
Daniel Dunbar55e87422008-11-11 02:29:29 +0000446 llvm::BasicBlock *WasMutated = createBasicBlock("wasmutated");
447 llvm::BasicBlock *WasNotMutated = createBasicBlock("wasnotmutated");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000448
449 Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated);
450
451 EmitBlock(WasMutated);
452 llvm::Value *V =
453 Builder.CreateBitCast(Collection,
454 ConvertType(getContext().getObjCIdType()),
455 "tmp");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000456 Builder.CreateCall(EnumerationMutationFn, V);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000457
458 EmitBlock(WasNotMutated);
459
Anders Carlssonf484c312008-08-31 02:33:12 +0000460 llvm::Value *StateItemsPtr =
461 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
462
463 llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
464
465 llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
466 "stateitems");
467
468 llvm::Value *CurrentItemPtr =
469 Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
470
471 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
472
473 // Cast the item to the right type.
474 CurrentItem = Builder.CreateBitCast(CurrentItem,
475 ConvertType(ElementTy), "tmp");
476
477 if (!DeclAddress) {
478 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
479
480 // Set the value to null.
481 Builder.CreateStore(CurrentItem, LV.getAddress());
482 } else
483 Builder.CreateStore(CurrentItem, DeclAddress);
484
485 // Increment the counter.
486 Counter = Builder.CreateAdd(Counter,
487 llvm::ConstantInt::get(UnsignedLongLTy, 1));
488 Builder.CreateStore(Counter, CounterPtr);
489
Daniel Dunbar55e87422008-11-11 02:29:29 +0000490 llvm::BasicBlock *LoopEnd = createBasicBlock("loopend");
491 llvm::BasicBlock *AfterBody = createBasicBlock("afterbody");
Anders Carlssonf484c312008-08-31 02:33:12 +0000492
493 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
494
495 EmitStmt(S.getBody());
496
497 BreakContinueStack.pop_back();
498
499 EmitBlock(AfterBody);
500
Daniel Dunbar55e87422008-11-11 02:29:29 +0000501 llvm::BasicBlock *FetchMore = createBasicBlock("fetchmore");
Anders Carlssonf484c312008-08-31 02:33:12 +0000502
503 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
Daniel Dunbarfe2b2c02008-09-04 21:54:37 +0000504 Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
Anders Carlssonf484c312008-08-31 02:33:12 +0000505
506 // Fetch more elements.
507 EmitBlock(FetchMore);
508
509 CountRV =
510 CGM.getObjCRuntime().GenerateMessageSend(*this,
511 getContext().UnsignedLongTy,
512 FastEnumSel,
513 Collection, false, Args);
514 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
515 Limit = Builder.CreateLoad(LimitPtr);
516
517 IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
518 Builder.CreateCondBr(IsZero, NoElements, LoopStart);
519
520 // No more elements.
521 EmitBlock(NoElements);
522
523 if (!DeclAddress) {
524 // If the element was not a declaration, set it to be null.
525
526 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
527
528 // Set the value to null.
529 Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
530 LV.getAddress());
531 }
532
533 EmitBlock(LoopEnd);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000534}
535
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000536void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
537{
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000538 CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000539}
540
541void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
542{
543 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
544}
545
Chris Lattner10cac6f2008-11-15 21:26:17 +0000546void CodeGenFunction::EmitObjCAtSynchronizedStmt(
547 const ObjCAtSynchronizedStmt &S)
548{
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000549 CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000550}
551
Ted Kremenek2979ec72008-04-09 15:51:31 +0000552CGObjCRuntime::~CGObjCRuntime() {}