blob: c7e0837b3dc2fed1f36f3745f52f6582e3b845ae [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"
Chris Lattner16f00492009-04-26 01:32:48 +000019#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000020#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000021#include "llvm/ADT/STLExtras.h"
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +000022#include "llvm/Target/TargetData.h"
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.
Mike Stump1eb44332009-09-09 15:08:12 +000027llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000028{
David Chisnall0d13f6f2010-01-23 02:40:42 +000029 llvm::Constant *C =
30 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000031 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000032 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000033}
34
35/// Emit a selector.
36llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
37 // Untyped selector.
38 // Note that this implementation allows for non-constant strings to be passed
39 // as arguments to @selector(). Currently, the only thing preventing this
40 // behaviour is the type checking in the front end.
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +000041 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000042}
43
Daniel Dunbared7c6182008-08-20 00:28:19 +000044llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
45 // FIXME: This should pass the Decl not the name.
46 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
47}
Chris Lattner8fdf3282008-06-24 17:04:18 +000048
49
John McCallef072fd2010-05-22 01:48:05 +000050RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
51 ReturnValueSlot Return) {
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.
Mike Stump1eb44332009-09-09 15:08:12 +000055
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000056 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +000057 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000058 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +000059 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +000060 // Find the receiver
Daniel Dunbar0b647a62010-04-22 03:17:06 +000061 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +000062 switch (E->getReceiverKind()) {
63 case ObjCMessageExpr::Instance:
64 Receiver = EmitScalarExpr(E->getInstanceReceiver());
65 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000066
Douglas Gregor04badcf2010-04-21 00:45:42 +000067 case ObjCMessageExpr::Class: {
John McCall3031c632010-05-17 20:12:43 +000068 const ObjCObjectType *ObjTy
69 = E->getClassReceiver()->getAs<ObjCObjectType>();
70 assert(ObjTy && "Invalid Objective-C class message send");
71 OID = ObjTy->getInterface();
72 assert(OID && "Invalid Objective-C class message send");
David Chisnallc6cd5fd2010-04-28 19:33:36 +000073 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +000074 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +000075 break;
76 }
77
78 case ObjCMessageExpr::SuperInstance:
Chris Lattner8fdf3282008-06-24 17:04:18 +000079 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +000080 isSuperMessage = true;
81 break;
82
83 case ObjCMessageExpr::SuperClass:
84 Receiver = LoadObjCSelf();
85 isSuperMessage = true;
86 isClassMessage = true;
87 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +000088 }
89
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000090 CallArgList Args;
Anders Carlsson131038e2009-04-18 20:29:27 +000091 EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +000092
Anders Carlsson7e70fb22010-06-21 20:59:55 +000093 QualType ResultType =
94 E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
95
Chris Lattner8fdf3282008-06-24 17:04:18 +000096 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +000097 // super is only valid in an Objective-C method
98 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +000099 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000100 return Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000101 E->getSelector(),
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000102 OMD->getClassInterface(),
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000103 isCategoryImpl,
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000104 Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000105 isClassMessage,
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000106 Args,
107 E->getMethodDecl());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000108 }
Daniel Dunbard6c93d72009-09-17 04:01:22 +0000109
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000110 return Runtime.GenerateMessageSend(*this, Return, ResultType,
John McCallef072fd2010-05-22 01:48:05 +0000111 E->getSelector(),
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000112 Receiver, Args, OID,
Fariborz Jahaniandf9ccc62009-05-05 21:36:57 +0000113 E->getMethodDecl());
Anders Carlsson55085182007-08-21 17:43:55 +0000114}
115
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000116/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
117/// the LLVM function and sets the other context used by
118/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000119void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
120 const ObjCContainerDecl *CD) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000121 FunctionArgList Args;
Devang Patel4800ea62010-04-05 21:09:15 +0000122 // Check if we should generate debug info for this method.
123 if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
124 DebugInfo = CGM.getDebugInfo();
125
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000126 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000127
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000128 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
129 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000130
Mike Stump1eb44332009-09-09 15:08:12 +0000131 Args.push_back(std::make_pair(OMD->getSelfDecl(),
Daniel Dunbar7c086512008-09-09 23:14:03 +0000132 OMD->getSelfDecl()->getType()));
133 Args.push_back(std::make_pair(OMD->getCmdDecl(),
134 OMD->getCmdDecl()->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000135
Chris Lattner89951a82009-02-20 18:43:26 +0000136 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
137 E = OMD->param_end(); PI != E; ++PI)
138 Args.push_back(std::make_pair(*PI, (*PI)->getType()));
Chris Lattner41110242008-06-17 18:05:57 +0000139
Peter Collingbourne14110472011-01-13 18:57:25 +0000140 CurGD = OMD;
141
Devang Patela92d6132010-02-15 18:08:38 +0000142 StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000143}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000144
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000145/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000146/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000147void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000148 StartObjCMethod(OMD, OMD->getClassInterface());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000149 EmitStmt(OMD->getBody());
150 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000151}
152
Mike Stumpf5408fe2009-05-16 07:57:57 +0000153// FIXME: I wasn't sure about the synthesis approach. If we end up generating an
154// AST for the whole body we can just fall back to having a GenerateFunction
155// which takes the body Stmt.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000156
157/// GenerateObjCGetter - Generate an Objective-C property getter
Steve Naroff489034c2009-01-10 22:55:25 +0000158/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
159/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000160void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
161 const ObjCPropertyImplDecl *PID) {
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000162 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000163 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000164 bool IsAtomic =
165 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000166 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
167 assert(OMD && "Invalid call to generate getter (empty method)");
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000168 StartObjCMethod(OMD, IMP->getClassInterface());
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000169
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000170 // Determine if we should use an objc_getProperty call for
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000171 // this. Non-atomic properties are directly evaluated.
172 // atomic 'copy' and 'retain' properties are also directly
173 // evaluated in gc-only mode.
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000174 if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000175 IsAtomic &&
Fariborz Jahanian447d7ae2008-12-08 23:56:17 +0000176 (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
177 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000178 llvm::Value *GetPropertyFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000179 CGM.getObjCRuntime().GetPropertyGetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000181 if (!GetPropertyFn) {
182 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
183 FinishFunction();
184 return;
185 }
186
187 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
188 // FIXME: Can't this be simpler? This might even be worse than the
189 // corresponding gcc code.
190 CodeGenTypes &Types = CGM.getTypes();
191 ValueDecl *Cmd = OMD->getCmdDecl();
192 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
193 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000194 llvm::Value *SelfAsId =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000195 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000196 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000197 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000198 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000199 CallArgList Args;
200 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
201 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
202 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
203 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000204 // FIXME: We shouldn't need to get the function info here, the
205 // runtime already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000206 RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000207 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000208 GetPropertyFn, ReturnValueSlot(), Args);
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000209 // We need to fix the type here. Ivars with copy & retain are
210 // always objects so we don't need to worry about complex or
211 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000212 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000213 Types.ConvertType(PD->getType())));
214 EmitReturnOfRValue(RV, PD->getType());
215 } else {
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000216 if (Ivar->getType()->isAnyComplexType()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000217 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
218 Ivar, 0);
Fariborz Jahanian1b23fe62010-03-25 21:56:43 +0000219 ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
220 LV.isVolatileQualified());
221 StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
222 }
223 else if (hasAggregateLLVMType(Ivar->getType())) {
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000224 bool IsStrong = false;
225 if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(Ivar->getType())))
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000226 && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
David Chisnall8fac25d2010-12-26 22:13:16 +0000227 && CGM.getObjCRuntime().GetGetStructFunction()) {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000228 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
229 Ivar, 0);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000230 llvm::Value *GetCopyStructFn =
David Chisnall8fac25d2010-12-26 22:13:16 +0000231 CGM.getObjCRuntime().GetGetStructFunction();
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000232 CodeGenTypes &Types = CGM.getTypes();
233 // objc_copyStruct (ReturnValue, &structIvar,
234 // sizeof (Type of Ivar), isAtomic, false);
235 CallArgList Args;
236 RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
237 Types.ConvertType(getContext().VoidPtrTy)));
238 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
239 RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
240 Types.ConvertType(getContext().VoidPtrTy)));
241 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
242 // sizeof (Type of Ivar)
243 uint64_t Size = getContext().getTypeSize(Ivar->getType()) / 8;
244 llvm::Value *SizeVal =
245 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), Size);
246 Args.push_back(std::make_pair(RValue::get(SizeVal),
247 getContext().LongTy));
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000248 llvm::Value *isAtomic =
Fariborz Jahanian08adf322010-04-13 18:43:37 +0000249 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
250 IsAtomic ? 1 : 0);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000251 Args.push_back(std::make_pair(RValue::get(isAtomic),
252 getContext().BoolTy));
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000253 llvm::Value *hasStrong =
254 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
255 IsStrong ? 1 : 0);
256 Args.push_back(std::make_pair(RValue::get(hasStrong),
257 getContext().BoolTy));
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000258 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
259 FunctionType::ExtInfo()),
260 GetCopyStructFn, ReturnValueSlot(), Args);
261 }
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000262 else {
263 if (PID->getGetterCXXConstructor()) {
264 ReturnStmt *Stmt =
265 new (getContext()) ReturnStmt(SourceLocation(),
Douglas Gregor5077c382010-05-15 06:01:05 +0000266 PID->getGetterCXXConstructor(),
267 0);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000268 EmitReturnStmt(*Stmt);
269 }
270 else {
271 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
272 Ivar, 0);
273 EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType());
274 }
275 }
Mike Stumpb3589f42009-07-30 22:28:39 +0000276 } else {
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000277 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
278 Ivar, 0);
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000279 CodeGenTypes &Types = CGM.getTypes();
280 RValue RV = EmitLoadOfLValue(LV, Ivar->getType());
281 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Mike Stump1eb44332009-09-09 15:08:12 +0000282 Types.ConvertType(PD->getType())));
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000283 EmitReturnOfRValue(RV, PD->getType());
284 }
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000285 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000286
287 FinishFunction();
288}
289
290/// GenerateObjCSetter - Generate an Objective-C property setter
Steve Naroff489034c2009-01-10 22:55:25 +0000291/// function. The given Decl must be an ObjCImplementationDecl. @synthesize
292/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000293void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
294 const ObjCPropertyImplDecl *PID) {
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000295 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000296 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
297 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
298 assert(OMD && "Invalid call to generate setter (empty method)");
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000299 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000300
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000301 bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
Mike Stump1eb44332009-09-09 15:08:12 +0000302 bool IsAtomic =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000303 !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
304
305 // Determine if we should use an objc_setProperty call for
306 // this. Properties with 'copy' semantics always use it, as do
307 // non-atomic properties with 'release' semantics as long as we are
308 // not in gc-only mode.
309 if (IsCopy ||
310 (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
311 PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000312 llvm::Value *SetPropertyFn =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000313 CGM.getObjCRuntime().GetPropertySetFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000315 if (!SetPropertyFn) {
316 CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
317 FinishFunction();
318 return;
319 }
Mike Stump1eb44332009-09-09 15:08:12 +0000320
321 // Emit objc_setProperty((id) self, _cmd, offset, arg,
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000322 // <is-atomic>, <is-copy>).
323 // FIXME: Can't this be simpler? This might even be worse than the
324 // corresponding gcc code.
325 CodeGenTypes &Types = CGM.getTypes();
326 ValueDecl *Cmd = OMD->getCmdDecl();
327 llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
328 QualType IdTy = getContext().getObjCIdType();
Mike Stump1eb44332009-09-09 15:08:12 +0000329 llvm::Value *SelfAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000330 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000331 llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
Chris Lattner89951a82009-02-20 18:43:26 +0000332 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
Mike Stump1eb44332009-09-09 15:08:12 +0000333 llvm::Value *ArgAsId =
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000334 Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
335 Types.ConvertType(IdTy));
336 llvm::Value *True =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000337 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000338 llvm::Value *False =
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000339 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000340 CallArgList Args;
341 Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
342 Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
343 Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
344 Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000345 Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000346 getContext().BoolTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000347 Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000348 getContext().BoolTy));
Mike Stumpf5408fe2009-05-16 07:57:57 +0000349 // FIXME: We shouldn't need to get the function info here, the runtime
350 // already should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000351 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
Rafael Espindola264ba482010-03-30 20:24:48 +0000352 FunctionType::ExtInfo()),
353 SetPropertyFn,
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000354 ReturnValueSlot(), Args);
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000355 } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
356 !Ivar->getType()->isAnyComplexType() &&
357 IndirectObjCSetterArg(*CurFnInfo)
David Chisnall8fac25d2010-12-26 22:13:16 +0000358 && CGM.getObjCRuntime().GetSetStructFunction()) {
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000359 // objc_copyStruct (&structIvar, &Arg,
360 // sizeof (struct something), true, false);
361 llvm::Value *GetCopyStructFn =
David Chisnall8fac25d2010-12-26 22:13:16 +0000362 CGM.getObjCRuntime().GetSetStructFunction();
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000363 CodeGenTypes &Types = CGM.getTypes();
364 CallArgList Args;
365 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
366 RValue RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
367 Types.ConvertType(getContext().VoidPtrTy)));
368 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
369 llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
370 llvm::Value *ArgAsPtrTy =
371 Builder.CreateBitCast(Arg,
372 Types.ConvertType(getContext().VoidPtrTy));
373 RV = RValue::get(ArgAsPtrTy);
374 Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
375 // sizeof (Type of Ivar)
376 uint64_t Size = getContext().getTypeSize(Ivar->getType()) / 8;
377 llvm::Value *SizeVal =
378 llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), Size);
379 Args.push_back(std::make_pair(RValue::get(SizeVal),
380 getContext().LongTy));
381 llvm::Value *True =
382 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
383 Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
384 llvm::Value *False =
385 llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
386 Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
387 EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
388 FunctionType::ExtInfo()),
389 GetCopyStructFn, ReturnValueSlot(), Args);
Fariborz Jahanian97a73cd2010-05-06 15:45:36 +0000390 } else if (PID->getSetterCXXAssignment()) {
John McCall2a416372010-12-05 02:00:02 +0000391 EmitIgnoredExpr(PID->getSetterCXXAssignment());
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000392 } else {
Daniel Dunbar45e84232009-10-27 19:21:30 +0000393 // FIXME: Find a clean way to avoid AST node creation.
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000394 SourceLocation Loc = PD->getLocation();
395 ValueDecl *Self = OMD->getSelfDecl();
396 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
John McCallf89e55a2010-11-18 06:31:45 +0000397 DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
Chris Lattner89951a82009-02-20 18:43:26 +0000398 ParmVarDecl *ArgDecl = *OMD->param_begin();
John McCallf89e55a2010-11-18 06:31:45 +0000399 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000400 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
401
402 // The property type can differ from the ivar type in some situations with
403 // Objective-C pointer types, we can always bit cast the RHS in these cases.
404 if (getContext().getCanonicalType(Ivar->getType()) !=
405 getContext().getCanonicalType(ArgDecl->getType())) {
John McCallf871d0c2010-08-07 06:22:56 +0000406 ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
John McCall2de56d12010-08-25 11:45:40 +0000407 Ivar->getType(), CK_BitCast, &Arg,
John McCall5baba9d2010-08-25 10:28:54 +0000408 VK_RValue);
John McCall2de56d12010-08-25 11:45:40 +0000409 BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
John McCallf89e55a2010-11-18 06:31:45 +0000410 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000411 EmitStmt(&Assign);
412 } else {
John McCall2de56d12010-08-25 11:45:40 +0000413 BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
John McCallf89e55a2010-11-18 06:31:45 +0000414 Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
Daniel Dunbar45e84232009-10-27 19:21:30 +0000415 EmitStmt(&Assign);
416 }
Daniel Dunbar86957eb2008-09-24 06:32:09 +0000417 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000418
419 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000420}
421
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000422void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
423 ObjCMethodDecl *MD,
424 bool ctor) {
Sean Huntcbb67482011-01-08 20:30:50 +0000425 llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000426 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
427 StartObjCMethod(MD, IMP->getClassInterface());
428 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
429 E = IMP->init_end(); B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000430 CXXCtorInitializer *Member = (*B);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000431 IvarInitializers.push_back(Member);
432 }
433 if (ctor) {
434 for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) {
Sean Huntcbb67482011-01-08 20:30:50 +0000435 CXXCtorInitializer *IvarInit = IvarInitializers[I];
Francois Pichet00eb3f92010-12-04 09:14:42 +0000436 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000437 QualType FieldType = Field->getType();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000438 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000439 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
440 LoadObjCSelf(), Ivar, 0);
John McCall558d2ab2010-09-15 10:14:12 +0000441 EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000442 }
443 // constructor returns 'self'.
444 CodeGenTypes &Types = CGM.getTypes();
445 QualType IdTy(CGM.getContext().getObjCIdType());
446 llvm::Value *SelfAsId =
447 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
448 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000449 } else {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000450 // dtor
451 for (size_t i = IvarInitializers.size(); i > 0; --i) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000452 FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000453 QualType FieldType = Field->getType();
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +0000454 const ConstantArrayType *Array =
455 getContext().getAsConstantArrayType(FieldType);
456 if (Array)
457 FieldType = getContext().getBaseElementType(FieldType);
458
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000459 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
460 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
461 LoadObjCSelf(), Ivar, 0);
462 const RecordType *RT = FieldType->getAs<RecordType>();
463 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Douglas Gregor1d110e02010-07-01 14:13:13 +0000464 CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor();
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000465 if (!Dtor->isTrivial()) {
Fariborz Jahanian8b688ed2010-05-04 19:29:32 +0000466 if (Array) {
467 const llvm::Type *BasePtr = ConvertType(FieldType);
468 BasePtr = llvm::PointerType::getUnqual(BasePtr);
469 llvm::Value *BaseAddrPtr =
470 Builder.CreateBitCast(LV.getAddress(), BasePtr);
471 EmitCXXAggrDestructorCall(Dtor,
472 Array, BaseAddrPtr);
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000473 } else {
Fariborz Jahanian8b688ed2010-05-04 19:29:32 +0000474 EmitCXXDestructorCall(Dtor,
475 Dtor_Complete, /*ForVirtualBase=*/false,
476 LV.getAddress());
Chandler Carruthbc397cf2010-05-06 00:20:39 +0000477 }
478 }
479 }
Fariborz Jahanian109dfc62010-04-28 21:28:56 +0000480 }
481 FinishFunction();
482}
483
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +0000484bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
485 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
486 it++; it++;
487 const ABIArgInfo &AI = it->info;
488 // FIXME. Is this sufficient check?
489 return (AI.getKind() == ABIArgInfo::Indirect);
490}
491
Fariborz Jahanian15bd5882010-04-13 18:32:24 +0000492bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
493 if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
494 return false;
495 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
496 return FDTTy->getDecl()->hasObjectMember();
497 return false;
498}
499
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000500llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000501 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
502 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000503}
504
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000505QualType CodeGenFunction::TypeOfSelfObject() {
506 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
507 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +0000508 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
509 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +0000510 return PTy->getPointeeType();
511}
512
John McCalle68b9842010-12-04 03:11:00 +0000513LValue
514CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
515 // This is a special l-value that just issues sends when we load or
516 // store through it.
517
518 // For certain base kinds, we need to emit the base immediately.
519 llvm::Value *Base;
520 if (E->isSuperReceiver())
521 Base = LoadObjCSelf();
522 else if (E->isClassReceiver())
523 Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
524 else
525 Base = EmitScalarExpr(E->getBase());
526 return LValue::MakePropertyRef(E, Base);
527}
528
529static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
530 ReturnValueSlot Return,
531 QualType ResultType,
532 Selector S,
533 llvm::Value *Receiver,
534 const CallArgList &CallArgs) {
535 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000536 bool isClassMessage = OMD->isClassMethod();
537 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
John McCalle68b9842010-12-04 03:11:00 +0000538 return CGF.CGM.getObjCRuntime()
539 .GenerateMessageSendSuper(CGF, Return, ResultType,
540 S, OMD->getClassInterface(),
541 isCategoryImpl, Receiver,
542 isClassMessage, CallArgs);
Fariborz Jahanianf4695572009-03-20 19:18:21 +0000543}
544
John McCall119a1c62010-12-04 02:32:38 +0000545RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
546 ReturnValueSlot Return) {
547 const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000548 QualType ResultType;
549 Selector S;
550 if (E->isExplicitProperty()) {
551 const ObjCPropertyDecl *Property = E->getExplicitProperty();
552 S = Property->getGetterName();
553 ResultType = E->getType();
Mike Stumpb3589f42009-07-30 22:28:39 +0000554 } else {
John McCall12f78a62010-12-02 01:19:52 +0000555 const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
556 S = Getter->getSelector();
557 ResultType = Getter->getResultType(); // with reference!
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000558 }
John McCall12f78a62010-12-02 01:19:52 +0000559
John McCall119a1c62010-12-04 02:32:38 +0000560 llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
John McCalle68b9842010-12-04 03:11:00 +0000561
562 // Accesses to 'super' follow a different code path.
563 if (E->isSuperReceiver())
564 return GenerateMessageSendSuper(*this, Return, ResultType,
565 S, Receiver, CallArgList());
566
John McCall119a1c62010-12-04 02:32:38 +0000567 const ObjCInterfaceDecl *ReceiverClass
568 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000569 return CGM.getObjCRuntime().
570 GenerateMessageSend(*this, Return, ResultType, S,
571 Receiver, CallArgList(), ReceiverClass);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000572}
573
John McCall119a1c62010-12-04 02:32:38 +0000574void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
575 LValue Dst) {
576 const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
John McCall12f78a62010-12-02 01:19:52 +0000577 Selector S = E->getSetterSelector();
578 QualType ArgType;
579 if (E->isImplicitProperty()) {
580 const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
581 ObjCMethodDecl::param_iterator P = Setter->param_begin();
582 ArgType = (*P)->getType();
583 } else {
584 ArgType = E->getType();
585 }
586
John McCalle68b9842010-12-04 03:11:00 +0000587 CallArgList Args;
588 Args.push_back(std::make_pair(Src, ArgType));
589
590 llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
591 QualType ResultType = getContext().VoidTy;
592
John McCall12f78a62010-12-02 01:19:52 +0000593 if (E->isSuperReceiver()) {
John McCalle68b9842010-12-04 03:11:00 +0000594 GenerateMessageSendSuper(*this, ReturnValueSlot(),
595 ResultType, S, Receiver, Args);
John McCall12f78a62010-12-02 01:19:52 +0000596 return;
597 }
598
John McCall119a1c62010-12-04 02:32:38 +0000599 const ObjCInterfaceDecl *ReceiverClass
600 = (E->isClassReceiver() ? E->getClassReceiver() : 0);
John McCall12f78a62010-12-02 01:19:52 +0000601
John McCall12f78a62010-12-02 01:19:52 +0000602 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
John McCalle68b9842010-12-04 03:11:00 +0000603 ResultType, S, Receiver, Args,
604 ReceiverClass);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000605}
606
Chris Lattner74391b42009-03-22 21:03:39 +0000607void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +0000608 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000609 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000611 if (!EnumerationMutationFn) {
612 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
613 return;
614 }
615
John McCalld88687f2011-01-07 01:49:06 +0000616 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
617 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
Mike Stump1eb44332009-09-09 15:08:12 +0000618
Anders Carlssonf484c312008-08-31 02:33:12 +0000619 // Fast enumeration state.
620 QualType StateTy = getContext().getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +0000621 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +0000622 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Anders Carlssonf484c312008-08-31 02:33:12 +0000624 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000625 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +0000626
John McCalld88687f2011-01-07 01:49:06 +0000627 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +0000628 IdentifierInfo *II[] = {
629 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
630 &CGM.getContext().Idents.get("objects"),
631 &CGM.getContext().Idents.get("count")
632 };
633 Selector FastEnumSel =
634 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +0000635
636 QualType ItemsTy =
637 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +0000638 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +0000639 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +0000640 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000641
John McCalld88687f2011-01-07 01:49:06 +0000642 // Emit the collection pointer.
Anders Carlssonf484c312008-08-31 02:33:12 +0000643 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
Mike Stump1eb44332009-09-09 15:08:12 +0000644
John McCalld88687f2011-01-07 01:49:06 +0000645 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +0000646 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +0000647
648 // The first argument is a temporary of the enumeration-state type.
Mike Stump1eb44332009-09-09 15:08:12 +0000649 Args.push_back(std::make_pair(RValue::get(StatePtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000650 getContext().getPointerType(StateTy)));
Mike Stump1eb44332009-09-09 15:08:12 +0000651
John McCalld88687f2011-01-07 01:49:06 +0000652 // The second argument is a temporary array with space for NumItems
653 // pointers. We'll actually be loading elements from the array
654 // pointer written into the control state; this buffer is so that
655 // collections that *aren't* backed by arrays can still queue up
656 // batches of elements.
Mike Stump1eb44332009-09-09 15:08:12 +0000657 Args.push_back(std::make_pair(RValue::get(ItemsPtr),
Anders Carlssonf484c312008-08-31 02:33:12 +0000658 getContext().getPointerType(ItemsTy)));
Mike Stump1eb44332009-09-09 15:08:12 +0000659
John McCalld88687f2011-01-07 01:49:06 +0000660 // The third argument is the capacity of that temporary array.
Anders Carlssonf484c312008-08-31 02:33:12 +0000661 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000662 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Mike Stump1eb44332009-09-09 15:08:12 +0000663 Args.push_back(std::make_pair(RValue::get(Count),
Daniel Dunbar46f45b92008-09-09 01:06:48 +0000664 getContext().UnsignedLongTy));
Mike Stump1eb44332009-09-09 15:08:12 +0000665
John McCalld88687f2011-01-07 01:49:06 +0000666 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +0000667 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000668 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000669 getContext().UnsignedLongTy,
670 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000671 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +0000672
John McCalld88687f2011-01-07 01:49:06 +0000673 // The initial number of objects that were returned in the buffer.
674 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +0000675
John McCalld88687f2011-01-07 01:49:06 +0000676 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
677 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +0000678
John McCalld88687f2011-01-07 01:49:06 +0000679 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +0000680
John McCalld88687f2011-01-07 01:49:06 +0000681 // If the limit pointer was zero to begin with, the collection is
682 // empty; skip all this.
683 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
684 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000685
John McCalld88687f2011-01-07 01:49:06 +0000686 // Otherwise, initialize the loop.
687 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000688
John McCalld88687f2011-01-07 01:49:06 +0000689 // Save the initial mutations value. This is the value at an
690 // address that was written into the state object by
691 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +0000692 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000693 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000694 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000695 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +0000696
John McCalld88687f2011-01-07 01:49:06 +0000697 llvm::Value *initialMutations =
698 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +0000699
John McCalld88687f2011-01-07 01:49:06 +0000700 // Start looping. This is the point we return to whenever we have a
701 // fresh, non-empty batch of objects.
702 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
703 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000704
John McCalld88687f2011-01-07 01:49:06 +0000705 // The current index into the buffer.
706 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
707 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000708
John McCalld88687f2011-01-07 01:49:06 +0000709 // The current buffer size.
710 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
711 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
John McCalld88687f2011-01-07 01:49:06 +0000713 // Check whether the mutations value has changed from where it was
714 // at start. StateMutationsPtr should actually be invariant between
715 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000716 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +0000717 llvm::Value *currentMutations
718 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000719
John McCalld88687f2011-01-07 01:49:06 +0000720 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
721 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +0000722
John McCalld88687f2011-01-07 01:49:06 +0000723 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
724 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000725
John McCalld88687f2011-01-07 01:49:06 +0000726 // If so, call the enumeration-mutation function.
727 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000728 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +0000729 Builder.CreateBitCast(Collection,
Anders Carlsson2abd89c2008-08-31 04:05:03 +0000730 ConvertType(getContext().getObjCIdType()),
731 "tmp");
Daniel Dunbar2b2105e2009-02-03 23:55:40 +0000732 CallArgList Args2;
Mike Stump1eb44332009-09-09 15:08:12 +0000733 Args2.push_back(std::make_pair(RValue::get(V),
Daniel Dunbar2b2105e2009-02-03 23:55:40 +0000734 getContext().getObjCIdType()));
Mike Stumpf5408fe2009-05-16 07:57:57 +0000735 // FIXME: We shouldn't need to get the function info here, the runtime already
736 // should have computed it to build the function.
John McCall04a67a62010-02-05 21:31:56 +0000737 EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
Rafael Espindola264ba482010-03-30 20:24:48 +0000738 FunctionType::ExtInfo()),
Anders Carlssonf3c47c92009-12-24 19:25:24 +0000739 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
John McCalld88687f2011-01-07 01:49:06 +0000741 // Otherwise, or if the mutation function returns, just continue.
742 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000743
John McCalld88687f2011-01-07 01:49:06 +0000744 // Initialize the element variable.
745 RunCleanupsScope elementVariableScope(*this);
746 bool elementIsDecl;
747 LValue elementLValue;
748 QualType elementType;
749 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
750 EmitStmt(SD);
751 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
752
753 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
754 VK_LValue, SourceLocation());
755 elementLValue = EmitLValue(&tempDRE);
756 elementType = D->getType();
757 elementIsDecl = true;
758 } else {
759 elementLValue = LValue(); // suppress warning
760 elementType = cast<Expr>(S.getElement())->getType();
761 elementIsDecl = false;
762 }
763 const llvm::Type *convertedElementType = ConvertType(elementType);
764
765 // Fetch the buffer out of the enumeration state.
766 // TODO: this pointer should actually be invariant between
767 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +0000768 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +0000769 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +0000770 llvm::Value *EnumStateItems =
771 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +0000772
John McCalld88687f2011-01-07 01:49:06 +0000773 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000774 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +0000775 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
776 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000777
John McCalld88687f2011-01-07 01:49:06 +0000778 // Cast that value to the right type.
779 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
780 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +0000781
John McCalld88687f2011-01-07 01:49:06 +0000782 // Make sure we have an l-value. Yes, this gets evaluated every
783 // time through the loop.
784 if (!elementIsDecl)
785 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
Mike Stump1eb44332009-09-09 15:08:12 +0000786
John McCalld88687f2011-01-07 01:49:06 +0000787 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
Mike Stump1eb44332009-09-09 15:08:12 +0000788
John McCalld88687f2011-01-07 01:49:06 +0000789 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +0000790 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +0000791 {
792 RunCleanupsScope Scope(*this);
793 EmitStmt(S.getBody());
794 }
Anders Carlssonf484c312008-08-31 02:33:12 +0000795 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +0000796
John McCalld88687f2011-01-07 01:49:06 +0000797 // Destroy the element variable now.
798 elementVariableScope.ForceCleanup();
799
800 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +0000801 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +0000802
John McCalld88687f2011-01-07 01:49:06 +0000803 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +0000804
John McCalld88687f2011-01-07 01:49:06 +0000805 // First we check in the local buffer.
806 llvm::Value *indexPlusOne
807 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +0000808
John McCalld88687f2011-01-07 01:49:06 +0000809 // If we haven't overrun the buffer yet, we can continue.
810 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
811 LoopBodyBB, FetchMoreBB);
812
813 index->addIncoming(indexPlusOne, AfterBody.getBlock());
814 count->addIncoming(count, AfterBody.getBlock());
815
816 // Otherwise, we have to fetch more elements.
817 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000818
819 CountRV =
John McCallef072fd2010-05-22 01:48:05 +0000820 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +0000821 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +0000822 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000823 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
John McCalld88687f2011-01-07 01:49:06 +0000825 // If we got a zero count, we're done.
826 llvm::Value *refetchCount = CountRV.getScalarVal();
827
828 // (note that the message send might split FetchMoreBB)
829 index->addIncoming(zero, Builder.GetInsertBlock());
830 count->addIncoming(refetchCount, Builder.GetInsertBlock());
831
832 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
833 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Anders Carlssonf484c312008-08-31 02:33:12 +0000835 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +0000836 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +0000837
John McCalld88687f2011-01-07 01:49:06 +0000838 if (!elementIsDecl) {
Anders Carlssonf484c312008-08-31 02:33:12 +0000839 // If the element was not a declaration, set it to be null.
840
John McCalld88687f2011-01-07 01:49:06 +0000841 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
842 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
843 EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
Anders Carlssonf484c312008-08-31 02:33:12 +0000844 }
845
John McCallff8e1152010-07-23 21:56:41 +0000846 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000847}
848
Mike Stump1eb44332009-09-09 15:08:12 +0000849void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000850 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000851}
852
Mike Stump1eb44332009-09-09 15:08:12 +0000853void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +0000854 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
855}
856
Chris Lattner10cac6f2008-11-15 21:26:17 +0000857void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +0000858 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +0000859 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +0000860}
861
Ted Kremenek2979ec72008-04-09 15:51:31 +0000862CGObjCRuntime::~CGObjCRuntime() {}
John McCallf1549f62010-07-06 01:34:17 +0000863
864