blob: 26f678cc4eb0d22e4875b149b1f394d1f5ec6bd3 [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"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000019#include "llvm/ADT/STLExtras.h"
Chris Lattner41110242008-06-17 18:05:57 +000020
Anders Carlsson55085182007-08-21 17:43:55 +000021using namespace clang;
22using namespace CodeGen;
23
Chris Lattner8fdf3282008-06-24 17:04:18 +000024/// Emits an instance of NSConstantString representing the object.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000025llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E) {
26 std::string String(E->getString()->getStrData(), E->getString()->getByteLength());
27 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(String);
Daniel Dunbared7c6182008-08-20 00:28:19 +000028 // FIXME: This bitcast should just be made an invariant on the Runtime.
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000029 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000030}
31
32/// Emit a selector.
33llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
34 // Untyped selector.
35 // Note that this implementation allows for non-constant strings to be passed
36 // as arguments to @selector(). Currently, the only thing preventing this
37 // behaviour is the type checking in the front end.
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000038 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +000039}
40
Daniel Dunbared7c6182008-08-20 00:28:19 +000041llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
42 // FIXME: This should pass the Decl not the name.
43 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
44}
Chris Lattner8fdf3282008-06-24 17:04:18 +000045
46
Daniel Dunbar8f2926b2008-08-23 03:46:30 +000047RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E) {
Chris Lattner8fdf3282008-06-24 17:04:18 +000048 // Only the lookup mechanism and first two arguments of the method
49 // implementation vary between runtimes. We can get the receiver and
50 // arguments in generic code.
51
Daniel Dunbar208ff5e2008-08-11 18:12:00 +000052 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +000053 const Expr *ReceiverExpr = E->getReceiver();
54 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000055 bool isClassMessage = false;
Chris Lattner8fdf3282008-06-24 17:04:18 +000056 // Find the receiver
57 llvm::Value *Receiver;
58 if (!ReceiverExpr) {
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000059 const ObjCInterfaceDecl *OID = E->getClassInfo().first;
60
61 // Very special case, super send in class method. The receiver is
62 // self (the class object) and the send uses super semantics.
63 if (!OID) {
64 assert(!strcmp(E->getClassName()->getName(), "super") &&
65 "Unexpected missing class interface in message send.");
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +000066 isSuperMessage = true;
Daniel Dunbarf56f1912008-08-25 08:19:24 +000067 Receiver = LoadObjCSelf();
68 } else {
69 Receiver = Runtime.GetClass(Builder, OID);
Chris Lattner8fdf3282008-06-24 17:04:18 +000070 }
Daniel Dunbarf56f1912008-08-25 08:19:24 +000071
72 isClassMessage = true;
Chris Lattnerd9f69102008-08-10 01:53:14 +000073 } else if (const PredefinedExpr *PDE =
74 dyn_cast<PredefinedExpr>(E->getReceiver())) {
75 assert(PDE->getIdentType() == PredefinedExpr::ObjCSuper);
Chris Lattner8fdf3282008-06-24 17:04:18 +000076 isSuperMessage = true;
77 Receiver = LoadObjCSelf();
78 } else {
Daniel Dunbar2bedbf82008-08-12 05:28:47 +000079 Receiver = EmitScalarExpr(E->getReceiver());
Chris Lattner8fdf3282008-06-24 17:04:18 +000080 }
81
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000082 CallArgList Args;
83 for (CallExpr::const_arg_iterator i = E->arg_begin(), e = E->arg_end();
84 i != e; ++i)
85 EmitCallArg(*i, Args);
86
Chris Lattner8fdf3282008-06-24 17:04:18 +000087 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +000088 // super is only valid in an Objective-C method
89 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000090 return Runtime.GenerateMessageSendSuper(*this, E->getType(),
91 E->getSelector(),
Daniel Dunbarf56f1912008-08-25 08:19:24 +000092 OMD->getClassInterface(),
93 Receiver,
Daniel Dunbar19cd87e2008-08-30 03:02:31 +000094 isClassMessage,
95 Args);
Chris Lattner8fdf3282008-06-24 17:04:18 +000096 }
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +000097 return Runtime.GenerateMessageSend(*this, E->getType(), E->getSelector(),
98 Receiver, isClassMessage, Args);
Anders Carlsson55085182007-08-21 17:43:55 +000099}
100
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000101/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
102/// the LLVM function and sets the other context used by
103/// CodeGenFunction.
104
105// FIXME: This should really be merged with GenerateCode.
106void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD) {
Daniel Dunbar7ded7f42008-08-15 22:20:32 +0000107 CurFn = CGM.getObjCRuntime().GenerateMethod(OMD);
Chris Lattner41110242008-06-17 18:05:57 +0000108 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
109
110 // Create a marker to make it easy to insert allocas into the entryblock
111 // later. Don't create this with the builder, because we don't want it
112 // folded.
113 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
114 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
115 EntryBB);
116
117 FnRetTy = OMD->getResultType();
118 CurFuncDecl = OMD;
119
120 Builder.SetInsertPoint(EntryBB);
121
122 // Emit allocs for param decls. Give the LLVM Argument nodes names.
123 llvm::Function::arg_iterator AI = CurFn->arg_begin();
124
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000125 // Name the struct return argument.
Chris Lattner41110242008-06-17 18:05:57 +0000126 if (hasAggregateLLVMType(OMD->getResultType())) {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000127 AI->setName("agg.result");
Chris Lattner41110242008-06-17 18:05:57 +0000128 ++AI;
129 }
Chris Lattner41110242008-06-17 18:05:57 +0000130
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000131 // Add implicit parameters to the decl map.
132 EmitParmDecl(*OMD->getSelfDecl(), AI);
Chris Lattner41110242008-06-17 18:05:57 +0000133 ++AI;
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000134
135 EmitParmDecl(*OMD->getCmdDecl(), AI);
136 ++AI;
Chris Lattner41110242008-06-17 18:05:57 +0000137
138 for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
139 assert(AI != CurFn->arg_end() && "Argument mismatch!");
140 EmitParmDecl(*OMD->getParamDecl(i), AI);
141 }
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000142 assert(AI == CurFn->arg_end() && "Argument mismatch");
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
146/// its pointer, name, and types registered in the class struture.
147void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
148 StartObjCMethod(OMD);
149 EmitStmt(OMD->getBody());
150
151 const CompoundStmt *S = dyn_cast<CompoundStmt>(OMD->getBody());
152 if (S) {
153 FinishFunction(S->getRBracLoc());
154 } else {
155 FinishFunction();
156 }
157}
158
159// FIXME: I wasn't sure about the synthesis approach. If we end up
160// generating an AST for the whole body we can just fall back to
161// having a GenerateFunction which takes the body Stmt.
162
163/// GenerateObjCGetter - Generate an Objective-C property getter
164/// function. The given Decl must be either an ObjCCategoryImplDecl
165/// or an ObjCImplementationDecl.
166void CodeGenFunction::GenerateObjCGetter(const ObjCPropertyImplDecl *PID) {
167 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
168 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
169 assert(OMD && "Invalid call to generate getter (empty method)");
170 // FIXME: This is rather murky, we create this here since they will
171 // not have been created by Sema for us.
172 OMD->createImplicitParams(getContext());
173 StartObjCMethod(OMD);
174
175 // FIXME: What about nonatomic?
176 SourceLocation Loc = PD->getLocation();
177 ValueDecl *Self = OMD->getSelfDecl();
178 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
179 DeclRefExpr Base(Self, Self->getType(), Loc);
180 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
181 true, true);
182 ReturnStmt Return(Loc, &IvarRef);
183 EmitStmt(&Return);
184
185 FinishFunction();
186}
187
188/// GenerateObjCSetter - Generate an Objective-C property setter
189/// function. The given Decl must be either an ObjCCategoryImplDecl
190/// or an ObjCImplementationDecl.
191void CodeGenFunction::GenerateObjCSetter(const ObjCPropertyImplDecl *PID) {
192 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
193 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
194 assert(OMD && "Invalid call to generate setter (empty method)");
195 // FIXME: This is rather murky, we create this here since they will
196 // not have been created by Sema for us.
197 OMD->createImplicitParams(getContext());
198 StartObjCMethod(OMD);
199
200 switch (PD->getSetterKind()) {
201 case ObjCPropertyDecl::Assign: break;
202 case ObjCPropertyDecl::Copy:
203 CGM.ErrorUnsupported(PID, "Obj-C setter with 'copy'");
204 break;
205 case ObjCPropertyDecl::Retain:
206 CGM.ErrorUnsupported(PID, "Obj-C setter with 'retain'");
207 break;
208 }
209
210 // FIXME: What about nonatomic?
211 SourceLocation Loc = PD->getLocation();
212 ValueDecl *Self = OMD->getSelfDecl();
213 ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
214 DeclRefExpr Base(Self, Self->getType(), Loc);
215 ParmVarDecl *ArgDecl = OMD->getParamDecl(0);
216 DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), Loc);
217 ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base,
218 true, true);
219 BinaryOperator Assign(&IvarRef, &Arg, BinaryOperator::Assign,
220 Ivar->getType(), Loc);
221 EmitStmt(&Assign);
222
223 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +0000224}
225
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000226llvm::Value *CodeGenFunction::LoadObjCSelf(void) {
227 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
228 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +0000229}
230
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000231RValue CodeGenFunction::EmitObjCPropertyGet(const ObjCPropertyRefExpr *E) {
232 // Determine getter selector.
233 Selector S;
234 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(E->getDecl())) {
235 S = MD->getSelector();
236 } else {
237 S = cast<ObjCPropertyDecl>(E->getDecl())->getGetterName();
238 }
239
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000240 return CGM.getObjCRuntime().
241 GenerateMessageSend(*this, E->getType(), S,
242 EmitScalarExpr(E->getBase()),
243 false, CallArgList());
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000244}
245
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000246void CodeGenFunction::EmitObjCPropertySet(const ObjCPropertyRefExpr *E,
247 RValue Src) {
Daniel Dunbar7f8ea5c2008-08-30 05:35:15 +0000248 Selector S;
249 if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(E->getDecl())) {
250 S = PD->getSetterName();
251 } else {
252 // FIXME: How can we have a method decl here?
253 ErrorUnsupported(E, "Objective-C property setter call");
254 return;
255 }
256
257 CallArgList Args;
258 EmitCallArg(Src, E->getType(), Args);
259 CGM.getObjCRuntime().GenerateMessageSend(*this, getContext().VoidTy, S,
260 EmitScalarExpr(E->getBase()),
261 false, Args);
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000262}
263
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000264void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S)
265{
Anders Carlssonf484c312008-08-31 02:33:12 +0000266 llvm::Value *DeclAddress;
267 QualType ElementTy;
268
269 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
270 EmitStmt(SD);
271
272 ElementTy = cast<ValueDecl>(SD->getDecl())->getType();
273 DeclAddress = LocalDeclMap[SD->getDecl()];
274 } else {
275 ElementTy = cast<Expr>(S.getElement())->getType();
276 DeclAddress = 0;
277 }
278
279 // Fast enumeration state.
280 QualType StateTy = getContext().getObjCFastEnumerationStateType();
281 llvm::AllocaInst *StatePtr = CreateTempAlloca(ConvertType(StateTy),
282 "state.ptr");
283 StatePtr->setAlignment(getContext().getTypeAlign(StateTy) >> 3);
284 EmitMemSetToZero(StatePtr,StateTy);
285
286 // Number of elements in the items array.
287 static const unsigned NumItems = 2;
288
289 // Get selector
290 llvm::SmallVector<IdentifierInfo*, 3> II;
291 II.push_back(&CGM.getContext().Idents.get("countByEnumeratingWithState"));
292 II.push_back(&CGM.getContext().Idents.get("objects"));
293 II.push_back(&CGM.getContext().Idents.get("count"));
294 Selector FastEnumSel = CGM.getContext().Selectors.getSelector(II.size(),
295 &II[0]);
296
297 QualType ItemsTy =
298 getContext().getConstantArrayType(getContext().getObjCIdType(),
299 llvm::APInt(32, NumItems),
300 ArrayType::Normal, 0);
301 llvm::Value *ItemsPtr = CreateTempAlloca(ConvertType(ItemsTy), "items.ptr");
302
303 llvm::Value *Collection = EmitScalarExpr(S.getCollection());
304
305 CallArgList Args;
306 Args.push_back(std::make_pair(StatePtr,
307 getContext().getPointerType(StateTy)));
308
309 Args.push_back(std::make_pair(ItemsPtr,
310 getContext().getPointerType(ItemsTy)));
311
312 const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
313 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
314 Args.push_back(std::make_pair(Count, getContext().UnsignedLongTy));
315
316 RValue CountRV =
317 CGM.getObjCRuntime().GenerateMessageSend(*this,
318 getContext().UnsignedLongTy,
319 FastEnumSel,
320 Collection, false, Args);
321
322 llvm::Value *LimitPtr = CreateTempAlloca(UnsignedLongLTy, "limit.ptr");
323 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
324
325 llvm::BasicBlock *NoElements = llvm::BasicBlock::Create("noelements");
326 llvm::BasicBlock *LoopStart = llvm::BasicBlock::Create("loopstart");
327
328 llvm::Value *Limit = Builder.CreateLoad(LimitPtr);
329 llvm::Value *Zero = llvm::Constant::getNullValue(UnsignedLongLTy);
330
331 llvm::Value *IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
332 Builder.CreateCondBr(IsZero, NoElements, LoopStart);
333
334 EmitBlock(LoopStart);
335
336 llvm::BasicBlock *LoopBody = llvm::BasicBlock::Create("loopbody");
337
338 llvm::Value *CounterPtr = CreateTempAlloca(UnsignedLongLTy, "counter.ptr");
339 Builder.CreateStore(Zero, CounterPtr);
340
341 EmitBlock(LoopBody);
342
343 llvm::Value *StateItemsPtr =
344 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
345
346 llvm::Value *Counter = Builder.CreateLoad(CounterPtr, "counter");
347
348 llvm::Value *EnumStateItems = Builder.CreateLoad(StateItemsPtr,
349 "stateitems");
350
351 llvm::Value *CurrentItemPtr =
352 Builder.CreateGEP(EnumStateItems, Counter, "currentitem.ptr");
353
354 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr, "currentitem");
355
356 // Cast the item to the right type.
357 CurrentItem = Builder.CreateBitCast(CurrentItem,
358 ConvertType(ElementTy), "tmp");
359
360 if (!DeclAddress) {
361 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
362
363 // Set the value to null.
364 Builder.CreateStore(CurrentItem, LV.getAddress());
365 } else
366 Builder.CreateStore(CurrentItem, DeclAddress);
367
368 // Increment the counter.
369 Counter = Builder.CreateAdd(Counter,
370 llvm::ConstantInt::get(UnsignedLongLTy, 1));
371 Builder.CreateStore(Counter, CounterPtr);
372
373 llvm::BasicBlock *LoopEnd = llvm::BasicBlock::Create("loopend");
374 llvm::BasicBlock *AfterBody = llvm::BasicBlock::Create("afterbody");
375
376 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
377
378 EmitStmt(S.getBody());
379
380 BreakContinueStack.pop_back();
381
382 EmitBlock(AfterBody);
383
384 llvm::BasicBlock *FetchMore = llvm::BasicBlock::Create("fetchmore");
385
386 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, Limit, "isless");
387 Builder.CreateCondBr(IsLess, LoopBody, FetchMore);
388
389 // Fetch more elements.
390 EmitBlock(FetchMore);
391
392 CountRV =
393 CGM.getObjCRuntime().GenerateMessageSend(*this,
394 getContext().UnsignedLongTy,
395 FastEnumSel,
396 Collection, false, Args);
397 Builder.CreateStore(CountRV.getScalarVal(), LimitPtr);
398 Limit = Builder.CreateLoad(LimitPtr);
399
400 IsZero = Builder.CreateICmpEQ(Limit, Zero, "iszero");
401 Builder.CreateCondBr(IsZero, NoElements, LoopStart);
402
403 // No more elements.
404 EmitBlock(NoElements);
405
406 if (!DeclAddress) {
407 // If the element was not a declaration, set it to be null.
408
409 LValue LV = EmitLValue(cast<Expr>(S.getElement()));
410
411 // Set the value to null.
412 Builder.CreateStore(llvm::Constant::getNullValue(ConvertType(ElementTy)),
413 LV.getAddress());
414 }
415
416 EmitBlock(LoopEnd);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000417}
418
Ted Kremenek2979ec72008-04-09 15:51:31 +0000419CGObjCRuntime::~CGObjCRuntime() {}