blob: 153fcc8ec478194582216fe5692e1656d9086e25 [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),
Mike Stump36a2ada2009-02-07 12:52:26 +000027 CaseRangeBlock(NULL), StackDepth(0) {
Chris Lattner41110242008-06-17 18:05:57 +000028 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
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000055const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
56 return CGM.getTypes().ConvertTypeForMem(T);
57}
58
Reid Spencer5f016e22007-07-11 17:01:13 +000059const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
60 return CGM.getTypes().ConvertType(T);
61}
62
Chris Lattner41110242008-06-17 18:05:57 +000063bool CodeGenFunction::isObjCPointerType(QualType T) {
64 // All Objective-C types are pointers.
65 return T->isObjCInterfaceType() ||
66 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
67}
68
Reid Spencer5f016e22007-07-11 17:01:13 +000069bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbara782ca72009-01-09 02:44:18 +000070 // FIXME: Use positive checks instead of negative ones to be more
71 // robust in the face of extension.
Chris Lattner41110242008-06-17 18:05:57 +000072 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000073 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
74 !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
85 // We have a valid insert point, reuse it if there are no explicit
86 // jumps to the return block.
87 if (ReturnBlock->use_empty())
88 delete ReturnBlock;
89 else
90 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
109 // FIXME: We are at an unreachable point, there is no reason to emit
110 // the block unless it has uses. However, we still need a place to
111 // put the debug region.end for now.
112
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.
131 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
132 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.
139 AllocaInsertPt->eraseFromParent();
140 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000141}
142
Daniel Dunbar7c086512008-09-09 23:14:03 +0000143void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
144 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000145 const FunctionArgList &Args,
146 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000147 DidCallStackSave = false;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000148 CurFuncDecl = D;
149 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000150 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000151 assert(CurFn->isDeclaration() && "Function already has body?");
152
Daniel Dunbar55e87422008-11-11 02:29:29 +0000153 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000154
Chris Lattner41110242008-06-17 18:05:57 +0000155 // Create a marker to make it easy to insert allocas into the entryblock
156 // later. Don't create this with the builder, because we don't want it
157 // folded.
158 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
159 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
160 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000161
Daniel Dunbar55e87422008-11-11 02:29:29 +0000162 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000163 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000164 if (!RetTy->isVoidType())
165 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000166
Chris Lattner41110242008-06-17 18:05:57 +0000167 Builder.SetInsertPoint(EntryBB);
168
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000169 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000170 // FIXME: The cast here is a huge hack.
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000171 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
172 DI->setLocation(StartLoc);
173 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000174 DI->EmitFunctionStart(FD->getIdentifier()->getName(),
175 RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000176 } else {
177 // Just use LLVM function name.
178 DI->EmitFunctionStart(Fn->getName().c_str(),
179 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000180 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000181 }
182
Daniel Dunbar88b53962009-02-02 22:03:45 +0000183 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000184 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000185 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000186
187 // If any of the arguments have a variably modified type, make sure to
188 // emit the type size.
189 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
190 i != e; ++i) {
191 QualType Ty = i->second;
192
193 if (Ty->isVariablyModifiedType())
194 EmitVLASize(Ty);
195 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000196}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000197
Daniel Dunbar7c086512008-09-09 23:14:03 +0000198void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
199 llvm::Function *Fn) {
200 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000201 if (FD->getNumParams()) {
202 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
203 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000204
205 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
206 Args.push_back(std::make_pair(FD->getParamDecl(i),
207 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000208 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000209
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000210 StartFunction(FD, FD->getResultType(), Fn, Args,
211 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000212
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000213 EmitStmt(FD->getBody());
214
215 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
216 if (S) {
217 FinishFunction(S->getRBracLoc());
218 } else {
219 FinishFunction();
220 }
Chris Lattner41110242008-06-17 18:05:57 +0000221}
222
Chris Lattner0946ccd2008-11-11 07:41:27 +0000223/// ContainsLabel - Return true if the statement contains a label in it. If
224/// this statement is not executed normally, it not containing a label means
225/// that we can just remove the code.
226bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
227 // Null statement, not a label!
228 if (S == 0) return false;
229
230 // If this is a label, we have to emit the code, consider something like:
231 // if (0) { ... foo: bar(); } goto foo;
232 if (isa<LabelStmt>(S))
233 return true;
234
235 // If this is a case/default statement, and we haven't seen a switch, we have
236 // to emit the code.
237 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
238 return true;
239
240 // If this is a switch statement, we want to ignore cases below it.
241 if (isa<SwitchStmt>(S))
242 IgnoreCaseStmts = true;
243
244 // Scan subexpressions for verboten labels.
245 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
246 I != E; ++I)
247 if (ContainsLabel(*I, IgnoreCaseStmts))
248 return true;
249
250 return false;
251}
252
Chris Lattner31a09842008-11-12 08:04:58 +0000253
254/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
255/// a constant, or if it does but contains a label, return 0. If it constant
256/// folds to 'true' and does not contain a label, return 1, if it constant folds
257/// to 'false' and does not contain a label, return -1.
258int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000259 // FIXME: Rename and handle conversion of other evaluatable things
260 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000261 Expr::EvalResult Result;
262 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
263 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000264 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000265
266 if (CodeGenFunction::ContainsLabel(Cond))
267 return 0; // Contains a label.
268
Anders Carlsson64712f12008-12-01 02:46:24 +0000269 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000270}
271
272
273/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
274/// statement) to the specified blocks. Based on the condition, this might try
275/// to simplify the codegen of the conditional based on the branch.
276///
277void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
278 llvm::BasicBlock *TrueBlock,
279 llvm::BasicBlock *FalseBlock) {
280 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
281 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
282
283 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
284 // Handle X && Y in a condition.
285 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
286 // If we have "1 && X", simplify the code. "0 && X" would have constant
287 // folded if the case was simple enough.
288 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
289 // br(1 && X) -> br(X).
290 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
291 }
292
293 // If we have "X && 1", simplify the code to use an uncond branch.
294 // "X && 0" would have been constant folded to 0.
295 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
296 // br(X && 1) -> br(X).
297 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
298 }
299
300 // Emit the LHS as a conditional. If the LHS conditional is false, we
301 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000302 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000303 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
304 EmitBlock(LHSTrue);
305
306 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
307 return;
308 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
309 // If we have "0 || X", simplify the code. "1 || X" would have constant
310 // folded if the case was simple enough.
311 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
312 // br(0 || X) -> br(X).
313 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
314 }
315
316 // If we have "X || 0", simplify the code to use an uncond branch.
317 // "X || 1" would have been constant folded to 1.
318 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
319 // br(X || 0) -> br(X).
320 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
321 }
322
323 // Emit the LHS as a conditional. If the LHS conditional is true, we
324 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000325 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000326 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
327 EmitBlock(LHSFalse);
328
329 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
330 return;
331 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000332 }
333
334 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
335 // br(!x, t, f) -> br(x, f, t)
336 if (CondUOp->getOpcode() == UnaryOperator::LNot)
337 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000338 }
339
Daniel Dunbar09b14892008-11-12 10:30:32 +0000340 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
341 // Handle ?: operator.
342
343 // Just ignore GNU ?: extension.
344 if (CondOp->getLHS()) {
345 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
346 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
347 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
348 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
349 EmitBlock(LHSBlock);
350 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
351 EmitBlock(RHSBlock);
352 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
353 return;
354 }
355 }
356
Chris Lattner31a09842008-11-12 08:04:58 +0000357 // Emit the code with the fully general case.
358 llvm::Value *CondV = EvaluateExprAsBool(Cond);
359 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
360}
361
Devang Patel88a981b2007-11-01 19:11:01 +0000362/// getCGRecordLayout - Return record layout info.
363const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000364 QualType Ty) {
365 const RecordType *RTy = Ty->getAsRecordType();
366 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000367
Chris Lattneraf319132008-02-05 06:55:31 +0000368 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000369}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000370
Daniel Dunbar488e9932008-08-16 00:56:44 +0000371/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000372/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000373void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
374 bool OmitOnError) {
375 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000376}
377
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000378unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
379 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
380 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
381}
382
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000383void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
384{
385 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
386 if (DestPtr->getType() != BP)
387 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
388
389 // Get size and alignment info for this aggregate.
390 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
391
392 // FIXME: Handle variable sized types.
393 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
394
395 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
396 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
397 // TypeInfo.first describes size in bits.
398 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
399 llvm::ConstantInt::get(llvm::Type::Int32Ty,
400 TypeInfo.second/8));
401}
402
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000403void CodeGenFunction::EmitIndirectSwitches() {
404 llvm::BasicBlock *Default;
405
Daniel Dunbar76526a52008-08-04 17:24:44 +0000406 if (IndirectSwitches.empty())
407 return;
408
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000409 if (!LabelIDs.empty()) {
410 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
411 } else {
412 // No possible targets for indirect goto, just emit an infinite
413 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000414 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000415 llvm::BranchInst::Create(Default, Default);
416 }
417
418 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
419 e = IndirectSwitches.end(); i != e; ++i) {
420 llvm::SwitchInst *I = *i;
421
422 I->setSuccessor(0, Default);
423 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
424 LE = LabelIDs.end(); LI != LE; ++LI) {
425 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
426 LI->second),
427 getBasicBlockForLabel(LI->first));
428 }
429 }
430}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000431
432llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
433{
434 // FIXME: This entire method is hardcoded for 32-bit X86.
435
436 const char *TargetPrefix = getContext().Target.getTargetPrefix();
437
438 if (strcmp(TargetPrefix, "x86") != 0 ||
439 getContext().Target.getPointerWidth(0) != 32)
440 return 0;
441
442 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
443 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
444
445 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
446 "ap");
447 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
448 llvm::Value *AddrTyped =
449 Builder.CreateBitCast(Addr,
450 llvm::PointerType::getUnqual(ConvertType(Ty)));
451
452 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
453 const unsigned ArgumentSizeInBytes = 4;
454 if (SizeInBytes < ArgumentSizeInBytes)
455 SizeInBytes = ArgumentSizeInBytes;
456
457 llvm::Value *NextAddr =
458 Builder.CreateGEP(Addr,
459 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
460 "ap.next");
461 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
462
463 return AddrTyped;
464}
465
Anders Carlssonf666b772008-12-20 20:27:15 +0000466
Anders Carlssondcc90d82008-12-12 07:19:02 +0000467llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
468{
469 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000470
Anders Carlssonf666b772008-12-20 20:27:15 +0000471 assert(SizeEntry && "Did not emit size for type");
472 return SizeEntry;
473}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000474
Anders Carlsson60d35412008-12-20 20:46:34 +0000475llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000476{
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
Anders Carlsson60d35412008-12-20 20:46:34 +0000480 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
481 llvm::Value *&SizeEntry = VLASizeMap[VAT];
482
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000483 if (!SizeEntry) {
484 // Get the element size;
485 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000486
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000487 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000488
489 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
490
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000491 if (ElemTy->isVariableArrayType())
492 ElemSize = EmitVLASize(ElemTy);
493 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000494 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000495 getContext().getTypeSize(ElemTy) / 8);
496 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000497
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000498 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000499 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
500
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000501 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000502 }
503
Anders Carlsson60d35412008-12-20 20:46:34 +0000504 return SizeEntry;
505 } else if (const PointerType *PT = Ty->getAsPointerType())
506 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000507 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000508 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000509 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000510
511 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000512}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000513
514llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
515 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
516 return EmitScalarExpr(E);
517 }
518 return EmitLValue(E).getAddress();
519}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000520
Anders Carlsson6fc55912009-02-08 03:22:36 +0000521void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000522{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000523 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000524}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000525
526void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
527{
528 assert(CleanupEntries.size() >= OldCleanupStackSize &&
529 "Cleanup stack mismatch!");
530
531 while (CleanupEntries.size() > OldCleanupStackSize)
532 EmitCleanupBlock();
533}
534
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000535CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000536{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000537 CleanupEntry &CE = CleanupEntries.back();
538
539 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
540
541 std::vector<llvm::BasicBlock *> Blocks;
542 std::swap(Blocks, CE.Blocks);
543
544 std::vector<llvm::BranchInst *> BranchFixups;
545 std::swap(BranchFixups, CE.BranchFixups);
546
547 CleanupEntries.pop_back();
548
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000549 // Check if any branch fixups pointed to the scope we just popped. If so,
550 // we can remove them.
551 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
552 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
553 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000554
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000555 if (I == BlockScopes.end())
556 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000557
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000558 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000559
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000560 if (I->second == CleanupEntries.size()) {
561 // We don't need to do this branch fixup.
562 BranchFixups[i] = BranchFixups.back();
563 BranchFixups.pop_back();
564 i--;
565 e--;
566 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000567 }
568 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000569
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000570 llvm::BasicBlock *SwitchBlock = 0;
571 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000572 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000573 SwitchBlock = createBasicBlock("cleanup.switch");
574 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000575
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000576 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
577
578 Builder.SetInsertPoint(SwitchBlock);
579
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000580 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
581 "cleanup.dst");
582 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
583
584 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000585 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000586 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000587
Anders Carlsson46831a92009-02-08 22:13:37 +0000588 // Restore the current basic block (if any)
589 if (CurBB)
590 Builder.SetInsertPoint(CurBB);
591 else
592 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000593
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000594 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
595 llvm::BranchInst *BI = BranchFixups[i];
596 llvm::BasicBlock *Dest = BI->getSuccessor(0);
597
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000598 // Fixup the branch instruction to point to the cleanup block.
599 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000600
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000601 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000602 llvm::ConstantInt *ID;
603
604 // Check if we already have a destination for this block.
605 if (Dest == SI->getDefaultDest())
606 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
607 else {
608 ID = SI->findCaseDest(Dest);
609 if (!ID) {
610 // No code found, get a new unique one by using the number of
611 // switch successors.
612 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
613 SI->getNumSuccessors());
614 SI->addCase(ID, Dest);
615 }
616 }
617
618 // Store the jump destination before the branch instruction.
619 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000620 } else {
621 // We need to jump through another cleanup block. Create a pad block
622 // with a branch instruction that jumps to the final destination and
623 // add it as a branch fixup to the current cleanup scope.
624
625 // Create the pad block.
626 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000627
628 // Create a unique case ID.
629 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
630 SI->getNumSuccessors());
631
632 // Store the jump destination before the branch instruction.
633 new llvm::StoreInst(ID, DestCodePtr, BI);
634
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000635 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000636 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000637
638 // Create the branch to the final destination.
639 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
640 CleanupPad->getInstList().push_back(BI);
641
642 // And add it as a branch fixup.
643 CleanupEntries.back().BranchFixups.push_back(BI);
644 }
645 }
646 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000647
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000648 // Remove all blocks from the block scope map.
649 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
650 assert(BlockScopes.count(Blocks[i]) &&
651 "Did not find block in scope map!");
652
653 BlockScopes.erase(Blocks[i]);
654 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000655
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000656 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000657}
658
659void CodeGenFunction::EmitCleanupBlock()
660{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000661 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000662
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000663 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
676 // FIXME: We could be more clever here and check if there's already a
677 // branch fixup for this destination and recycle it.
678 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}