blob: 4b3ab2de194e92ff7eb62d69e3c3a67faf15de3b [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) {
Daniel Dunbar7c086512008-09-09 23:14:03 +0000147 CurFuncDecl = D;
148 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000149 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000150 assert(CurFn->isDeclaration() && "Function already has body?");
151
Daniel Dunbar55e87422008-11-11 02:29:29 +0000152 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000153
Chris Lattner41110242008-06-17 18:05:57 +0000154 // Create a marker to make it easy to insert allocas into the entryblock
155 // later. Don't create this with the builder, because we don't want it
156 // folded.
157 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
158 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
159 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000160
Daniel Dunbar55e87422008-11-11 02:29:29 +0000161 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000162 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000163 if (!RetTy->isVoidType())
164 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000165
Chris Lattner41110242008-06-17 18:05:57 +0000166 Builder.SetInsertPoint(EntryBB);
167
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000168 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000169 // FIXME: The cast here is a huge hack.
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000170 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
171 DI->setLocation(StartLoc);
172 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Chris Lattner8ec03f52008-11-24 03:54:41 +0000173 DI->EmitFunctionStart(FD->getIdentifier()->getName(),
174 RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000175 } else {
176 // Just use LLVM function name.
177 DI->EmitFunctionStart(Fn->getName().c_str(),
178 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000179 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000180 }
181
Daniel Dunbar88b53962009-02-02 22:03:45 +0000182 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000183 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000184 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000185
186 // If any of the arguments have a variably modified type, make sure to
187 // emit the type size.
188 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
189 i != e; ++i) {
190 QualType Ty = i->second;
191
192 if (Ty->isVariablyModifiedType())
193 EmitVLASize(Ty);
194 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000195}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000196
Daniel Dunbar7c086512008-09-09 23:14:03 +0000197void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
198 llvm::Function *Fn) {
199 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000200 if (FD->getNumParams()) {
201 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
202 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000203
204 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
205 Args.push_back(std::make_pair(FD->getParamDecl(i),
206 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000207 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000208
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000209 StartFunction(FD, FD->getResultType(), Fn, Args,
210 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000211
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000212 EmitStmt(FD->getBody());
213
214 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
215 if (S) {
216 FinishFunction(S->getRBracLoc());
217 } else {
218 FinishFunction();
219 }
Chris Lattner41110242008-06-17 18:05:57 +0000220}
221
Chris Lattner0946ccd2008-11-11 07:41:27 +0000222/// ContainsLabel - Return true if the statement contains a label in it. If
223/// this statement is not executed normally, it not containing a label means
224/// that we can just remove the code.
225bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
226 // Null statement, not a label!
227 if (S == 0) return false;
228
229 // If this is a label, we have to emit the code, consider something like:
230 // if (0) { ... foo: bar(); } goto foo;
231 if (isa<LabelStmt>(S))
232 return true;
233
234 // If this is a case/default statement, and we haven't seen a switch, we have
235 // to emit the code.
236 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
237 return true;
238
239 // If this is a switch statement, we want to ignore cases below it.
240 if (isa<SwitchStmt>(S))
241 IgnoreCaseStmts = true;
242
243 // Scan subexpressions for verboten labels.
244 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
245 I != E; ++I)
246 if (ContainsLabel(*I, IgnoreCaseStmts))
247 return true;
248
249 return false;
250}
251
Chris Lattner31a09842008-11-12 08:04:58 +0000252
253/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
254/// a constant, or if it does but contains a label, return 0. If it constant
255/// folds to 'true' and does not contain a label, return 1, if it constant folds
256/// to 'false' and does not contain a label, return -1.
257int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000258 // FIXME: Rename and handle conversion of other evaluatable things
259 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000260 Expr::EvalResult Result;
261 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
262 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000263 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000264
265 if (CodeGenFunction::ContainsLabel(Cond))
266 return 0; // Contains a label.
267
Anders Carlsson64712f12008-12-01 02:46:24 +0000268 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000269}
270
271
272/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
273/// statement) to the specified blocks. Based on the condition, this might try
274/// to simplify the codegen of the conditional based on the branch.
275///
276void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
277 llvm::BasicBlock *TrueBlock,
278 llvm::BasicBlock *FalseBlock) {
279 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
280 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
281
282 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
283 // Handle X && Y in a condition.
284 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
285 // If we have "1 && X", simplify the code. "0 && X" would have constant
286 // folded if the case was simple enough.
287 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
288 // br(1 && X) -> br(X).
289 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
290 }
291
292 // If we have "X && 1", simplify the code to use an uncond branch.
293 // "X && 0" would have been constant folded to 0.
294 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
295 // br(X && 1) -> br(X).
296 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
297 }
298
299 // Emit the LHS as a conditional. If the LHS conditional is false, we
300 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000301 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000302 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
303 EmitBlock(LHSTrue);
304
305 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
306 return;
307 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
308 // If we have "0 || X", simplify the code. "1 || X" would have constant
309 // folded if the case was simple enough.
310 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
311 // br(0 || X) -> br(X).
312 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
313 }
314
315 // If we have "X || 0", simplify the code to use an uncond branch.
316 // "X || 1" would have been constant folded to 1.
317 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
318 // br(X || 0) -> br(X).
319 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
320 }
321
322 // Emit the LHS as a conditional. If the LHS conditional is true, we
323 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000324 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000325 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
326 EmitBlock(LHSFalse);
327
328 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
329 return;
330 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000331 }
332
333 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
334 // br(!x, t, f) -> br(x, f, t)
335 if (CondUOp->getOpcode() == UnaryOperator::LNot)
336 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000337 }
338
Daniel Dunbar09b14892008-11-12 10:30:32 +0000339 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
340 // Handle ?: operator.
341
342 // Just ignore GNU ?: extension.
343 if (CondOp->getLHS()) {
344 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
345 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
346 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
347 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
348 EmitBlock(LHSBlock);
349 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
350 EmitBlock(RHSBlock);
351 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
352 return;
353 }
354 }
355
Chris Lattner31a09842008-11-12 08:04:58 +0000356 // Emit the code with the fully general case.
357 llvm::Value *CondV = EvaluateExprAsBool(Cond);
358 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
359}
360
Devang Patel88a981b2007-11-01 19:11:01 +0000361/// getCGRecordLayout - Return record layout info.
362const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000363 QualType Ty) {
364 const RecordType *RTy = Ty->getAsRecordType();
365 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000366
Chris Lattneraf319132008-02-05 06:55:31 +0000367 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000368}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000369
Daniel Dunbar488e9932008-08-16 00:56:44 +0000370/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000371/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000372void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
373 bool OmitOnError) {
374 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000375}
376
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000377unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
378 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
379 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
380}
381
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000382void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
383{
384 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
385 if (DestPtr->getType() != BP)
386 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
387
388 // Get size and alignment info for this aggregate.
389 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
390
391 // FIXME: Handle variable sized types.
392 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
393
394 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
395 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
396 // TypeInfo.first describes size in bits.
397 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
398 llvm::ConstantInt::get(llvm::Type::Int32Ty,
399 TypeInfo.second/8));
400}
401
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000402void CodeGenFunction::EmitIndirectSwitches() {
403 llvm::BasicBlock *Default;
404
Daniel Dunbar76526a52008-08-04 17:24:44 +0000405 if (IndirectSwitches.empty())
406 return;
407
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000408 if (!LabelIDs.empty()) {
409 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
410 } else {
411 // No possible targets for indirect goto, just emit an infinite
412 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000413 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000414 llvm::BranchInst::Create(Default, Default);
415 }
416
417 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
418 e = IndirectSwitches.end(); i != e; ++i) {
419 llvm::SwitchInst *I = *i;
420
421 I->setSuccessor(0, Default);
422 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
423 LE = LabelIDs.end(); LI != LE; ++LI) {
424 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
425 LI->second),
426 getBasicBlockForLabel(LI->first));
427 }
428 }
429}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000430
431llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
432{
433 // FIXME: This entire method is hardcoded for 32-bit X86.
434
435 const char *TargetPrefix = getContext().Target.getTargetPrefix();
436
437 if (strcmp(TargetPrefix, "x86") != 0 ||
438 getContext().Target.getPointerWidth(0) != 32)
439 return 0;
440
441 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
442 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
443
444 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
445 "ap");
446 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
447 llvm::Value *AddrTyped =
448 Builder.CreateBitCast(Addr,
449 llvm::PointerType::getUnqual(ConvertType(Ty)));
450
451 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
452 const unsigned ArgumentSizeInBytes = 4;
453 if (SizeInBytes < ArgumentSizeInBytes)
454 SizeInBytes = ArgumentSizeInBytes;
455
456 llvm::Value *NextAddr =
457 Builder.CreateGEP(Addr,
458 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
459 "ap.next");
460 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
461
462 return AddrTyped;
463}
464
Anders Carlssonf666b772008-12-20 20:27:15 +0000465
Anders Carlssondcc90d82008-12-12 07:19:02 +0000466llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
467{
468 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000469
Anders Carlssonf666b772008-12-20 20:27:15 +0000470 assert(SizeEntry && "Did not emit size for type");
471 return SizeEntry;
472}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000473
Anders Carlsson60d35412008-12-20 20:46:34 +0000474llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000475{
Anders Carlsson60d35412008-12-20 20:46:34 +0000476 assert(Ty->isVariablyModifiedType() &&
477 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000478
Anders Carlsson60d35412008-12-20 20:46:34 +0000479 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
480 llvm::Value *&SizeEntry = VLASizeMap[VAT];
481
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000482 if (!SizeEntry) {
483 // Get the element size;
484 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000485
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000486 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000487
488 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
489
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000490 if (ElemTy->isVariableArrayType())
491 ElemSize = EmitVLASize(ElemTy);
492 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000493 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000494 getContext().getTypeSize(ElemTy) / 8);
495 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000496
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000497 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000498 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
499
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000500 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000501 }
502
Anders Carlsson60d35412008-12-20 20:46:34 +0000503 return SizeEntry;
504 } else if (const PointerType *PT = Ty->getAsPointerType())
505 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000506 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000507 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000508 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000509
510 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000511}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000512
513llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
514 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
515 return EmitScalarExpr(E);
516 }
517 return EmitLValue(E).getAddress();
518}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000519
520llvm::BasicBlock *CodeGenFunction::CreateCleanupBlock()
521{
522 llvm::BasicBlock *CleanupBlock = createBasicBlock("cleanup");
523
524 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
525
526 return CleanupBlock;
527}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000528
529void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
530{
531 assert(CleanupEntries.size() >= OldCleanupStackSize &&
532 "Cleanup stack mismatch!");
533
534 while (CleanupEntries.size() > OldCleanupStackSize)
535 EmitCleanupBlock();
536}
537
538void CodeGenFunction::EmitCleanupBlock()
539{
540 CleanupEntry &CE = CleanupEntries.back();
541
542 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
543
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000544 std::vector<llvm::BasicBlock *> Blocks;
545 std::swap(Blocks, CE.Blocks);
546
547 std::vector<llvm::BranchInst *> BranchFixups;
548 std::swap(BranchFixups, CE.BranchFixups);
549
Anders Carlssonc71c8452009-02-07 23:50:39 +0000550 CleanupEntries.pop_back();
551
552 EmitBlock(CleanupBlock);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000553
554 if (!CleanupEntries.empty()) {
555 // Check if any branch fixups pointed to the scope we just popped. If so,
556 // we can remove them.
557 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
558 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
559 BlockScopeMap::iterator I = BlockScopes.find(Dest);
560
561 if (I == BlockScopes.end())
562 continue;
563
564 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
565
566 if (I->second == CleanupEntries.size()) {
567 // We don't need to do this branch fixup.
568 BranchFixups[i] = BranchFixups.back();
569 BranchFixups.pop_back();
570 i--;
571 e--;
572 continue;
573 }
574 }
575 }
576
577 if (!BranchFixups.empty()) {
578 llvm::BasicBlock *CleanupEnd = createBasicBlock("cleanup.end");
579
580 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.
585 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, CleanupEnd,
586 BranchFixups.size());
587 EmitBlock(CleanupEnd);
588
589 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
590 llvm::BranchInst *BI = BranchFixups[i];
591 llvm::BasicBlock *Dest = BI->getSuccessor(0);
592
593 // Store the jump destination before the branch instruction.
594 llvm::ConstantInt *DI =
595 llvm::ConstantInt::get(llvm::Type::Int32Ty, i + 1);
596 new llvm::StoreInst(DI, DestCodePtr, BI);
597
598 // Fixup the branch instruction to point to the cleanup block.
599 BI->setSuccessor(0, CleanupBlock);
600
601 if (CleanupEntries.empty()) {
602 SI->addCase(DI, Dest);
603 } else {
604 // We need to jump through another cleanup block. Create a pad block
605 // with a branch instruction that jumps to the final destination and
606 // add it as a branch fixup to the current cleanup scope.
607
608 // Create the pad block.
609 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
610
611 // Add it as the destination.
612 SI->addCase(DI, CleanupPad);
613
614 // Create the branch to the final destination.
615 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
616 CleanupPad->getInstList().push_back(BI);
617
618 // And add it as a branch fixup.
619 CleanupEntries.back().BranchFixups.push_back(BI);
620 }
621 }
622 }
623
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000624 // Remove all blocks from the block scope map.
625 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
626 assert(BlockScopes.count(Blocks[i]) &&
627 "Did not find block in scope map!");
628
629 BlockScopes.erase(Blocks[i]);
630 }
Anders Carlssonc71c8452009-02-07 23:50:39 +0000631}
632
Anders Carlsson87eaf172009-02-08 00:50:42 +0000633void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
634{
635 assert(!CleanupEntries.empty() &&
636 "Trying to add branch fixup without cleanup block!");
637
638 // FIXME: We could be more clever here and check if there's already a
639 // branch fixup for this destination and recycle it.
640 CleanupEntries.back().BranchFixups.push_back(BI);
641}
642
643void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
644{
645 llvm::BranchInst* BI = Builder.CreateBr(Dest);
646
647 // The stack is empty, no need to do any cleanup.
648 if (CleanupEntries.empty())
649 return;
650
651 if (!Dest->getParent()) {
652 // We are trying to branch to a block that hasn't been inserted yet.
653 AddBranchFixup(BI);
654 return;
655 }
656
657 BlockScopeMap::iterator I = BlockScopes.find(Dest);
658 if (I == BlockScopes.end()) {
659 // We are trying to jump to a block that is outside of any cleanup scope.
660 AddBranchFixup(BI);
661 return;
662 }
663
664 assert(I->second < CleanupEntries.size() &&
665 "Trying to branch into cleanup region");
666
667 if (I->second == CleanupEntries.size() - 1) {
668 // We have a branch to a block in the same scope.
669 return;
670 }
671
672 AddBranchFixup(BI);
673}