blob: 68d10ff56ed7e510bb87521ccec382d5e97536b4 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +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 Friedman9bc7c8d2008-05-22 01:40:10 +000016#include "CGDebugInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/Basic/TargetInfo.h"
Chris Lattner3d6606b2008-11-12 08:04:58 +000018#include "clang/AST/APValue.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000020#include "clang/AST/Decl.h"
Devang Patel97299362007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023using namespace clang;
24using namespace CodeGen;
25
26CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpecd79422009-03-06 01:33:24 +000027 : BlockFunction(cgm, *this, Builder), CGM(cgm),
28 Target(CGM.getContext().Target),
Mike Stumpa79696d2009-03-04 18:57:26 +000029 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0) {
Mike Stumpfca5da02009-02-21 20:00:35 +000030 LLVMIntTy = ConvertType(getContext().IntTy);
31 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner8c7c6a12008-06-17 18:05:57 +000032}
Chris Lattner4b009652007-07-25 00:24:17 +000033
34ASTContext &CodeGenFunction::getContext() const {
35 return CGM.getContext();
36}
37
38
39llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
40 llvm::BasicBlock *&BB = LabelMap[S];
41 if (BB) return BB;
42
43 // Create, but don't insert, the new block.
Daniel Dunbar72f96552008-11-11 02:29:29 +000044 return BB = createBasicBlock(S->getName());
Chris Lattner4b009652007-07-25 00:24:17 +000045}
46
Daniel Dunbardea59212009-02-25 19:24:29 +000047llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
48 llvm::Value *Res = LocalDeclMap[VD];
49 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
50 return Res;
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000051}
Chris Lattner4b009652007-07-25 00:24:17 +000052
Daniel Dunbardea59212009-02-25 19:24:29 +000053llvm::Constant *
54CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
55 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson75d86732008-09-11 09:15:33 +000056}
57
Daniel Dunbar706059f2009-02-03 23:03:55 +000058const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
59 return CGM.getTypes().ConvertTypeForMem(T);
60}
61
Chris Lattner4b009652007-07-25 00:24:17 +000062const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
63 return CGM.getTypes().ConvertType(T);
64}
65
66bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbar96891242009-01-09 02:44:18 +000067 // FIXME: Use positive checks instead of negative ones to be more
68 // robust in the face of extension.
Daniel Dunbarfc096bf2009-02-26 20:52:22 +000069 return !T->hasPointerRepresentation() &&!T->isRealType() &&
70 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbar96891242009-01-09 02:44:18 +000071 !T->isBlockPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +000072}
73
Daniel Dunbar924f4ea2009-01-26 23:27:52 +000074void CodeGenFunction::EmitReturnBlock() {
75 // For cleanliness, we try to avoid emitting the return block for
76 // simple cases.
77 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
78
79 if (CurBB) {
80 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
81
82 // We have a valid insert point, reuse it if there are no explicit
83 // jumps to the return block.
84 if (ReturnBlock->use_empty())
85 delete ReturnBlock;
86 else
87 EmitBlock(ReturnBlock);
88 return;
89 }
90
91 // Otherwise, if the return block is the target of a single direct
92 // branch then we can just put the code in that block instead. This
93 // cleans up functions which started with a unified return block.
94 if (ReturnBlock->hasOneUse()) {
95 llvm::BranchInst *BI =
96 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
97 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
98 // Reset insertion point and delete the branch.
99 Builder.SetInsertPoint(BI->getParent());
100 BI->eraseFromParent();
101 delete ReturnBlock;
102 return;
103 }
104 }
105
106 // FIXME: We are at an unreachable point, there is no reason to emit
107 // the block unless it has uses. However, we still need a place to
108 // put the debug region.end for now.
109
110 EmitBlock(ReturnBlock);
111}
112
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000113void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar879788d2008-08-04 16:51:22 +0000114 // Finish emission of indirect switches.
115 EmitIndirectSwitches();
116
Chris Lattner4b009652007-07-25 00:24:17 +0000117 assert(BreakContinueStack.empty() &&
118 "mismatched push/pop in break/continue stack!");
Anders Carlssone7de3522009-02-08 00:16:35 +0000119 assert(BlockScopes.empty() &&
120 "did not remove all blocks from block scope map!");
121 assert(CleanupEntries.empty() &&
122 "mismatched push/pop in cleanup stack!");
123
Daniel Dunbar924f4ea2009-01-26 23:27:52 +0000124 // Emit function epilog (to return).
125 EmitReturnBlock();
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000126
127 // Emit debug descriptor for function end.
Anders Carlsson73007792009-02-13 08:11:52 +0000128 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000129 DI->setLocation(EndLoc);
130 DI->EmitRegionEnd(CurFn, Builder);
131 }
132
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000133 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000134
Chris Lattnerca929812007-12-02 06:32:24 +0000135 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
136 AllocaInsertPt->eraseFromParent();
137 AllocaInsertPt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +0000138}
139
Daniel Dunbar96816832008-09-09 23:14:03 +0000140void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
141 llvm::Function *Fn,
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000142 const FunctionArgList &Args,
143 SourceLocation StartLoc) {
Anders Carlsson60c4c402009-02-09 20:20:56 +0000144 DidCallStackSave = false;
Daniel Dunbar96816832008-09-09 23:14:03 +0000145 CurFuncDecl = D;
146 FnRetTy = RetTy;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000147 CurFn = Fn;
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000148 assert(CurFn->isDeclaration() && "Function already has body?");
149
Daniel Dunbar72f96552008-11-11 02:29:29 +0000150 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000151
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000152 // Create a marker to make it easy to insert allocas into the entryblock
153 // later. Don't create this with the builder, because we don't want it
154 // folded.
155 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
Chris Lattner7fbb70d2009-03-22 00:24:14 +0000156 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000157 EntryBB);
Chris Lattner7fbb70d2009-03-22 00:24:14 +0000158 if (Builder.isNamePreserving())
159 AllocaInsertPt->setName("allocapt");
160
Daniel Dunbar72f96552008-11-11 02:29:29 +0000161 ReturnBlock = createBasicBlock("return");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000162 ReturnValue = 0;
Daniel Dunbar96816832008-09-09 23:14:03 +0000163 if (!RetTy->isVoidType())
164 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000165
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000166 Builder.SetInsertPoint(EntryBB);
167
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000168 // Emit subprogram debug descriptor.
Daniel Dunbar96816832008-09-09 23:14:03 +0000169 // FIXME: The cast here is a huge hack.
Anders Carlsson73007792009-02-13 08:11:52 +0000170 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000171 DI->setLocation(StartLoc);
172 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000173 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000174 } else {
175 // Just use LLVM function name.
176 DI->EmitFunctionStart(Fn->getName().c_str(),
177 RetTy, CurFn, Builder);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000178 }
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000179 }
180
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000181 // FIXME: Leaked.
Daniel Dunbar34bda882009-02-02 23:23:47 +0000182 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000183 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson21cecd42008-12-20 21:28:43 +0000184
185 // If any of the arguments have a variably modified type, make sure to
186 // emit the type size.
187 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
188 i != e; ++i) {
189 QualType Ty = i->second;
190
191 if (Ty->isVariablyModifiedType())
192 EmitVLASize(Ty);
193 }
Daniel Dunbar96816832008-09-09 23:14:03 +0000194}
Eli Friedman769e7302008-08-25 21:31:01 +0000195
Daniel Dunbar96816832008-09-09 23:14:03 +0000196void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
197 llvm::Function *Fn) {
Anders Carlsson73007792009-02-13 08:11:52 +0000198 // Check if we should generate debug info for this function.
199 if (CGM.getDebugInfo() && !FD->getAttr<NodebugAttr>())
200 DebugInfo = CGM.getDebugInfo();
201
Daniel Dunbar96816832008-09-09 23:14:03 +0000202 FunctionArgList Args;
Eli Friedman769e7302008-08-25 21:31:01 +0000203 if (FD->getNumParams()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000204 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedman769e7302008-08-25 21:31:01 +0000205 assert(FProto && "Function def must have prototype!");
Daniel Dunbar96816832008-09-09 23:14:03 +0000206
207 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
208 Args.push_back(std::make_pair(FD->getParamDecl(i),
209 FProto->getArgType(i)));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000210 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000211
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000212 StartFunction(FD, FD->getResultType(), Fn, Args,
213 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar96816832008-09-09 23:14:03 +0000214
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000215 EmitStmt(FD->getBody());
216
217 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
218 if (S) {
219 FinishFunction(S->getRBracLoc());
220 } else {
221 FinishFunction();
222 }
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000223}
224
Chris Lattner3f73d0d2008-11-11 07:41:27 +0000225/// ContainsLabel - Return true if the statement contains a label in it. If
226/// this statement is not executed normally, it not containing a label means
227/// that we can just remove the code.
228bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
229 // Null statement, not a label!
230 if (S == 0) return false;
231
232 // If this is a label, we have to emit the code, consider something like:
233 // if (0) { ... foo: bar(); } goto foo;
234 if (isa<LabelStmt>(S))
235 return true;
236
237 // If this is a case/default statement, and we haven't seen a switch, we have
238 // to emit the code.
239 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
240 return true;
241
242 // If this is a switch statement, we want to ignore cases below it.
243 if (isa<SwitchStmt>(S))
244 IgnoreCaseStmts = true;
245
246 // Scan subexpressions for verboten labels.
247 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
248 I != E; ++I)
249 if (ContainsLabel(*I, IgnoreCaseStmts))
250 return true;
251
252 return false;
253}
254
Chris Lattner3d6606b2008-11-12 08:04:58 +0000255
256/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
257/// a constant, or if it does but contains a label, return 0. If it constant
258/// folds to 'true' and does not contain a label, return 1, if it constant folds
259/// to 'false' and does not contain a label, return -1.
260int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar14937022008-11-12 22:37:10 +0000261 // FIXME: Rename and handle conversion of other evaluatable things
262 // to bool.
Anders Carlsson90d85f32008-12-01 02:46:24 +0000263 Expr::EvalResult Result;
264 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
265 Result.HasSideEffects)
Anders Carlssonea3c6ab2008-11-22 22:32:07 +0000266 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner3d6606b2008-11-12 08:04:58 +0000267
268 if (CodeGenFunction::ContainsLabel(Cond))
269 return 0; // Contains a label.
270
Anders Carlsson90d85f32008-12-01 02:46:24 +0000271 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner3d6606b2008-11-12 08:04:58 +0000272}
273
274
275/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
276/// statement) to the specified blocks. Based on the condition, this might try
277/// to simplify the codegen of the conditional based on the branch.
278///
279void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
280 llvm::BasicBlock *TrueBlock,
281 llvm::BasicBlock *FalseBlock) {
282 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
283 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
284
285 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
286 // Handle X && Y in a condition.
287 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
288 // If we have "1 && X", simplify the code. "0 && X" would have constant
289 // folded if the case was simple enough.
290 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
291 // br(1 && X) -> br(X).
292 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
293 }
294
295 // If we have "X && 1", simplify the code to use an uncond branch.
296 // "X && 0" would have been constant folded to 0.
297 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
298 // br(X && 1) -> br(X).
299 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
300 }
301
302 // Emit the LHS as a conditional. If the LHS conditional is false, we
303 // want to jump to the FalseBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000304 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000305 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
306 EmitBlock(LHSTrue);
307
308 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
309 return;
310 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
311 // If we have "0 || X", simplify the code. "1 || X" would have constant
312 // folded if the case was simple enough.
313 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
314 // br(0 || X) -> br(X).
315 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
316 }
317
318 // If we have "X || 0", simplify the code to use an uncond branch.
319 // "X || 1" would have been constant folded to 1.
320 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
321 // br(X || 0) -> br(X).
322 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
323 }
324
325 // Emit the LHS as a conditional. If the LHS conditional is true, we
326 // want to jump to the TrueBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000327 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000328 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
329 EmitBlock(LHSFalse);
330
331 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
332 return;
333 }
Chris Lattnercfbfe912008-11-12 08:13:36 +0000334 }
335
336 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
337 // br(!x, t, f) -> br(x, f, t)
338 if (CondUOp->getOpcode() == UnaryOperator::LNot)
339 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000340 }
341
Daniel Dunbarab81c632008-11-12 10:30:32 +0000342 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
343 // Handle ?: operator.
344
345 // Just ignore GNU ?: extension.
346 if (CondOp->getLHS()) {
347 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
348 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
349 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
350 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
351 EmitBlock(LHSBlock);
352 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
353 EmitBlock(RHSBlock);
354 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
355 return;
356 }
357 }
358
Chris Lattner3d6606b2008-11-12 08:04:58 +0000359 // Emit the code with the fully general case.
360 llvm::Value *CondV = EvaluateExprAsBool(Cond);
361 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
362}
363
Devang Patel7a78e432007-11-01 19:11:01 +0000364/// getCGRecordLayout - Return record layout info.
365const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000366 QualType Ty) {
367 const RecordType *RTy = Ty->getAsRecordType();
368 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000369
Chris Lattner7b2543e2008-02-05 06:55:31 +0000370 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000371}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000372
Daniel Dunbar9503b782008-08-16 00:56:44 +0000373/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner9d4e6202007-12-02 01:43:38 +0000374/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000375void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
376 bool OmitOnError) {
377 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000378}
379
Daniel Dunbar879788d2008-08-04 16:51:22 +0000380unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
381 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
382 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
383}
384
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000385void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
386{
387 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
388 if (DestPtr->getType() != BP)
389 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
390
391 // Get size and alignment info for this aggregate.
392 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
393
394 // FIXME: Handle variable sized types.
395 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
396
397 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
398 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
399 // TypeInfo.first describes size in bits.
400 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
401 llvm::ConstantInt::get(llvm::Type::Int32Ty,
402 TypeInfo.second/8));
403}
404
Daniel Dunbar879788d2008-08-04 16:51:22 +0000405void CodeGenFunction::EmitIndirectSwitches() {
406 llvm::BasicBlock *Default;
407
Daniel Dunbar8ccfa802008-08-04 17:24:44 +0000408 if (IndirectSwitches.empty())
409 return;
410
Daniel Dunbar879788d2008-08-04 16:51:22 +0000411 if (!LabelIDs.empty()) {
412 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
413 } else {
414 // No possible targets for indirect goto, just emit an infinite
415 // loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000416 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000417 llvm::BranchInst::Create(Default, Default);
418 }
419
420 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
421 e = IndirectSwitches.end(); i != e; ++i) {
422 llvm::SwitchInst *I = *i;
423
424 I->setSuccessor(0, Default);
425 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
426 LE = LabelIDs.end(); LI != LE; ++LI) {
427 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
428 LI->second),
429 getBasicBlockForLabel(LI->first));
430 }
431 }
432}
Anders Carlsson285611e2008-11-04 05:30:00 +0000433
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000434llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
435{
436 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000437
Anders Carlssonf860e022008-12-20 20:27:15 +0000438 assert(SizeEntry && "Did not emit size for type");
439 return SizeEntry;
440}
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000441
Anders Carlssond9767612008-12-20 20:46:34 +0000442llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf860e022008-12-20 20:27:15 +0000443{
Anders Carlssond9767612008-12-20 20:46:34 +0000444 assert(Ty->isVariablyModifiedType() &&
445 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf860e022008-12-20 20:27:15 +0000446
Anders Carlssond9767612008-12-20 20:46:34 +0000447 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
448 llvm::Value *&SizeEntry = VLASizeMap[VAT];
449
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000450 if (!SizeEntry) {
451 // Get the element size;
452 llvm::Value *ElemSize;
Anders Carlssond9767612008-12-20 20:46:34 +0000453
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000454 QualType ElemTy = VAT->getElementType();
Anders Carlsson8f30de92009-02-05 19:43:10 +0000455
456 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
457
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000458 if (ElemTy->isVariableArrayType())
459 ElemSize = EmitVLASize(ElemTy);
460 else {
Anders Carlsson8f30de92009-02-05 19:43:10 +0000461 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000462 getContext().getTypeSize(ElemTy) / 8);
463 }
Anders Carlssond9767612008-12-20 20:46:34 +0000464
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000465 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson8f30de92009-02-05 19:43:10 +0000466 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
467
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000468 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlssond9767612008-12-20 20:46:34 +0000469 }
470
Anders Carlssond9767612008-12-20 20:46:34 +0000471 return SizeEntry;
472 } else if (const PointerType *PT = Ty->getAsPointerType())
473 EmitVLASize(PT->getPointeeType());
Anders Carlssonf860e022008-12-20 20:27:15 +0000474 else {
Anders Carlssond9767612008-12-20 20:46:34 +0000475 assert(0 && "unknown VM type!");
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000476 }
Anders Carlssond9767612008-12-20 20:46:34 +0000477
478 return 0;
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000479}
Eli Friedman8f5e8782009-01-20 17:46:04 +0000480
481llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
482 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
483 return EmitScalarExpr(E);
484 }
485 return EmitLValue(E).getAddress();
486}
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000487
Anders Carlsson459ee362009-02-08 03:22:36 +0000488void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000489{
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000490 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000491}
Anders Carlsson883fa552009-02-07 23:50:39 +0000492
493void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
494{
495 assert(CleanupEntries.size() >= OldCleanupStackSize &&
496 "Cleanup stack mismatch!");
497
498 while (CleanupEntries.size() > OldCleanupStackSize)
499 EmitCleanupBlock();
500}
501
Anders Carlssondf274192009-02-08 07:46:24 +0000502CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlsson883fa552009-02-07 23:50:39 +0000503{
Anders Carlssondf274192009-02-08 07:46:24 +0000504 CleanupEntry &CE = CleanupEntries.back();
505
506 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
507
508 std::vector<llvm::BasicBlock *> Blocks;
509 std::swap(Blocks, CE.Blocks);
510
511 std::vector<llvm::BranchInst *> BranchFixups;
512 std::swap(BranchFixups, CE.BranchFixups);
513
514 CleanupEntries.pop_back();
515
Anders Carlsson98720f02009-02-08 22:45:15 +0000516 // Check if any branch fixups pointed to the scope we just popped. If so,
517 // we can remove them.
518 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
519 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
520 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000521
Anders Carlsson98720f02009-02-08 22:45:15 +0000522 if (I == BlockScopes.end())
523 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000524
Anders Carlsson98720f02009-02-08 22:45:15 +0000525 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000526
Anders Carlsson98720f02009-02-08 22:45:15 +0000527 if (I->second == CleanupEntries.size()) {
528 // We don't need to do this branch fixup.
529 BranchFixups[i] = BranchFixups.back();
530 BranchFixups.pop_back();
531 i--;
532 e--;
533 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000534 }
535 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000536
Anders Carlssondf274192009-02-08 07:46:24 +0000537 llvm::BasicBlock *SwitchBlock = 0;
538 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson9b399792009-02-08 01:23:05 +0000539 if (!BranchFixups.empty()) {
Anders Carlssondf274192009-02-08 07:46:24 +0000540 SwitchBlock = createBasicBlock("cleanup.switch");
541 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson9b399792009-02-08 01:23:05 +0000542
Anders Carlssondf274192009-02-08 07:46:24 +0000543 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000544
Anders Carlssondf274192009-02-08 07:46:24 +0000545 Builder.SetInsertPoint(SwitchBlock);
546
Anders Carlsson9b399792009-02-08 01:23:05 +0000547 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
548 "cleanup.dst");
549 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
550
551 // Create a switch instruction to determine where to jump next.
Anders Carlssondf274192009-02-08 07:46:24 +0000552 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson9b399792009-02-08 01:23:05 +0000553 BranchFixups.size());
Anders Carlssondf274192009-02-08 07:46:24 +0000554
Anders Carlsson32fffb72009-02-08 22:13:37 +0000555 // Restore the current basic block (if any)
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000556 if (CurBB) {
Anders Carlsson32fffb72009-02-08 22:13:37 +0000557 Builder.SetInsertPoint(CurBB);
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000558
559 // If we had a current basic block, we also need to emit an instruction
560 // to initialize the cleanup destination.
561 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::Int32Ty),
562 DestCodePtr);
563 } else
Anders Carlsson32fffb72009-02-08 22:13:37 +0000564 Builder.ClearInsertionPoint();
Anders Carlssondf274192009-02-08 07:46:24 +0000565
Anders Carlsson9b399792009-02-08 01:23:05 +0000566 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
567 llvm::BranchInst *BI = BranchFixups[i];
568 llvm::BasicBlock *Dest = BI->getSuccessor(0);
569
Anders Carlsson9b399792009-02-08 01:23:05 +0000570 // Fixup the branch instruction to point to the cleanup block.
571 BI->setSuccessor(0, CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000572
Anders Carlsson9b399792009-02-08 01:23:05 +0000573 if (CleanupEntries.empty()) {
Anders Carlsson8be63402009-02-08 22:46:50 +0000574 llvm::ConstantInt *ID;
575
576 // Check if we already have a destination for this block.
577 if (Dest == SI->getDefaultDest())
578 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
579 else {
580 ID = SI->findCaseDest(Dest);
581 if (!ID) {
582 // No code found, get a new unique one by using the number of
583 // switch successors.
584 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
585 SI->getNumSuccessors());
586 SI->addCase(ID, Dest);
587 }
588 }
589
590 // Store the jump destination before the branch instruction.
591 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson9b399792009-02-08 01:23:05 +0000592 } else {
593 // We need to jump through another cleanup block. Create a pad block
594 // with a branch instruction that jumps to the final destination and
595 // add it as a branch fixup to the current cleanup scope.
596
597 // Create the pad block.
598 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson8be63402009-02-08 22:46:50 +0000599
600 // Create a unique case ID.
601 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
602 SI->getNumSuccessors());
603
604 // Store the jump destination before the branch instruction.
605 new llvm::StoreInst(ID, DestCodePtr, BI);
606
Anders Carlsson9b399792009-02-08 01:23:05 +0000607 // Add it as the destination.
Anders Carlsson8be63402009-02-08 22:46:50 +0000608 SI->addCase(ID, CleanupPad);
Anders Carlsson9b399792009-02-08 01:23:05 +0000609
610 // Create the branch to the final destination.
611 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
612 CleanupPad->getInstList().push_back(BI);
613
614 // And add it as a branch fixup.
615 CleanupEntries.back().BranchFixups.push_back(BI);
616 }
617 }
618 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000619
Anders Carlssone7de3522009-02-08 00:16:35 +0000620 // Remove all blocks from the block scope map.
621 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
622 assert(BlockScopes.count(Blocks[i]) &&
623 "Did not find block in scope map!");
624
625 BlockScopes.erase(Blocks[i]);
626 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000627
Anders Carlssondf274192009-02-08 07:46:24 +0000628 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000629}
630
631void CodeGenFunction::EmitCleanupBlock()
632{
Anders Carlssondf274192009-02-08 07:46:24 +0000633 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000634
Anders Carlssondf274192009-02-08 07:46:24 +0000635 EmitBlock(Info.CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000636
Anders Carlssondf274192009-02-08 07:46:24 +0000637 if (Info.SwitchBlock)
638 EmitBlock(Info.SwitchBlock);
639 if (Info.EndBlock)
640 EmitBlock(Info.EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000641}
642
Anders Carlssoned536bc2009-02-08 00:50:42 +0000643void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
644{
645 assert(!CleanupEntries.empty() &&
646 "Trying to add branch fixup without cleanup block!");
647
648 // FIXME: We could be more clever here and check if there's already a
649 // branch fixup for this destination and recycle it.
650 CleanupEntries.back().BranchFixups.push_back(BI);
651}
652
653void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
654{
Anders Carlsson32fffb72009-02-08 22:13:37 +0000655 if (!HaveInsertPoint())
656 return;
657
Anders Carlssoned536bc2009-02-08 00:50:42 +0000658 llvm::BranchInst* BI = Builder.CreateBr(Dest);
659
Anders Carlsson32fffb72009-02-08 22:13:37 +0000660 Builder.ClearInsertionPoint();
661
Anders Carlssoned536bc2009-02-08 00:50:42 +0000662 // The stack is empty, no need to do any cleanup.
663 if (CleanupEntries.empty())
664 return;
665
666 if (!Dest->getParent()) {
667 // We are trying to branch to a block that hasn't been inserted yet.
668 AddBranchFixup(BI);
669 return;
670 }
671
672 BlockScopeMap::iterator I = BlockScopes.find(Dest);
673 if (I == BlockScopes.end()) {
674 // We are trying to jump to a block that is outside of any cleanup scope.
675 AddBranchFixup(BI);
676 return;
677 }
678
679 assert(I->second < CleanupEntries.size() &&
680 "Trying to branch into cleanup region");
681
682 if (I->second == CleanupEntries.size() - 1) {
683 // We have a branch to a block in the same scope.
684 return;
685 }
686
687 AddBranchFixup(BI);
688}