blob: 3ebee12f0df56b3ace544b54c87476a1aba16ece [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.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000106void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
107 const ObjCContainerDecl *CD) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000108 FunctionArgList Args;
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000109 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000110
Daniel Dunbar7c086512008-09-09 23:14:03 +0000111 CGM.SetMethodAttributes(OMD, Fn);
Chris Lattner41110242008-06-17 18:05:57 +0000112
Daniel Dunbar7c086512008-09-09 23:14:03 +0000113 Args.push_back(std::make_pair(OMD->getSelfDecl(),
114 OMD->getSelfDecl()->getType()));
115 Args.push_back(std::make_pair(OMD->getCmdDecl(),
116 OMD->getCmdDecl()->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000117
Daniel Dunbar7c086512008-09-09 23:14:03 +0000118 for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i) {
119 ParmVarDecl *IPD = OMD->getParamDecl(i);
120 Args.push_back(std::make_pair(IPD, IPD->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000121 }
Chris Lattner41110242008-06-17 18:05:57 +0000122
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000123 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocEnd());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000124}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000125
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000126/// Generate an Objective-C method. An Objective-C method is a C function with
127/// its pointer, name, and types registered in the class struture.
128void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000129 StartObjCMethod(OMD, OMD->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000130 EmitStmt(OMD->getBody());
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000131 FinishFunction(cast<CompoundStmt>(OMD->getBody())->getRBracLoc());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000132}
133
134// FIXME: I wasn't sure about the synthesis approach. If we end up
135// generating an AST for the whole body we can just fall back to
136// having a GenerateFunction which takes the body Stmt.
137
138/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000139/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
140/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000141void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
142 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000143 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000144 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
145 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
146 assert(OMD && "Invalid call to generate getter (empty method)");
147 // FIXME: This is rather murky, we create this here since they will
148 // not have been created by Sema for us.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000149 OMD->createImplicitParams(getContext(), IMP->getClassInterface());
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000150 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000151
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000152 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000153 // this. Non-atomic properties are directly evaluated.
154 // atomic 'copy' and 'retain' properties are also directly
155 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000156 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000157 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
158 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
159 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000160 llvm::Value *GetPropertyFn =
161 CGM.getObjCRuntime().GetPropertyGetFunction();
162
163 if (!GetPropertyFn) {
164 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
165 FinishFunction();
166 return;
167 }
168
169 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
170 // FIXME: Can't this be simpler? This might even be worse than the
171 // corresponding gcc code.
172 CodeGenTypes &Types = CGM.getTypes();
173 ValueDecl *Cmd = OMD->getCmdDecl();
174 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
175 QualType IdTy = getContext().getObjCIdType();
176 llvm::Value *SelfAsId =
177 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000178 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000179 llvm::Value *True =
180 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
181 CallArgList Args;
182 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
183 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
184 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
185 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000186 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args),
Daniel Dunbar88b53962009-02-02 22:03:45 +0000187 GetPropertyFn, Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000188 // We need to fix the type here. Ivars with copy & retain are
189 // always objects so we don't need to worry about complex or
190 // aggregates.
191 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
192 Types.ConvertType(PD->getType())));
193 EmitReturnOfRValue(RV, PD->getType());
194 } else {
Fariborz Jahanianfd64bb62008-12-15 20:35:07 +0000195 FieldDecl *Field =
196 IMP->getClassInterface()->lookupFieldDeclForIvar(getContext(), Ivar);
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000197 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
198 LoadObjCSelf(), Ivar, Field, 0);
Fariborz Jahanian6010bca2008-11-26 22:36:09 +0000199 if (hasAggregateLLVMType(Ivar->getType())) {
200 EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType());
201 }
202 else
203 EmitReturnOfRValue(EmitLoadOfLValue(LV, Ivar->getType()),
204 PD->getType());
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000205 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000206
207 FinishFunction();
208}
209
210/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000211/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
212/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000213void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
214 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000215 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000216 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
217 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
218 assert(OMD && "Invalid call to generate setter (empty method)");
219 // FIXME: This is rather murky, we create this here since they will
220 // not have been created by Sema for us.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000221 OMD->createImplicitParams(getContext(), IMP->getClassInterface());
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000222 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000223
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000224 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
225 bool IsAtomic =
226 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
227
228 // Determine if we should use an objc_setProperty call for
229 // this. Properties with 'copy' semantics always use it, as do
230 // non-atomic properties with 'release' semantics as long as we are
231 // not in gc-only mode.
232 if (IsCopy ||
233 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
234 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
235 llvm::Value *SetPropertyFn =
236 CGM.getObjCRuntime().GetPropertySetFunction();
237
238 if (!SetPropertyFn) {
239 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
240 FinishFunction();
241 return;
242 }
243
244 // Emit objc_setProperty((id) self, _cmd, offset, arg,
245 // <is-atomic>, <is-copy>).
246 // FIXME: Can't this be simpler? This might even be worse than the
247 // corresponding gcc code.
248 CodeGenTypes &Types = CGM.getTypes();
249 ValueDecl *Cmd = OMD->getCmdDecl();
250 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
251 QualType IdTy = getContext().getObjCIdType();
252 llvm::Value *SelfAsId =
253 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000254 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000255 llvm::Value *Arg = LocalDeclMap[OMD->getParamDecl(0)];
256 llvm::Value *ArgAsId =
257 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
258 Types.ConvertType(IdTy));
259 llvm::Value *True =
260 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 1);
261 llvm::Value *False =
262 llvm::ConstantInt::get(Types.ConvertTypeForMem(getContext().BoolTy), 0);
263 CallArgList Args;
264 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
265 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
266 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
267 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
268 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
269 getContext().BoolTy));
270 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
271 getContext().BoolTy));
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000272 EmitCall(Types.getFunctionInfo(PD->getType(), Args),
273 SetPropertyFn, Args);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000274 } else {
275 SourceLocation Loc = PD->getLocation();
276 ValueDecl *Self = OMD->getSelfDecl();
277 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
278 DeclRefExpr Base(Self, Self->getType(), Loc);
279 ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
280 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
Fariborz Jahanianaaa63a72008-12-13 22:20:28 +0000281 ObjCInterfaceDecl *OI = IMP->getClassInterface();
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000282 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000283 true, true);
Fariborz Jahanianefc4c4b2008-12-18 17:29:46 +0000284 getContext().setFieldDecl(OI, Ivar, &IvarRef);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000285 BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
286 Ivar->getType(), Loc);
287 EmitStmt(&Assign);
288 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000289
290 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000291}
292
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000293llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000294 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
295 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000296}
297
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000298QualType CodeGenFunction::TypeOfSelfObject() {
299 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
300 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
301 const PointerType *PTy =
302 cast<PointerType>(getContext().getCanonicalType(selfDecl->getType()));
303 return PTy->getPointeeType();
304}
305
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000306RValue CodeGenFunction::EmitObjCPropertyGet(const Expr *Exp) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000307 // FIXME: Split it into two separate routines.
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000308 if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
309 Selector S = E->getProperty()->getGetterName();
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000310 return CGM.getObjCRuntime().
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000311 GenerateMessageSend(*this, Exp->getType(), S,
312 EmitScalarExpr(E->getBase()),
313 false, CallArgList());
Fariborz Jahanian5daf5702008-11-22 18:39:36 +0000314 }
Daniel Dunbarf1853192009-01-15 18:32:35 +0000315 else {
Daniel Dunbarf479cea2009-01-16 01:50:29 +0000316 const ObjCKVCRefExpr *KE = cast<ObjCKVCRefExpr>(Exp);
317 Selector S = KE->getGetterMethod()->getSelector();
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000318 return CGM.getObjCRuntime().
319 GenerateMessageSend(*this, Exp->getType(), S,
Daniel Dunbarf479cea2009-01-16 01:50:29 +0000320 EmitScalarExpr(KE->getBase()),
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000321 false, CallArgList());
322 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000323}
324
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000325void CodeGenFunction::EmitObjCPropertySet(const Expr *Exp,
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000326 RValue Src) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000327 // FIXME: Split it into two separate routines.
328 if (const ObjCPropertyRefExpr *E = dyn_cast<ObjCPropertyRefExpr>(Exp)) {
329 Selector S = E->getProperty()->getSetterName();
330 CallArgList Args;
331 Args.push_back(std::make_pair(Src, E->getType()));
332 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
333 EmitScalarExpr(E->getBase()),
334 false, Args);
335 }
336 else if (const ObjCKVCRefExpr *E = dyn_cast<ObjCKVCRefExpr>(Exp)) {
337 Selector S = E->getSetterMethod()->getSelector();
338 CallArgList Args;
339 Args.push_back(std::make_pair(Src, E->getType()));
340 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
341 EmitScalarExpr(E->getBase()),
342 false, Args);
343 }
344 else
345 assert (0 && "bad expression node in EmitObjCPropertySet");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000346}
347
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000348void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
349{
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000350 llvm::Function *EnumerationMutationFn =
351 CGM.getObjCRuntime().EnumerationMutationFunction();
Anders Carlssonf484c312008-08-31 02:33:12 +0000352 llvm::Value *DeclAddress;
353 QualType ElementTy;
354
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000355 if (!EnumerationMutationFn) {
356 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
357 return;
358 }
359
Anders Carlssonf484c312008-08-31 02:33:12 +0000360 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
361 EmitStmt(SD);
Daniel Dunbara448fb22008-11-11 23:11:34 +0000362 assert(HaveInsertPoint() && "DeclStmt destroyed insert point!");
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000363 const Decl* D = SD->getSolitaryDecl();
Ted Kremenek39741ce2008-10-06 20:59:48 +0000364 ElementTy = cast<ValueDecl>(D)->getType();
365 DeclAddress = LocalDeclMap[D];
Anders Carlssonf484c312008-08-31 02:33:12 +0000366 } else {
367 ElementTy = cast<Expr>(S.getElement())->getType();
368 DeclAddress = 0;
369 }
370
371 // Fast enumeration state.
372 QualType StateTy = getContext().getObjCFastEnumerationStateType();
373 llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
374 "state.ptr");
375 StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000376 EmitMemSetToZero(StatePtr, StateTy);
Anders Carlssonf484c312008-08-31 02:33:12 +0000377
378 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000379 static const unsigned NumItems = 16;
Anders Carlssonf484c312008-08-31 02:33:12 +0000380
381 // Get selector
382 llvm::SmallVector<IdentifierInfo*, 3> II;
383 II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
384 II.push_back(&CGM.getContext().Idents.get("objects"));
385 II.push_back(&CGM.getContext().Idents.get("count"));
386 Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
387 &II[0]);
388
389 QualType ItemsTy =
390 getContext().getConstantArrayType(getContext().getObjCIdType(),
391 llvm::APInt(32, NumItems),
392 ArrayType::Normal, 0);
393 llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
394
395 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
396
397 CallArgList Args;
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000398 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000399 getContext().getPointerType(StateTy)));
400
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000401 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000402 getContext().getPointerType(ItemsTy)));
403
404 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
405 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000406 Args.push_back(std::make_pair(RValue::get(Count),
407 getContext().UnsignedLongTy));
Anders Carlssonf484c312008-08-31 02:33:12 +0000408
409 RValue CountRV =
410 CGM.getObjCRuntime().GenerateMessageSend(*this,
411 getContext().UnsignedLongTy,
412 FastEnumSel,
413 Collection, false, Args);
414
415 llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
416 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
417
Daniel Dunbar55e87422008-11-11 02:29:29 +0000418 llvm::BasicBlock *NoElements = createBasicBlock("noelements");
419 llvm::BasicBlock *SetStartMutations = createBasicBlock("setstartmutations");
Anders Carlssonf484c312008-08-31 02:33:12 +0000420
421 llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
422 llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
423
424 llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000425 Builder.CreateCondBr(IsZero, NoElements, SetStartMutations);
Anders Carlssonf484c312008-08-31 02:33:12 +0000426
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000427 EmitBlock(SetStartMutations);
428
429 llvm::Value *StartMutationsPtr =
430 CreateTempAlloca(UnsignedLongLTy);
431
432 llvm::Value *StateMutationsPtrPtr =
433 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
434 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
435 "mutationsptr");
436
437 llvm::Value *StateMutations = Builder.CreateLoad(StateMutationsPtr,
438 "mutations");
439
440 Builder.CreateStore(StateMutations, StartMutationsPtr);
441
Daniel Dunbar55e87422008-11-11 02:29:29 +0000442 llvm::BasicBlock *LoopStart = createBasicBlock("loopstart");
Anders Carlssonf484c312008-08-31 02:33:12 +0000443 EmitBlock(LoopStart);
444
Anders Carlssonf484c312008-08-31 02:33:12 +0000445 llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
446 Builder.CreateStore(Zero, CounterPtr);
447
Daniel Dunbar55e87422008-11-11 02:29:29 +0000448 llvm::BasicBlock *LoopBody = createBasicBlock("loopbody");
Anders Carlssonf484c312008-08-31 02:33:12 +0000449 EmitBlock(LoopBody);
450
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000451 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
452 StateMutations = Builder.CreateLoad(StateMutationsPtr, "statemutations");
453
454 llvm::Value *StartMutations = Builder.CreateLoad(StartMutationsPtr,
455 "mutations");
456 llvm::Value *MutationsEqual = Builder.CreateICmpEQ(StateMutations,
457 StartMutations,
458 "tobool");
459
460
Daniel Dunbar55e87422008-11-11 02:29:29 +0000461 llvm::BasicBlock *WasMutated = createBasicBlock("wasmutated");
462 llvm::BasicBlock *WasNotMutated = createBasicBlock("wasnotmutated");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000463
464 Builder.CreateCondBr(MutationsEqual, WasNotMutated, WasMutated);
465
466 EmitBlock(WasMutated);
467 llvm::Value *V =
468 Builder.CreateBitCast(Collection,
469 ConvertType(getContext().getObjCIdType()),
470 "tmp");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000471 Builder.CreateCall(EnumerationMutationFn, V);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000472
473 EmitBlock(WasNotMutated);
474
Anders Carlssonf484c312008-08-31 02:33:12 +0000475 llvm::Value *StateItemsPtr =
476 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
477
478 llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
479
480 llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
481 "stateitems");
482
483 llvm::Value *CurrentItemPtr =
484 Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
485
486 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
487
488 // Cast the item to the right type.
489 CurrentItem = Builder.CreateBitCast(CurrentItem,
490 ConvertType(ElementTy), "tmp");
491
492 if (!DeclAddress) {
493 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
494
495 // Set the value to null.
496 Builder.CreateStore(CurrentItem, LV.getAddress());
497 } else
498 Builder.CreateStore(CurrentItem, DeclAddress);
499
500 // Increment the counter.
501 Counter = Builder.CreateAdd(Counter,
502 llvm::ConstantInt::get(UnsignedLongLTy, 1));
503 Builder.CreateStore(Counter, CounterPtr);
504
Daniel Dunbar55e87422008-11-11 02:29:29 +0000505 llvm::BasicBlock *LoopEnd = createBasicBlock("loopend");
506 llvm::BasicBlock *AfterBody = createBasicBlock("afterbody");
Anders Carlssonf484c312008-08-31 02:33:12 +0000507
Anders Carlssone21269b2008-12-13 22:52:24 +0000508 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody,
509 ObjCEHStack.size()));
Anders Carlssonf484c312008-08-31 02:33:12 +0000510
511 EmitStmt(S.getBody());
512
513 BreakContinueStack.pop_back();
514
515 EmitBlock(AfterBody);
516
Daniel Dunbar55e87422008-11-11 02:29:29 +0000517 llvm::BasicBlock *FetchMore = createBasicBlock("fetchmore");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +0000518
519 Counter = Builder.CreateLoad(CounterPtr);
520 Limit = Builder.CreateLoad(LimitPtr);
Anders Carlssonf484c312008-08-31 02:33:12 +0000521 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
Daniel Dunbarfe2b2c02008-09-04 21:54:37 +0000522 Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
Anders Carlssonf484c312008-08-31 02:33:12 +0000523
524 // Fetch more elements.
525 EmitBlock(FetchMore);
526
527 CountRV =
528 CGM.getObjCRuntime().GenerateMessageSend(*this,
529 getContext().UnsignedLongTy,
530 FastEnumSel,
531 Collection, false, Args);
532 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
533 Limit = Builder.CreateLoad(LimitPtr);
534
535 IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
536 Builder.CreateCondBr(IsZero, NoElements, LoopStart);
537
538 // No more elements.
539 EmitBlock(NoElements);
540
541 if (!DeclAddress) {
542 // If the element was not a declaration, set it to be null.
543
544 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
545
546 // Set the value to null.
547 Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
548 LV.getAddress());
549 }
550
551 EmitBlock(LoopEnd);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000552}
553
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000554void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S)
555{
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000556 CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000557}
558
559void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S)
560{
561 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
562}
563
Chris Lattner10cac6f2008-11-15 21:26:17 +0000564void CodeGenFunction::EmitObjCAtSynchronizedStmt(
565 const ObjCAtSynchronizedStmt &S)
566{
Fariborz Jahanianbd71be42008-11-21 00:49:24 +0000567 CGM.getObjCRuntime().EmitTryOrSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000568}
569
Ted Kremenek2979ec72008-04-09 15:51:31 +0000570CGObjCRuntime::~CGObjCRuntime() {}