blob: 2050d12e466bbcb1f60ec02a9b3f83527cdb9f9e [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"
Anders Carlsson2b77ba82009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Devang Pateld9363c32007-09-28 21:49:18 +000022#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000023#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024using namespace clang;
25using namespace CodeGen;
26
27CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000030 Builder(cgm.getModule().getContext()),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000031 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
32 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000033 LLVMIntTy = ConvertType(getContext().IntTy);
34 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000035}
Reid Spencer5f016e22007-07-11 17:01:13 +000036
37ASTContext &CodeGenFunction::getContext() const {
38 return CGM.getContext();
39}
40
41
42llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
43 llvm::BasicBlock *&BB = LabelMap[S];
44 if (BB) return BB;
45
46 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000047 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Daniel Dunbar0096acf2009-02-25 19:24:29 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
51 llvm::Value *Res = LocalDeclMap[VD];
52 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
53 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000054}
Reid Spencer5f016e22007-07-11 17:01:13 +000055
Daniel Dunbar0096acf2009-02-25 19:24:29 +000056llvm::Constant *
57CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
58 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000059}
60
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000061const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
62 return CGM.getTypes().ConvertTypeForMem(T);
63}
64
Reid Spencer5f016e22007-07-11 17:01:13 +000065const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
66 return CGM.getTypes().ConvertType(T);
67}
68
69bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Mike Stumpf5408fe2009-05-16 07:57:57 +000070 // FIXME: Use positive checks instead of negative ones to be more robust in
71 // the face of extension.
Daniel Dunbar89588912009-02-26 20:52:22 +000072 return !T->hasPointerRepresentation() &&!T->isRealType() &&
73 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000074 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000075}
76
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000077void CodeGenFunction::EmitReturnBlock() {
78 // For cleanliness, we try to avoid emitting the return block for
79 // simple cases.
80 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
81
82 if (CurBB) {
83 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
84
Daniel Dunbar96e18b02009-07-19 08:24:34 +000085 // We have a valid insert point, reuse it if it is empty or there are no
86 // explicit jumps to the return block.
87 if (CurBB->empty() || ReturnBlock->use_empty()) {
88 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000089 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000090 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000091 EmitBlock(ReturnBlock);
92 return;
93 }
94
95 // Otherwise, if the return block is the target of a single direct
96 // branch then we can just put the code in that block instead. This
97 // cleans up functions which started with a unified return block.
98 if (ReturnBlock->hasOneUse()) {
99 llvm::BranchInst *BI =
100 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
101 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
102 // Reset insertion point and delete the branch.
103 Builder.SetInsertPoint(BI->getParent());
104 BI->eraseFromParent();
105 delete ReturnBlock;
106 return;
107 }
108 }
109
Mike Stumpf5408fe2009-05-16 07:57:57 +0000110 // FIXME: We are at an unreachable point, there is no reason to emit the block
111 // unless it has uses. However, we still need a place to put the debug
112 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000113
114 EmitBlock(ReturnBlock);
115}
116
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000117void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000118 // Finish emission of indirect switches.
119 EmitIndirectSwitches();
120
Chris Lattnerda138702007-07-16 21:28:45 +0000121 assert(BreakContinueStack.empty() &&
122 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000123 assert(BlockScopes.empty() &&
124 "did not remove all blocks from block scope map!");
125 assert(CleanupEntries.empty() &&
126 "mismatched push/pop in cleanup stack!");
127
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000128 // Emit function epilog (to return).
129 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000130
131 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000132 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000133 DI->setLocation(EndLoc);
134 DI->EmitRegionEnd(CurFn, Builder);
135 }
136
Daniel Dunbar88b53962009-02-02 22:03:45 +0000137 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000138
Chris Lattner5a2fa142007-12-02 06:32:24 +0000139 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000140 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000141 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000142 Ptr->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000143}
144
Daniel Dunbar7c086512008-09-09 23:14:03 +0000145void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
146 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000147 const FunctionArgList &Args,
148 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000149 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000150 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000151 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000152 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000153 assert(CurFn->isDeclaration() && "Function already has body?");
154
Daniel Dunbar55e87422008-11-11 02:29:29 +0000155 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000156
Chris Lattner41110242008-06-17 18:05:57 +0000157 // Create a marker to make it easy to insert allocas into the entryblock
158 // later. Don't create this with the builder, because we don't want it
159 // folded.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000160 llvm::Value *Undef = VMContext.getUndef(llvm::Type::Int32Ty);
Chris Lattnerf1466842009-03-22 00:24:14 +0000161 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
Chris Lattner41110242008-06-17 18:05:57 +0000162 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000163 if (Builder.isNamePreserving())
164 AllocaInsertPt->setName("allocapt");
165
Daniel Dunbar55e87422008-11-11 02:29:29 +0000166 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000167 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000168 if (!RetTy->isVoidType())
169 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000170
Chris Lattner41110242008-06-17 18:05:57 +0000171 Builder.SetInsertPoint(EntryBB);
172
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000173 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000174 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000175 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000176 DI->setLocation(StartLoc);
177 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6ec36682009-02-18 23:53:56 +0000178 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000179 } else {
180 // Just use LLVM function name.
181 DI->EmitFunctionStart(Fn->getName().c_str(),
182 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000183 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000184 }
185
Daniel Dunbar88b53962009-02-02 22:03:45 +0000186 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000187 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000188 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000189
190 // If any of the arguments have a variably modified type, make sure to
191 // emit the type size.
192 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
193 i != e; ++i) {
194 QualType Ty = i->second;
195
196 if (Ty->isVariablyModifiedType())
197 EmitVLASize(Ty);
198 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000199}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000200
Daniel Dunbar7c086512008-09-09 23:14:03 +0000201void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
202 llvm::Function *Fn) {
Anders Carlssone896d982009-02-13 08:11:52 +0000203 // Check if we should generate debug info for this function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000204 if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000205 DebugInfo = CGM.getDebugInfo();
206
Daniel Dunbar7c086512008-09-09 23:14:03 +0000207 FunctionArgList Args;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000208
209 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
210 if (MD->isInstance()) {
211 // Create the implicit 'this' decl.
212 // FIXME: I'm not entirely sure I like using a fake decl just for code
213 // generation. Maybe we can come up with a better way?
214 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
215 &getContext().Idents.get("this"),
216 MD->getThisType(getContext()));
217 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
218 }
219 }
220
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000221 if (FD->getNumParams()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000222 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000223 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000224
225 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
226 Args.push_back(std::make_pair(FD->getParamDecl(i),
227 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000228 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000229
Sebastian Redld3a413d2009-04-26 20:35:05 +0000230 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000231 if (const CompoundStmt *S = FD->getCompoundBody()) {
Sebastian Redld3a413d2009-04-26 20:35:05 +0000232 StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
233 EmitStmt(S);
234 FinishFunction(S->getRBracLoc());
235 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000236
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000237 // Destroy the 'this' declaration.
238 if (CXXThisDecl)
239 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000240}
241
Chris Lattner0946ccd2008-11-11 07:41:27 +0000242/// ContainsLabel - Return true if the statement contains a label in it. If
243/// this statement is not executed normally, it not containing a label means
244/// that we can just remove the code.
245bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
246 // Null statement, not a label!
247 if (S == 0) return false;
248
249 // If this is a label, we have to emit the code, consider something like:
250 // if (0) { ... foo: bar(); } goto foo;
251 if (isa<LabelStmt>(S))
252 return true;
253
254 // If this is a case/default statement, and we haven't seen a switch, we have
255 // to emit the code.
256 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
257 return true;
258
259 // If this is a switch statement, we want to ignore cases below it.
260 if (isa<SwitchStmt>(S))
261 IgnoreCaseStmts = true;
262
263 // Scan subexpressions for verboten labels.
264 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
265 I != E; ++I)
266 if (ContainsLabel(*I, IgnoreCaseStmts))
267 return true;
268
269 return false;
270}
271
Chris Lattner31a09842008-11-12 08:04:58 +0000272
273/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
274/// a constant, or if it does but contains a label, return 0. If it constant
275/// folds to 'true' and does not contain a label, return 1, if it constant folds
276/// to 'false' and does not contain a label, return -1.
277int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000278 // FIXME: Rename and handle conversion of other evaluatable things
279 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000280 Expr::EvalResult Result;
281 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
282 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000283 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000284
285 if (CodeGenFunction::ContainsLabel(Cond))
286 return 0; // Contains a label.
287
Anders Carlsson64712f12008-12-01 02:46:24 +0000288 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000289}
290
291
292/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
293/// statement) to the specified blocks. Based on the condition, this might try
294/// to simplify the codegen of the conditional based on the branch.
295///
296void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
297 llvm::BasicBlock *TrueBlock,
298 llvm::BasicBlock *FalseBlock) {
299 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
300 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
301
302 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
303 // Handle X && Y in a condition.
304 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
305 // If we have "1 && X", simplify the code. "0 && X" would have constant
306 // folded if the case was simple enough.
307 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
308 // br(1 && X) -> br(X).
309 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
310 }
311
312 // If we have "X && 1", simplify the code to use an uncond branch.
313 // "X && 0" would have been constant folded to 0.
314 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
315 // br(X && 1) -> br(X).
316 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
317 }
318
319 // Emit the LHS as a conditional. If the LHS conditional is false, we
320 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000321 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000322 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
323 EmitBlock(LHSTrue);
324
325 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
326 return;
327 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
328 // If we have "0 || X", simplify the code. "1 || X" would have constant
329 // folded if the case was simple enough.
330 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
331 // br(0 || X) -> br(X).
332 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
333 }
334
335 // If we have "X || 0", simplify the code to use an uncond branch.
336 // "X || 1" would have been constant folded to 1.
337 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
338 // br(X || 0) -> br(X).
339 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
340 }
341
342 // Emit the LHS as a conditional. If the LHS conditional is true, we
343 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000344 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000345 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
346 EmitBlock(LHSFalse);
347
348 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
349 return;
350 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000351 }
352
353 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
354 // br(!x, t, f) -> br(x, f, t)
355 if (CondUOp->getOpcode() == UnaryOperator::LNot)
356 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000357 }
358
Daniel Dunbar09b14892008-11-12 10:30:32 +0000359 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
360 // Handle ?: operator.
361
362 // Just ignore GNU ?: extension.
363 if (CondOp->getLHS()) {
364 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
365 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
366 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
367 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
368 EmitBlock(LHSBlock);
369 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
370 EmitBlock(RHSBlock);
371 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
372 return;
373 }
374 }
375
Chris Lattner31a09842008-11-12 08:04:58 +0000376 // Emit the code with the fully general case.
377 llvm::Value *CondV = EvaluateExprAsBool(Cond);
378 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
379}
380
Devang Patel88a981b2007-11-01 19:11:01 +0000381/// getCGRecordLayout - Return record layout info.
382const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000383 QualType Ty) {
Ted Kremenek35366a62009-07-17 17:50:17 +0000384 const RecordType *RTy = Ty->getAsRecordType();
Chris Lattneraf319132008-02-05 06:55:31 +0000385 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000386
Chris Lattneraf319132008-02-05 06:55:31 +0000387 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000388}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000389
Daniel Dunbar488e9932008-08-16 00:56:44 +0000390/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000391/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000392void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
393 bool OmitOnError) {
394 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000395}
396
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000397unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
398 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
399 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
400}
401
Chris Lattner88207c92009-04-21 17:59:23 +0000402void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000403 const llvm::Type *BP = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000404 if (DestPtr->getType() != BP)
405 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
406
407 // Get size and alignment info for this aggregate.
408 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
409
Chris Lattner88207c92009-04-21 17:59:23 +0000410 // Don't bother emitting a zero-byte memset.
411 if (TypeInfo.first == 0)
412 return;
413
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000414 // FIXME: Handle variable sized types.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000415 const llvm::Type *IntPtr = VMContext.getIntegerType(LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000416
417 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson69243822009-07-13 04:10:07 +0000418 getLLVMContext().getNullValue(llvm::Type::Int8Ty),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000419 // TypeInfo.first describes size in bits.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000420 VMContext.getConstantInt(IntPtr, TypeInfo.first/8),
421 VMContext.getConstantInt(llvm::Type::Int32Ty,
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000422 TypeInfo.second/8));
423}
424
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000425void CodeGenFunction::EmitIndirectSwitches() {
426 llvm::BasicBlock *Default;
427
Daniel Dunbar76526a52008-08-04 17:24:44 +0000428 if (IndirectSwitches.empty())
429 return;
430
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000431 if (!LabelIDs.empty()) {
432 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
433 } else {
434 // No possible targets for indirect goto, just emit an infinite
435 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000436 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000437 llvm::BranchInst::Create(Default, Default);
438 }
439
440 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
441 e = IndirectSwitches.end(); i != e; ++i) {
442 llvm::SwitchInst *I = *i;
443
444 I->setSuccessor(0, Default);
445 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
446 LE = LabelIDs.end(); LI != LE; ++LI) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000447 I->addCase(VMContext.getConstantInt(llvm::Type::Int32Ty,
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000448 LI->second),
449 getBasicBlockForLabel(LI->first));
450 }
451 }
452}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000453
Daniel Dunbard286f052009-07-19 06:58:07 +0000454llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Anders Carlssondcc90d82008-12-12 07:19:02 +0000455 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000456
Anders Carlssonf666b772008-12-20 20:27:15 +0000457 assert(SizeEntry && "Did not emit size for type");
458 return SizeEntry;
459}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000460
Daniel Dunbard286f052009-07-19 06:58:07 +0000461llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000462 assert(Ty->isVariablyModifiedType() &&
463 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000464
Daniel Dunbard286f052009-07-19 06:58:07 +0000465 EnsureInsertPoint();
466
Anders Carlsson60d35412008-12-20 20:46:34 +0000467 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
468 llvm::Value *&SizeEntry = VLASizeMap[VAT];
469
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000470 if (!SizeEntry) {
471 // Get the element size;
472 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000473
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000474 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000475
476 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
477
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000478 if (ElemTy->isVariableArrayType())
479 ElemSize = EmitVLASize(ElemTy);
480 else {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000481 ElemSize = VMContext.getConstantInt(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000482 getContext().getTypeSize(ElemTy) / 8);
483 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000484
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000485 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000486 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
487
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000488 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000489 }
490
Anders Carlsson60d35412008-12-20 20:46:34 +0000491 return SizeEntry;
Eli Friedmanbdad6b62009-05-29 19:23:46 +0000492 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
493 EmitVLASize(AT->getElementType());
Ted Kremenek35366a62009-07-17 17:50:17 +0000494 } else if (const PointerType *PT = Ty->getAsPointerType())
Anders Carlsson60d35412008-12-20 20:46:34 +0000495 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000496 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000497 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000498 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000499
500 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000501}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000502
503llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
504 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
505 return EmitScalarExpr(E);
506 }
507 return EmitLValue(E).getAddress();
508}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000509
Anders Carlsson6fc55912009-02-08 03:22:36 +0000510void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000511{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000512 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000513}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000514
515void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
516{
517 assert(CleanupEntries.size() >= OldCleanupStackSize &&
518 "Cleanup stack mismatch!");
519
520 while (CleanupEntries.size() > OldCleanupStackSize)
521 EmitCleanupBlock();
522}
523
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000524CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000525{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000526 CleanupEntry &CE = CleanupEntries.back();
527
528 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
529
530 std::vector<llvm::BasicBlock *> Blocks;
531 std::swap(Blocks, CE.Blocks);
532
533 std::vector<llvm::BranchInst *> BranchFixups;
534 std::swap(BranchFixups, CE.BranchFixups);
535
536 CleanupEntries.pop_back();
537
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000538 // Check if any branch fixups pointed to the scope we just popped. If so,
539 // we can remove them.
540 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
541 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
542 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000543
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000544 if (I == BlockScopes.end())
545 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000546
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000547 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000548
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000549 if (I->second == CleanupEntries.size()) {
550 // We don't need to do this branch fixup.
551 BranchFixups[i] = BranchFixups.back();
552 BranchFixups.pop_back();
553 i--;
554 e--;
555 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000556 }
557 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000558
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000559 llvm::BasicBlock *SwitchBlock = 0;
560 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000561 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000562 SwitchBlock = createBasicBlock("cleanup.switch");
563 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000564
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000565 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000566
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000567 Builder.SetInsertPoint(SwitchBlock);
568
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000569 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
570 "cleanup.dst");
571 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
572
573 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000574 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000575 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000576
Anders Carlsson46831a92009-02-08 22:13:37 +0000577 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000578 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000579 Builder.SetInsertPoint(CurBB);
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000580
581 // If we had a current basic block, we also need to emit an instruction
582 // to initialize the cleanup destination.
Owen Anderson69243822009-07-13 04:10:07 +0000583 Builder.CreateStore(getLLVMContext().getNullValue(llvm::Type::Int32Ty),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000584 DestCodePtr);
585 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000586 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000587
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000588 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
589 llvm::BranchInst *BI = BranchFixups[i];
590 llvm::BasicBlock *Dest = BI->getSuccessor(0);
591
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000592 // Fixup the branch instruction to point to the cleanup block.
593 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000594
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000595 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000596 llvm::ConstantInt *ID;
597
598 // Check if we already have a destination for this block.
599 if (Dest == SI->getDefaultDest())
Owen Andersona1cf15f2009-07-14 23:10:40 +0000600 ID = VMContext.getConstantInt(llvm::Type::Int32Ty, 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000601 else {
602 ID = SI->findCaseDest(Dest);
603 if (!ID) {
604 // No code found, get a new unique one by using the number of
605 // switch successors.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000606 ID = VMContext.getConstantInt(llvm::Type::Int32Ty,
Anders Carlssoncc899202009-02-08 22:46:50 +0000607 SI->getNumSuccessors());
608 SI->addCase(ID, Dest);
609 }
610 }
611
612 // Store the jump destination before the branch instruction.
613 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000614 } else {
615 // We need to jump through another cleanup block. Create a pad block
616 // with a branch instruction that jumps to the final destination and
617 // add it as a branch fixup to the current cleanup scope.
618
619 // Create the pad block.
620 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000621
622 // Create a unique case ID.
Owen Andersona1cf15f2009-07-14 23:10:40 +0000623 llvm::ConstantInt *ID = VMContext.getConstantInt(llvm::Type::Int32Ty,
Anders Carlssoncc899202009-02-08 22:46:50 +0000624 SI->getNumSuccessors());
625
626 // Store the jump destination before the branch instruction.
627 new llvm::StoreInst(ID, DestCodePtr, BI);
628
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000629 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000630 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000631
632 // Create the branch to the final destination.
633 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
634 CleanupPad->getInstList().push_back(BI);
635
636 // And add it as a branch fixup.
637 CleanupEntries.back().BranchFixups.push_back(BI);
638 }
639 }
640 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000641
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000642 // Remove all blocks from the block scope map.
643 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
644 assert(BlockScopes.count(Blocks[i]) &&
645 "Did not find block in scope map!");
646
647 BlockScopes.erase(Blocks[i]);
648 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000649
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000650 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000651}
652
653void CodeGenFunction::EmitCleanupBlock()
654{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000655 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000656
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000657 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
658 if (CurBB && !CurBB->getTerminator() &&
659 Info.CleanupBlock->getNumUses() == 0) {
660 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
661 delete Info.CleanupBlock;
662 } else
663 EmitBlock(Info.CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000664
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000665 if (Info.SwitchBlock)
666 EmitBlock(Info.SwitchBlock);
667 if (Info.EndBlock)
668 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000669}
670
Anders Carlsson87eaf172009-02-08 00:50:42 +0000671void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
672{
673 assert(!CleanupEntries.empty() &&
674 "Trying to add branch fixup without cleanup block!");
675
Mike Stumpf5408fe2009-05-16 07:57:57 +0000676 // FIXME: We could be more clever here and check if there's already a branch
677 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000678 CleanupEntries.back().BranchFixups.push_back(BI);
679}
680
681void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
682{
Anders Carlsson46831a92009-02-08 22:13:37 +0000683 if (!HaveInsertPoint())
684 return;
685
Anders Carlsson87eaf172009-02-08 00:50:42 +0000686 llvm::BranchInst* BI = Builder.CreateBr(Dest);
687
Anders Carlsson46831a92009-02-08 22:13:37 +0000688 Builder.ClearInsertionPoint();
689
Anders Carlsson87eaf172009-02-08 00:50:42 +0000690 // The stack is empty, no need to do any cleanup.
691 if (CleanupEntries.empty())
692 return;
693
694 if (!Dest->getParent()) {
695 // We are trying to branch to a block that hasn't been inserted yet.
696 AddBranchFixup(BI);
697 return;
698 }
699
700 BlockScopeMap::iterator I = BlockScopes.find(Dest);
701 if (I == BlockScopes.end()) {
702 // We are trying to jump to a block that is outside of any cleanup scope.
703 AddBranchFixup(BI);
704 return;
705 }
706
707 assert(I->second < CleanupEntries.size() &&
708 "Trying to branch into cleanup region");
709
710 if (I->second == CleanupEntries.size() - 1) {
711 // We have a branch to a block in the same scope.
712 return;
713 }
714
715 AddBranchFixup(BI);
716}