blob: b56b050c144374efe856d01c4145d01f7ae7df7c [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
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.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-function state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Eli Friedman3f2af102008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner31a09842008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Devang Pateld9363c32007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patelc049e4f2007-10-08 20:57:48 +000026 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattner41110242008-06-17 18:05:57 +000027 CaseRangeBlock(NULL) {
28 LLVMIntTy = ConvertType(getContext().IntTy);
29 LLVMPointerWidth = Target.getPointerWidth(0);
30}
Reid Spencer5f016e22007-07-11 17:01:13 +000031
32ASTContext &CodeGenFunction::getContext() const {
33 return CGM.getContext();
34}
35
36
37llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38 llvm::BasicBlock *&BB = LabelMap[S];
39 if (BB) return BB;
40
41 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000042 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000045llvm::Constant *
Steve Naroff248a7532008-04-15 22:42:06 +000046CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000047 return cast<llvm::Constant>(LocalDeclMap[BVD]);
48}
Reid Spencer5f016e22007-07-11 17:01:13 +000049
Anders Carlssondde0a942008-09-11 09:15:33 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51{
52 return LocalDeclMap[VD];
53}
54
Reid Spencer5f016e22007-07-11 17:01:13 +000055const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56 return CGM.getTypes().ConvertType(T);
57}
58
Chris Lattner41110242008-06-17 18:05:57 +000059bool CodeGenFunction::isObjCPointerType(QualType T) {
60 // All Objective-C types are pointers.
61 return T->isObjCInterfaceType() ||
62 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63}
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner41110242008-06-17 18:05:57 +000066 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
67 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +000068}
69
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000070void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000071 // Finish emission of indirect switches.
72 EmitIndirectSwitches();
73
Chris Lattnerda138702007-07-16 21:28:45 +000074 assert(BreakContinueStack.empty() &&
75 "mismatched push/pop in break/continue stack!");
Daniel Dunbar5ca20842008-09-09 21:00:17 +000076
Daniel Dunbarb01d1912008-09-27 07:15:59 +000077 // Emit function epilog (to return). This has the nice side effect
78 // of also automatically handling code that falls off the end.
79 EmitBlock(ReturnBlock);
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +000080
81 // Emit debug descriptor for function end.
82 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
83 DI->setLocation(EndLoc);
84 DI->EmitRegionEnd(CurFn, Builder);
85 }
86
Daniel Dunbar17b708d2008-09-09 23:27:19 +000087 EmitFunctionEpilog(FnRetTy, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +000088
Chris Lattner5a2fa142007-12-02 06:32:24 +000089 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
90 AllocaInsertPt->eraseFromParent();
91 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000092}
93
Daniel Dunbar7c086512008-09-09 23:14:03 +000094void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
95 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +000096 const FunctionArgList &Args,
97 SourceLocation StartLoc) {
Daniel Dunbar7c086512008-09-09 23:14:03 +000098 CurFuncDecl = D;
99 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000100 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000101 assert(CurFn->isDeclaration() && "Function already has body?");
102
Daniel Dunbar55e87422008-11-11 02:29:29 +0000103 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000104
Chris Lattner41110242008-06-17 18:05:57 +0000105 // Create a marker to make it easy to insert allocas into the entryblock
106 // later. Don't create this with the builder, because we don't want it
107 // folded.
108 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
109 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
110 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000111
Daniel Dunbar55e87422008-11-11 02:29:29 +0000112 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000113 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000114 if (!RetTy->isVoidType())
115 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000116
Chris Lattner41110242008-06-17 18:05:57 +0000117 Builder.SetInsertPoint(EntryBB);
118
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000119 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000120 // FIXME: The cast here is a huge hack.
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000121 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
122 DI->setLocation(StartLoc);
123 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor2e1cd422008-11-17 14:58:09 +0000124 DI->EmitFunctionStart(FD->getIdentifierName(), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000125 } else {
126 // Just use LLVM function name.
127 DI->EmitFunctionStart(Fn->getName().c_str(),
128 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000129 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000130 }
131
Daniel Dunbar17b708d2008-09-09 23:27:19 +0000132 EmitFunctionProlog(CurFn, FnRetTy, Args);
Daniel Dunbar7c086512008-09-09 23:14:03 +0000133}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000134
Daniel Dunbar7c086512008-09-09 23:14:03 +0000135void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
136 llvm::Function *Fn) {
137 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000138 if (FD->getNumParams()) {
139 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
140 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000141
142 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
143 Args.push_back(std::make_pair(FD->getParamDecl(i),
144 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000145 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000146
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000147 StartFunction(FD, FD->getResultType(), Fn, Args,
148 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000149
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000150 EmitStmt(FD->getBody());
151
152 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
153 if (S) {
154 FinishFunction(S->getRBracLoc());
155 } else {
156 FinishFunction();
157 }
Chris Lattner41110242008-06-17 18:05:57 +0000158}
159
Chris Lattner0946ccd2008-11-11 07:41:27 +0000160/// ContainsLabel - Return true if the statement contains a label in it. If
161/// this statement is not executed normally, it not containing a label means
162/// that we can just remove the code.
163bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
164 // Null statement, not a label!
165 if (S == 0) return false;
166
167 // If this is a label, we have to emit the code, consider something like:
168 // if (0) { ... foo: bar(); } goto foo;
169 if (isa<LabelStmt>(S))
170 return true;
171
172 // If this is a case/default statement, and we haven't seen a switch, we have
173 // to emit the code.
174 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
175 return true;
176
177 // If this is a switch statement, we want to ignore cases below it.
178 if (isa<SwitchStmt>(S))
179 IgnoreCaseStmts = true;
180
181 // Scan subexpressions for verboten labels.
182 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
183 I != E; ++I)
184 if (ContainsLabel(*I, IgnoreCaseStmts))
185 return true;
186
187 return false;
188}
189
Chris Lattner31a09842008-11-12 08:04:58 +0000190
191/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
192/// a constant, or if it does but contains a label, return 0. If it constant
193/// folds to 'true' and does not contain a label, return 1, if it constant folds
194/// to 'false' and does not contain a label, return -1.
195int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
196 APValue V;
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000197
198 // FIXME: Rename and handle conversion of other evaluatable things
199 // to bool.
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000200 bool isEvaluated;
201 if (!Cond->Evaluate(V, getContext(), &isEvaluated) || !V.isInt() ||
202 !isEvaluated)
203 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000204
205 if (CodeGenFunction::ContainsLabel(Cond))
206 return 0; // Contains a label.
207
208 return V.getInt().getBoolValue() ? 1 : -1;
209}
210
211
212/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
213/// statement) to the specified blocks. Based on the condition, this might try
214/// to simplify the codegen of the conditional based on the branch.
215///
216void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
217 llvm::BasicBlock *TrueBlock,
218 llvm::BasicBlock *FalseBlock) {
219 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
220 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
221
222 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
223 // Handle X && Y in a condition.
224 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
225 // If we have "1 && X", simplify the code. "0 && X" would have constant
226 // folded if the case was simple enough.
227 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
228 // br(1 && X) -> br(X).
229 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
230 }
231
232 // If we have "X && 1", simplify the code to use an uncond branch.
233 // "X && 0" would have been constant folded to 0.
234 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
235 // br(X && 1) -> br(X).
236 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
237 }
238
239 // Emit the LHS as a conditional. If the LHS conditional is false, we
240 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000241 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000242 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
243 EmitBlock(LHSTrue);
244
245 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
246 return;
247 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
248 // If we have "0 || X", simplify the code. "1 || X" would have constant
249 // folded if the case was simple enough.
250 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
251 // br(0 || X) -> br(X).
252 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
253 }
254
255 // If we have "X || 0", simplify the code to use an uncond branch.
256 // "X || 1" would have been constant folded to 1.
257 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
258 // br(X || 0) -> br(X).
259 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
260 }
261
262 // Emit the LHS as a conditional. If the LHS conditional is true, we
263 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000264 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000265 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
266 EmitBlock(LHSFalse);
267
268 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
269 return;
270 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000271 }
272
273 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
274 // br(!x, t, f) -> br(x, f, t)
275 if (CondUOp->getOpcode() == UnaryOperator::LNot)
276 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000277 }
278
Daniel Dunbar09b14892008-11-12 10:30:32 +0000279 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
280 // Handle ?: operator.
281
282 // Just ignore GNU ?: extension.
283 if (CondOp->getLHS()) {
284 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
285 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
286 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
287 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
288 EmitBlock(LHSBlock);
289 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
290 EmitBlock(RHSBlock);
291 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
292 return;
293 }
294 }
295
Chris Lattner31a09842008-11-12 08:04:58 +0000296 // Emit the code with the fully general case.
297 llvm::Value *CondV = EvaluateExprAsBool(Cond);
298 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
299}
300
Devang Patel88a981b2007-11-01 19:11:01 +0000301/// getCGRecordLayout - Return record layout info.
302const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000303 QualType Ty) {
304 const RecordType *RTy = Ty->getAsRecordType();
305 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000306
Chris Lattneraf319132008-02-05 06:55:31 +0000307 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000308}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000309
Daniel Dunbar488e9932008-08-16 00:56:44 +0000310/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000311/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000312void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
313 bool OmitOnError) {
314 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000315}
316
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000317unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
318 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
319 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
320}
321
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000322void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
323{
324 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
325 if (DestPtr->getType() != BP)
326 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
327
328 // Get size and alignment info for this aggregate.
329 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
330
331 // FIXME: Handle variable sized types.
332 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
333
334 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
335 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
336 // TypeInfo.first describes size in bits.
337 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
338 llvm::ConstantInt::get(llvm::Type::Int32Ty,
339 TypeInfo.second/8));
340}
341
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000342void CodeGenFunction::EmitIndirectSwitches() {
343 llvm::BasicBlock *Default;
344
Daniel Dunbar76526a52008-08-04 17:24:44 +0000345 if (IndirectSwitches.empty())
346 return;
347
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000348 if (!LabelIDs.empty()) {
349 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
350 } else {
351 // No possible targets for indirect goto, just emit an infinite
352 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000353 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000354 llvm::BranchInst::Create(Default, Default);
355 }
356
357 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
358 e = IndirectSwitches.end(); i != e; ++i) {
359 llvm::SwitchInst *I = *i;
360
361 I->setSuccessor(0, Default);
362 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
363 LE = LabelIDs.end(); LI != LE; ++LI) {
364 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
365 LI->second),
366 getBasicBlockForLabel(LI->first));
367 }
368 }
369}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000370
371llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
372{
373 // FIXME: This entire method is hardcoded for 32-bit X86.
374
375 const char *TargetPrefix = getContext().Target.getTargetPrefix();
376
377 if (strcmp(TargetPrefix, "x86") != 0 ||
378 getContext().Target.getPointerWidth(0) != 32)
379 return 0;
380
381 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
382 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
383
384 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
385 "ap");
386 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
387 llvm::Value *AddrTyped =
388 Builder.CreateBitCast(Addr,
389 llvm::PointerType::getUnqual(ConvertType(Ty)));
390
391 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
392 const unsigned ArgumentSizeInBytes = 4;
393 if (SizeInBytes < ArgumentSizeInBytes)
394 SizeInBytes = ArgumentSizeInBytes;
395
396 llvm::Value *NextAddr =
397 Builder.CreateGEP(Addr,
398 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
399 "ap.next");
400 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
401
402 return AddrTyped;
403}
404