blob: 22c099f8dcd26f924834aa32618cf7a39e3421bd [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"
Mike Stump4e7a1f72009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
26CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpa4f668f2009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Owen Andersonaac87052009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
Anders Carlsson2b77ba82009-04-04 20:47:02 +000030 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
31 CXXThisDecl(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000032 LLVMIntTy = ConvertType(getContext().IntTy);
33 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner41110242008-06-17 18:05:57 +000034}
Reid Spencer5f016e22007-07-11 17:01:13 +000035
36ASTContext &CodeGenFunction::getContext() const {
37 return CGM.getContext();
38}
39
40
41llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
42 llvm::BasicBlock *&BB = LabelMap[S];
43 if (BB) return BB;
44
45 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000046 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000047}
48
Daniel Dunbar0096acf2009-02-25 19:24:29 +000049llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
50 llvm::Value *Res = LocalDeclMap[VD];
51 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
52 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000053}
Reid Spencer5f016e22007-07-11 17:01:13 +000054
Daniel Dunbar0096acf2009-02-25 19:24:29 +000055llvm::Constant *
56CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000058}
59
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
66}
67
68bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Mike Stumpf5408fe2009-05-16 07:57:57 +000069 // FIXME: Use positive checks instead of negative ones to be more robust in
70 // the face of extension.
Daniel Dunbar89588912009-02-26 20:52:22 +000071 return !T->hasPointerRepresentation() &&!T->isRealType() &&
72 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000073 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000074}
75
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000076void CodeGenFunction::EmitReturnBlock() {
77 // For cleanliness, we try to avoid emitting the return block for
78 // simple cases.
79 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
80
81 if (CurBB) {
82 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
83
Daniel Dunbar96e18b02009-07-19 08:24:34 +000084 // We have a valid insert point, reuse it if it is empty or there are no
85 // explicit jumps to the return block.
86 if (CurBB->empty() || ReturnBlock->use_empty()) {
87 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000088 delete ReturnBlock;
Daniel Dunbar96e18b02009-07-19 08:24:34 +000089 } else
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000090 EmitBlock(ReturnBlock);
91 return;
92 }
93
94 // Otherwise, if the return block is the target of a single direct
95 // branch then we can just put the code in that block instead. This
96 // cleans up functions which started with a unified return block.
97 if (ReturnBlock->hasOneUse()) {
98 llvm::BranchInst *BI =
99 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
100 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
101 // Reset insertion point and delete the branch.
102 Builder.SetInsertPoint(BI->getParent());
103 BI->eraseFromParent();
104 delete ReturnBlock;
105 return;
106 }
107 }
108
Mike Stumpf5408fe2009-05-16 07:57:57 +0000109 // FIXME: We are at an unreachable point, there is no reason to emit the block
110 // unless it has uses. However, we still need a place to put the debug
111 // region.end for now.
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000112
113 EmitBlock(ReturnBlock);
114}
115
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000116void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000117 // Finish emission of indirect switches.
118 EmitIndirectSwitches();
119
Chris Lattnerda138702007-07-16 21:28:45 +0000120 assert(BreakContinueStack.empty() &&
121 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000122 assert(BlockScopes.empty() &&
123 "did not remove all blocks from block scope map!");
124 assert(CleanupEntries.empty() &&
125 "mismatched push/pop in cleanup stack!");
126
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000127 // Emit function epilog (to return).
128 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000129
130 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000131 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000132 DI->setLocation(EndLoc);
133 DI->EmitRegionEnd(CurFn, Builder);
134 }
135
Daniel Dunbar88b53962009-02-02 22:03:45 +0000136 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000137
Chris Lattner5a2fa142007-12-02 06:32:24 +0000138 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattner481769b2009-03-31 22:17:44 +0000139 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattner5a2fa142007-12-02 06:32:24 +0000140 AllocaInsertPt = 0;
Chris Lattner481769b2009-03-31 22:17:44 +0000141 Ptr->eraseFromParent();
Reid Spencer5f016e22007-07-11 17:01:13 +0000142}
143
Daniel Dunbar7c086512008-09-09 23:14:03 +0000144void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
145 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000146 const FunctionArgList &Args,
147 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000148 DidCallStackSave = false;
Chris Lattnerb5437d22009-04-23 05:30:27 +0000149 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000150 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000151 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000152 assert(CurFn->isDeclaration() && "Function already has body?");
153
Daniel Dunbar55e87422008-11-11 02:29:29 +0000154 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000155
Chris Lattner41110242008-06-17 18:05:57 +0000156 // Create a marker to make it easy to insert allocas into the entryblock
157 // later. Don't create this with the builder, because we don't want it
158 // folded.
Owen Anderson03e20502009-07-30 23:11:26 +0000159 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
Chris Lattnerf1466842009-03-22 00:24:14 +0000160 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
Chris Lattner41110242008-06-17 18:05:57 +0000161 EntryBB);
Chris Lattnerf1466842009-03-22 00:24:14 +0000162 if (Builder.isNamePreserving())
163 AllocaInsertPt->setName("allocapt");
164
Daniel Dunbar55e87422008-11-11 02:29:29 +0000165 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000166 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000167 if (!RetTy->isVoidType())
168 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000169
Chris Lattner41110242008-06-17 18:05:57 +0000170 Builder.SetInsertPoint(EntryBB);
171
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000172 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000173 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000174 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000175 DI->setLocation(StartLoc);
176 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6ec36682009-02-18 23:53:56 +0000177 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000178 } else {
179 // Just use LLVM function name.
Daniel Dunbar42719fc2009-07-23 05:30:36 +0000180
181 // FIXME: Remove unnecessary conversion to std::string when API settles.
182 DI->EmitFunctionStart(std::string(Fn->getName()).c_str(),
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000183 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000184 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000185 }
186
Daniel Dunbar88b53962009-02-02 22:03:45 +0000187 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000188 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000189 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000190
191 // If any of the arguments have a variably modified type, make sure to
192 // emit the type size.
193 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
194 i != e; ++i) {
195 QualType Ty = i->second;
196
197 if (Ty->isVariablyModifiedType())
198 EmitVLASize(Ty);
199 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000200}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000201
Daniel Dunbar7c086512008-09-09 23:14:03 +0000202void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
203 llvm::Function *Fn) {
Anders Carlssone896d982009-02-13 08:11:52 +0000204 // Check if we should generate debug info for this function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000205 if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
Anders Carlssone896d982009-02-13 08:11:52 +0000206 DebugInfo = CGM.getDebugInfo();
207
Daniel Dunbar7c086512008-09-09 23:14:03 +0000208 FunctionArgList Args;
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000209
210 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
211 if (MD->isInstance()) {
212 // Create the implicit 'this' decl.
213 // FIXME: I'm not entirely sure I like using a fake decl just for code
214 // generation. Maybe we can come up with a better way?
215 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
216 &getContext().Idents.get("this"),
217 MD->getThisType(getContext()));
218 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
219 }
220 }
221
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000222 if (FD->getNumParams()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000223 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000224 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000225
226 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
227 Args.push_back(std::make_pair(FD->getParamDecl(i),
228 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000229 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000230
Sebastian Redld3a413d2009-04-26 20:35:05 +0000231 // FIXME: Support CXXTryStmt here, too.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000232 if (const CompoundStmt *S = FD->getCompoundBody()) {
Sebastian Redld3a413d2009-04-26 20:35:05 +0000233 StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Fariborz Jahanianab3c0a22009-07-20 22:35:22 +0000234 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
235 EmitCtorPrologue(CD);
Sebastian Redld3a413d2009-04-26 20:35:05 +0000236 EmitStmt(S);
Fariborz Jahanian426cc382009-07-30 17:49:11 +0000237 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
238 EmitDtorEpilogue(DD);
Sebastian Redld3a413d2009-04-26 20:35:05 +0000239 FinishFunction(S->getRBracLoc());
240 }
Fariborz Jahanianc7ff8e12009-07-30 23:22:00 +0000241 else
242 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
243 assert(
244 !cast<CXXRecordDecl>(CD->getDeclContext())->
245 hasUserDeclaredConstructor() &&
246 "bogus constructor is being synthesize");
247 StartFunction(FD, FD->getResultType(), Fn, Args, SourceLocation());
248 EmitCtorPrologue(CD);
249 FinishFunction();
250 }
251
Anders Carlsson2b77ba82009-04-04 20:47:02 +0000252 // Destroy the 'this' declaration.
253 if (CXXThisDecl)
254 CXXThisDecl->Destroy(getContext());
Chris Lattner41110242008-06-17 18:05:57 +0000255}
256
Chris Lattner0946ccd2008-11-11 07:41:27 +0000257/// ContainsLabel - Return true if the statement contains a label in it. If
258/// this statement is not executed normally, it not containing a label means
259/// that we can just remove the code.
260bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
261 // Null statement, not a label!
262 if (S == 0) return false;
263
264 // If this is a label, we have to emit the code, consider something like:
265 // if (0) { ... foo: bar(); } goto foo;
266 if (isa<LabelStmt>(S))
267 return true;
268
269 // If this is a case/default statement, and we haven't seen a switch, we have
270 // to emit the code.
271 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
272 return true;
273
274 // If this is a switch statement, we want to ignore cases below it.
275 if (isa<SwitchStmt>(S))
276 IgnoreCaseStmts = true;
277
278 // Scan subexpressions for verboten labels.
279 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
280 I != E; ++I)
281 if (ContainsLabel(*I, IgnoreCaseStmts))
282 return true;
283
284 return false;
285}
286
Chris Lattner31a09842008-11-12 08:04:58 +0000287
288/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
289/// a constant, or if it does but contains a label, return 0. If it constant
290/// folds to 'true' and does not contain a label, return 1, if it constant folds
291/// to 'false' and does not contain a label, return -1.
292int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000293 // FIXME: Rename and handle conversion of other evaluatable things
294 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000295 Expr::EvalResult Result;
296 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
297 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000298 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000299
300 if (CodeGenFunction::ContainsLabel(Cond))
301 return 0; // Contains a label.
302
Anders Carlsson64712f12008-12-01 02:46:24 +0000303 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000304}
305
306
307/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
308/// statement) to the specified blocks. Based on the condition, this might try
309/// to simplify the codegen of the conditional based on the branch.
310///
311void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
312 llvm::BasicBlock *TrueBlock,
313 llvm::BasicBlock *FalseBlock) {
314 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
315 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
316
317 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
318 // Handle X && Y in a condition.
319 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
320 // If we have "1 && X", simplify the code. "0 && X" would have constant
321 // folded if the case was simple enough.
322 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
323 // br(1 && X) -> br(X).
324 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
325 }
326
327 // If we have "X && 1", simplify the code to use an uncond branch.
328 // "X && 0" would have been constant folded to 0.
329 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
330 // br(X && 1) -> br(X).
331 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
332 }
333
334 // Emit the LHS as a conditional. If the LHS conditional is false, we
335 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000336 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000337 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
338 EmitBlock(LHSTrue);
339
340 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
341 return;
342 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
343 // If we have "0 || X", simplify the code. "1 || X" would have constant
344 // folded if the case was simple enough.
345 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
346 // br(0 || X) -> br(X).
347 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
348 }
349
350 // If we have "X || 0", simplify the code to use an uncond branch.
351 // "X || 1" would have been constant folded to 1.
352 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
353 // br(X || 0) -> br(X).
354 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
355 }
356
357 // Emit the LHS as a conditional. If the LHS conditional is true, we
358 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000359 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000360 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
361 EmitBlock(LHSFalse);
362
363 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
364 return;
365 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000366 }
367
368 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
369 // br(!x, t, f) -> br(x, f, t)
370 if (CondUOp->getOpcode() == UnaryOperator::LNot)
371 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000372 }
373
Daniel Dunbar09b14892008-11-12 10:30:32 +0000374 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
375 // Handle ?: operator.
376
377 // Just ignore GNU ?: extension.
378 if (CondOp->getLHS()) {
379 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
380 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
381 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
382 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
383 EmitBlock(LHSBlock);
384 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
385 EmitBlock(RHSBlock);
386 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
387 return;
388 }
389 }
390
Chris Lattner31a09842008-11-12 08:04:58 +0000391 // Emit the code with the fully general case.
392 llvm::Value *CondV = EvaluateExprAsBool(Cond);
393 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
394}
395
Devang Patel88a981b2007-11-01 19:11:01 +0000396/// getCGRecordLayout - Return record layout info.
397const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000398 QualType Ty) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000399 const RecordType *RTy = Ty->getAs<RecordType>();
Chris Lattneraf319132008-02-05 06:55:31 +0000400 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000401
Chris Lattneraf319132008-02-05 06:55:31 +0000402 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000403}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000404
Daniel Dunbar488e9932008-08-16 00:56:44 +0000405/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000406/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000407void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
408 bool OmitOnError) {
409 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000410}
411
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000412unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
413 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
414 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
415}
416
Chris Lattner88207c92009-04-21 17:59:23 +0000417void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000418 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000419 if (DestPtr->getType() != BP)
420 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
421
422 // Get size and alignment info for this aggregate.
423 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
424
Chris Lattner88207c92009-04-21 17:59:23 +0000425 // Don't bother emitting a zero-byte memset.
426 if (TypeInfo.first == 0)
427 return;
428
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000429 // FIXME: Handle variable sized types.
Owen Anderson96e0fc72009-07-29 22:16:19 +0000430 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000431
432 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Andersonc9c88b42009-07-31 20:28:54 +0000433 llvm::Constant::getNullValue(llvm::Type::Int8Ty),
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000434 // TypeInfo.first describes size in bits.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000435 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
436 llvm::ConstantInt::get(llvm::Type::Int32Ty,
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000437 TypeInfo.second/8));
438}
439
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000440void CodeGenFunction::EmitIndirectSwitches() {
441 llvm::BasicBlock *Default;
442
Daniel Dunbar76526a52008-08-04 17:24:44 +0000443 if (IndirectSwitches.empty())
444 return;
445
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000446 if (!LabelIDs.empty()) {
447 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
448 } else {
449 // No possible targets for indirect goto, just emit an infinite
450 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000451 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000452 llvm::BranchInst::Create(Default, Default);
453 }
454
455 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
456 e = IndirectSwitches.end(); i != e; ++i) {
457 llvm::SwitchInst *I = *i;
458
459 I->setSuccessor(0, Default);
460 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
461 LE = LabelIDs.end(); LI != LE; ++LI) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000462 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000463 LI->second),
464 getBasicBlockForLabel(LI->first));
465 }
466 }
467}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000468
Daniel Dunbard286f052009-07-19 06:58:07 +0000469llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Anders Carlssondcc90d82008-12-12 07:19:02 +0000470 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000471
Anders Carlssonf666b772008-12-20 20:27:15 +0000472 assert(SizeEntry && "Did not emit size for type");
473 return SizeEntry;
474}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000475
Daniel Dunbard286f052009-07-19 06:58:07 +0000476llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlsson60d35412008-12-20 20:46:34 +0000477 assert(Ty->isVariablyModifiedType() &&
478 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000479
Daniel Dunbard286f052009-07-19 06:58:07 +0000480 EnsureInsertPoint();
481
Anders Carlsson60d35412008-12-20 20:46:34 +0000482 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
483 llvm::Value *&SizeEntry = VLASizeMap[VAT];
484
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000485 if (!SizeEntry) {
486 // Get the element size;
487 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000488
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000489 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000490
491 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
492
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000493 if (ElemTy->isVariableArrayType())
494 ElemSize = EmitVLASize(ElemTy);
495 else {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000496 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000497 getContext().getTypeSize(ElemTy) / 8);
498 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000499
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000500 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000501 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
502
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000503 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000504 }
505
Anders Carlsson60d35412008-12-20 20:46:34 +0000506 return SizeEntry;
Eli Friedmanbdad6b62009-05-29 19:23:46 +0000507 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
508 EmitVLASize(AT->getElementType());
Ted Kremenek6217b802009-07-29 21:53:49 +0000509 } else if (const PointerType *PT = Ty->getAs<PointerType>())
Anders Carlsson60d35412008-12-20 20:46:34 +0000510 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000511 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000512 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000513 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000514
515 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000516}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000517
518llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
519 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
520 return EmitScalarExpr(E);
521 }
522 return EmitLValue(E).getAddress();
523}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000524
Anders Carlsson6fc55912009-02-08 03:22:36 +0000525void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000526{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000527 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000528}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000529
530void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
531{
532 assert(CleanupEntries.size() >= OldCleanupStackSize &&
533 "Cleanup stack mismatch!");
534
535 while (CleanupEntries.size() > OldCleanupStackSize)
536 EmitCleanupBlock();
537}
538
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000539CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000540{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000541 CleanupEntry &CE = CleanupEntries.back();
542
543 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
544
545 std::vector<llvm::BasicBlock *> Blocks;
546 std::swap(Blocks, CE.Blocks);
547
548 std::vector<llvm::BranchInst *> BranchFixups;
549 std::swap(BranchFixups, CE.BranchFixups);
550
551 CleanupEntries.pop_back();
552
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000553 // Check if any branch fixups pointed to the scope we just popped. If so,
554 // we can remove them.
555 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
556 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
557 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000558
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000559 if (I == BlockScopes.end())
560 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000561
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000562 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000563
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000564 if (I->second == CleanupEntries.size()) {
565 // We don't need to do this branch fixup.
566 BranchFixups[i] = BranchFixups.back();
567 BranchFixups.pop_back();
568 i--;
569 e--;
570 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000571 }
572 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000573
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000574 llvm::BasicBlock *SwitchBlock = 0;
575 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000576 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000577 SwitchBlock = createBasicBlock("cleanup.switch");
578 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000579
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000580 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000581
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000582 Builder.SetInsertPoint(SwitchBlock);
583
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000584 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
585 "cleanup.dst");
586 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
587
588 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000589 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000590 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000591
Anders Carlsson46831a92009-02-08 22:13:37 +0000592 // Restore the current basic block (if any)
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000593 if (CurBB) {
Anders Carlsson46831a92009-02-08 22:13:37 +0000594 Builder.SetInsertPoint(CurBB);
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000595
596 // If we had a current basic block, we also need to emit an instruction
597 // to initialize the cleanup destination.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000598 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::Int32Ty),
Anders Carlsson0ae7b2b2009-03-17 05:53:35 +0000599 DestCodePtr);
600 } else
Anders Carlsson46831a92009-02-08 22:13:37 +0000601 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000602
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000603 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
604 llvm::BranchInst *BI = BranchFixups[i];
605 llvm::BasicBlock *Dest = BI->getSuccessor(0);
606
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000607 // Fixup the branch instruction to point to the cleanup block.
608 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000609
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000610 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000611 llvm::ConstantInt *ID;
612
613 // Check if we already have a destination for this block.
614 if (Dest == SI->getDefaultDest())
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000615 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Anders Carlssoncc899202009-02-08 22:46:50 +0000616 else {
617 ID = SI->findCaseDest(Dest);
618 if (!ID) {
619 // No code found, get a new unique one by using the number of
620 // switch successors.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000621 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
Anders Carlssoncc899202009-02-08 22:46:50 +0000622 SI->getNumSuccessors());
623 SI->addCase(ID, Dest);
624 }
625 }
626
627 // Store the jump destination before the branch instruction.
628 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000629 } else {
630 // We need to jump through another cleanup block. Create a pad block
631 // with a branch instruction that jumps to the final destination and
632 // add it as a branch fixup to the current cleanup scope.
633
634 // Create the pad block.
635 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000636
637 // Create a unique case ID.
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000638 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
Anders Carlssoncc899202009-02-08 22:46:50 +0000639 SI->getNumSuccessors());
640
641 // Store the jump destination before the branch instruction.
642 new llvm::StoreInst(ID, DestCodePtr, BI);
643
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000644 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000645 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000646
647 // Create the branch to the final destination.
648 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
649 CleanupPad->getInstList().push_back(BI);
650
651 // And add it as a branch fixup.
652 CleanupEntries.back().BranchFixups.push_back(BI);
653 }
654 }
655 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000656
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000657 // Remove all blocks from the block scope map.
658 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
659 assert(BlockScopes.count(Blocks[i]) &&
660 "Did not find block in scope map!");
661
662 BlockScopes.erase(Blocks[i]);
663 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000664
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000665 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000666}
667
668void CodeGenFunction::EmitCleanupBlock()
669{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000670 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000671
Anders Carlssoneb6437a2009-05-31 00:33:20 +0000672 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
673 if (CurBB && !CurBB->getTerminator() &&
674 Info.CleanupBlock->getNumUses() == 0) {
675 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
676 delete Info.CleanupBlock;
677 } else
678 EmitBlock(Info.CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000679
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000680 if (Info.SwitchBlock)
681 EmitBlock(Info.SwitchBlock);
682 if (Info.EndBlock)
683 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000684}
685
Anders Carlsson87eaf172009-02-08 00:50:42 +0000686void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
687{
688 assert(!CleanupEntries.empty() &&
689 "Trying to add branch fixup without cleanup block!");
690
Mike Stumpf5408fe2009-05-16 07:57:57 +0000691 // FIXME: We could be more clever here and check if there's already a branch
692 // fixup for this destination and recycle it.
Anders Carlsson87eaf172009-02-08 00:50:42 +0000693 CleanupEntries.back().BranchFixups.push_back(BI);
694}
695
696void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
697{
Anders Carlsson46831a92009-02-08 22:13:37 +0000698 if (!HaveInsertPoint())
699 return;
700
Anders Carlsson87eaf172009-02-08 00:50:42 +0000701 llvm::BranchInst* BI = Builder.CreateBr(Dest);
702
Anders Carlsson46831a92009-02-08 22:13:37 +0000703 Builder.ClearInsertionPoint();
704
Anders Carlsson87eaf172009-02-08 00:50:42 +0000705 // The stack is empty, no need to do any cleanup.
706 if (CleanupEntries.empty())
707 return;
708
709 if (!Dest->getParent()) {
710 // We are trying to branch to a block that hasn't been inserted yet.
711 AddBranchFixup(BI);
712 return;
713 }
714
715 BlockScopeMap::iterator I = BlockScopes.find(Dest);
716 if (I == BlockScopes.end()) {
717 // We are trying to jump to a block that is outside of any cleanup scope.
718 AddBranchFixup(BI);
719 return;
720 }
721
722 assert(I->second < CleanupEntries.size() &&
723 "Trying to branch into cleanup region");
724
725 if (I->second == CleanupEntries.size() - 1) {
726 // We have a branch to a block in the same scope.
727 return;
728 }
729
730 AddBranchFixup(BI);
731}