blob: 879b85891de6088b1ebceecaab3cdec3cb39ba85 [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"
Mike Stump4e7a1f72009-02-21 20:00:35 +000022#include "llvm/Target/TargetData.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023using namespace clang;
24using namespace CodeGen;
25
26CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Anders Carlssone896d982009-02-13 08:11:52 +000027 : CGM(cgm), Target(CGM.getContext().Target), DebugInfo(0), SwitchInsn(0),
Daniel Dunbar9834ffb2009-02-23 17:26:39 +000028 CaseRangeBlock(0), InvokeDest(0) {
Mike Stump4e7a1f72009-02-21 20:00:35 +000029 LLVMIntTy = ConvertType(getContext().IntTy);
30 LLVMPointerWidth = Target.getPointerWidth(0);
31
32 // FIXME: We need to rearrange the code for copy/dispose so we have this
33 // sooner, so we can calculate offsets correctly.
34 BlockHasCopyDispose = false;
35 if (!BlockHasCopyDispose)
36 BlockOffset = CGM.getTargetData()
37 .getTypeStoreSizeInBits(CGM.getGenericBlockLiteralType()) / 8;
38 else
39 BlockOffset = CGM.getTargetData()
40 .getTypeStoreSizeInBits(CGM.getGenericExtendedBlockLiteralType()) / 8;
Chris Lattner41110242008-06-17 18:05:57 +000041}
Reid Spencer5f016e22007-07-11 17:01:13 +000042
43ASTContext &CodeGenFunction::getContext() const {
44 return CGM.getContext();
45}
46
47
48llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
49 llvm::BasicBlock *&BB = LabelMap[S];
50 if (BB) return BB;
51
52 // Create, but don't insert, the new block.
Daniel Dunbar55e87422008-11-11 02:29:29 +000053 return BB = createBasicBlock(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000054}
55
Daniel Dunbar0096acf2009-02-25 19:24:29 +000056llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
57 llvm::Value *Res = LocalDeclMap[VD];
58 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
59 return Res;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000060}
Reid Spencer5f016e22007-07-11 17:01:13 +000061
Daniel Dunbar0096acf2009-02-25 19:24:29 +000062llvm::Constant *
63CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
64 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlssondde0a942008-09-11 09:15:33 +000065}
66
Daniel Dunbar8b1a3432009-02-03 23:03:55 +000067const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
68 return CGM.getTypes().ConvertTypeForMem(T);
69}
70
Reid Spencer5f016e22007-07-11 17:01:13 +000071const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
72 return CGM.getTypes().ConvertType(T);
73}
74
Chris Lattner41110242008-06-17 18:05:57 +000075bool CodeGenFunction::isObjCPointerType(QualType T) {
76 // All Objective-C types are pointers.
77 return T->isObjCInterfaceType() ||
78 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
79}
80
Reid Spencer5f016e22007-07-11 17:01:13 +000081bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbara782ca72009-01-09 02:44:18 +000082 // FIXME: Use positive checks instead of negative ones to be more
83 // robust in the face of extension.
Chris Lattner41110242008-06-17 18:05:57 +000084 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
Daniel Dunbara782ca72009-01-09 02:44:18 +000085 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
86 !T->isBlockPointerType();
Reid Spencer5f016e22007-07-11 17:01:13 +000087}
88
Daniel Dunbar1c1d6072009-01-26 23:27:52 +000089void CodeGenFunction::EmitReturnBlock() {
90 // For cleanliness, we try to avoid emitting the return block for
91 // simple cases.
92 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
93
94 if (CurBB) {
95 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
96
97 // We have a valid insert point, reuse it if there are no explicit
98 // jumps to the return block.
99 if (ReturnBlock->use_empty())
100 delete ReturnBlock;
101 else
102 EmitBlock(ReturnBlock);
103 return;
104 }
105
106 // Otherwise, if the return block is the target of a single direct
107 // branch then we can just put the code in that block instead. This
108 // cleans up functions which started with a unified return block.
109 if (ReturnBlock->hasOneUse()) {
110 llvm::BranchInst *BI =
111 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
112 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
113 // Reset insertion point and delete the branch.
114 Builder.SetInsertPoint(BI->getParent());
115 BI->eraseFromParent();
116 delete ReturnBlock;
117 return;
118 }
119 }
120
121 // FIXME: We are at an unreachable point, there is no reason to emit
122 // the block unless it has uses. However, we still need a place to
123 // put the debug region.end for now.
124
125 EmitBlock(ReturnBlock);
126}
127
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000128void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000129 // Finish emission of indirect switches.
130 EmitIndirectSwitches();
131
Chris Lattnerda138702007-07-16 21:28:45 +0000132 assert(BreakContinueStack.empty() &&
133 "mismatched push/pop in break/continue stack!");
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000134 assert(BlockScopes.empty() &&
135 "did not remove all blocks from block scope map!");
136 assert(CleanupEntries.empty() &&
137 "mismatched push/pop in cleanup stack!");
138
Daniel Dunbar1c1d6072009-01-26 23:27:52 +0000139 // Emit function epilog (to return).
140 EmitReturnBlock();
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000141
142 // Emit debug descriptor for function end.
Anders Carlssone896d982009-02-13 08:11:52 +0000143 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbarf5bd45c2008-11-11 20:59:54 +0000144 DI->setLocation(EndLoc);
145 DI->EmitRegionEnd(CurFn, Builder);
146 }
147
Daniel Dunbar88b53962009-02-02 22:03:45 +0000148 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000149
Chris Lattner5a2fa142007-12-02 06:32:24 +0000150 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
151 AllocaInsertPt->eraseFromParent();
152 AllocaInsertPt = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000153}
154
Daniel Dunbar7c086512008-09-09 23:14:03 +0000155void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
156 llvm::Function *Fn,
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000157 const FunctionArgList &Args,
158 SourceLocation StartLoc) {
Anders Carlsson4cc1a472009-02-09 20:20:56 +0000159 DidCallStackSave = false;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000160 CurFuncDecl = D;
161 FnRetTy = RetTy;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000162 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000163 assert(CurFn->isDeclaration() && "Function already has body?");
164
Daniel Dunbar55e87422008-11-11 02:29:29 +0000165 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000166
Chris Lattner41110242008-06-17 18:05:57 +0000167 // Create a marker to make it easy to insert allocas into the entryblock
168 // later. Don't create this with the builder, because we don't want it
169 // folded.
170 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
171 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
172 EntryBB);
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000173
Daniel Dunbar55e87422008-11-11 02:29:29 +0000174 ReturnBlock = createBasicBlock("return");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000175 ReturnValue = 0;
Daniel Dunbar7c086512008-09-09 23:14:03 +0000176 if (!RetTy->isVoidType())
177 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar5ca20842008-09-09 21:00:17 +0000178
Chris Lattner41110242008-06-17 18:05:57 +0000179 Builder.SetInsertPoint(EntryBB);
180
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000181 // Emit subprogram debug descriptor.
Daniel Dunbar7c086512008-09-09 23:14:03 +0000182 // FIXME: The cast here is a huge hack.
Anders Carlssone896d982009-02-13 08:11:52 +0000183 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000184 DI->setLocation(StartLoc);
185 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6ec36682009-02-18 23:53:56 +0000186 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000187 } else {
188 // Just use LLVM function name.
189 DI->EmitFunctionStart(Fn->getName().c_str(),
190 RetTy, CurFn, Builder);
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000191 }
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000192 }
193
Daniel Dunbar88b53962009-02-02 22:03:45 +0000194 // FIXME: Leaked.
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000195 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar88b53962009-02-02 22:03:45 +0000196 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson751358f2008-12-20 21:28:43 +0000197
198 // If any of the arguments have a variably modified type, make sure to
199 // emit the type size.
200 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
201 i != e; ++i) {
202 QualType Ty = i->second;
203
204 if (Ty->isVariablyModifiedType())
205 EmitVLASize(Ty);
206 }
Daniel Dunbar7c086512008-09-09 23:14:03 +0000207}
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000208
Daniel Dunbar7c086512008-09-09 23:14:03 +0000209void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
210 llvm::Function *Fn) {
Anders Carlssone896d982009-02-13 08:11:52 +0000211 // Check if we should generate debug info for this function.
212 if (CGM.getDebugInfo() && !FD->getAttr<NodebugAttr>())
213 DebugInfo = CGM.getDebugInfo();
214
Daniel Dunbar7c086512008-09-09 23:14:03 +0000215 FunctionArgList Args;
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000216 if (FD->getNumParams()) {
217 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
218 assert(FProto && "Function def must have prototype!");
Daniel Dunbar7c086512008-09-09 23:14:03 +0000219
220 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
221 Args.push_back(std::make_pair(FD->getParamDecl(i),
222 FProto->getArgType(i)));
Chris Lattner41110242008-06-17 18:05:57 +0000223 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000224
Daniel Dunbar2284ac92008-10-18 18:22:23 +0000225 StartFunction(FD, FD->getResultType(), Fn, Args,
226 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar7c086512008-09-09 23:14:03 +0000227
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000228 EmitStmt(FD->getBody());
229
230 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
231 if (S) {
232 FinishFunction(S->getRBracLoc());
233 } else {
234 FinishFunction();
235 }
Chris Lattner41110242008-06-17 18:05:57 +0000236}
237
Chris Lattner0946ccd2008-11-11 07:41:27 +0000238/// ContainsLabel - Return true if the statement contains a label in it. If
239/// this statement is not executed normally, it not containing a label means
240/// that we can just remove the code.
241bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
242 // Null statement, not a label!
243 if (S == 0) return false;
244
245 // If this is a label, we have to emit the code, consider something like:
246 // if (0) { ... foo: bar(); } goto foo;
247 if (isa<LabelStmt>(S))
248 return true;
249
250 // If this is a case/default statement, and we haven't seen a switch, we have
251 // to emit the code.
252 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
253 return true;
254
255 // If this is a switch statement, we want to ignore cases below it.
256 if (isa<SwitchStmt>(S))
257 IgnoreCaseStmts = true;
258
259 // Scan subexpressions for verboten labels.
260 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
261 I != E; ++I)
262 if (ContainsLabel(*I, IgnoreCaseStmts))
263 return true;
264
265 return false;
266}
267
Chris Lattner31a09842008-11-12 08:04:58 +0000268
269/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
270/// a constant, or if it does but contains a label, return 0. If it constant
271/// folds to 'true' and does not contain a label, return 1, if it constant folds
272/// to 'false' and does not contain a label, return -1.
273int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar36bc14c2008-11-12 22:37:10 +0000274 // FIXME: Rename and handle conversion of other evaluatable things
275 // to bool.
Anders Carlsson64712f12008-12-01 02:46:24 +0000276 Expr::EvalResult Result;
277 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
278 Result.HasSideEffects)
Anders Carlssonef5a66d2008-11-22 22:32:07 +0000279 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner31a09842008-11-12 08:04:58 +0000280
281 if (CodeGenFunction::ContainsLabel(Cond))
282 return 0; // Contains a label.
283
Anders Carlsson64712f12008-12-01 02:46:24 +0000284 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner31a09842008-11-12 08:04:58 +0000285}
286
287
288/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
289/// statement) to the specified blocks. Based on the condition, this might try
290/// to simplify the codegen of the conditional based on the branch.
291///
292void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
293 llvm::BasicBlock *TrueBlock,
294 llvm::BasicBlock *FalseBlock) {
295 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
296 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
297
298 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
299 // Handle X && Y in a condition.
300 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
301 // If we have "1 && X", simplify the code. "0 && X" would have constant
302 // folded if the case was simple enough.
303 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
304 // br(1 && X) -> br(X).
305 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
306 }
307
308 // If we have "X && 1", simplify the code to use an uncond branch.
309 // "X && 0" would have been constant folded to 0.
310 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
311 // br(X && 1) -> br(X).
312 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
313 }
314
315 // Emit the LHS as a conditional. If the LHS conditional is false, we
316 // want to jump to the FalseBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000317 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner31a09842008-11-12 08:04:58 +0000318 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
319 EmitBlock(LHSTrue);
320
321 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
322 return;
323 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
324 // If we have "0 || X", simplify the code. "1 || X" would have constant
325 // folded if the case was simple enough.
326 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
327 // br(0 || X) -> br(X).
328 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
329 }
330
331 // If we have "X || 0", simplify the code to use an uncond branch.
332 // "X || 1" would have been constant folded to 1.
333 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
334 // br(X || 0) -> br(X).
335 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
336 }
337
338 // Emit the LHS as a conditional. If the LHS conditional is true, we
339 // want to jump to the TrueBlock.
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000340 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner31a09842008-11-12 08:04:58 +0000341 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
342 EmitBlock(LHSFalse);
343
344 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
345 return;
346 }
Chris Lattner552f4c42008-11-12 08:13:36 +0000347 }
348
349 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
350 // br(!x, t, f) -> br(x, f, t)
351 if (CondUOp->getOpcode() == UnaryOperator::LNot)
352 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner31a09842008-11-12 08:04:58 +0000353 }
354
Daniel Dunbar09b14892008-11-12 10:30:32 +0000355 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
356 // Handle ?: operator.
357
358 // Just ignore GNU ?: extension.
359 if (CondOp->getLHS()) {
360 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
361 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
362 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
363 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
364 EmitBlock(LHSBlock);
365 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
366 EmitBlock(RHSBlock);
367 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
368 return;
369 }
370 }
371
Chris Lattner31a09842008-11-12 08:04:58 +0000372 // Emit the code with the fully general case.
373 llvm::Value *CondV = EvaluateExprAsBool(Cond);
374 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
375}
376
Devang Patel88a981b2007-11-01 19:11:01 +0000377/// getCGRecordLayout - Return record layout info.
378const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000379 QualType Ty) {
380 const RecordType *RTy = Ty->getAsRecordType();
381 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000382
Chris Lattneraf319132008-02-05 06:55:31 +0000383 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000384}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000385
Daniel Dunbar488e9932008-08-16 00:56:44 +0000386/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000387/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000388void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
389 bool OmitOnError) {
390 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000391}
392
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000393unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
394 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
395 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
396}
397
Anders Carlsson3d8400d2008-08-30 19:51:14 +0000398void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
399{
400 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
401 if (DestPtr->getType() != BP)
402 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
403
404 // Get size and alignment info for this aggregate.
405 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
406
407 // FIXME: Handle variable sized types.
408 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
409
410 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
411 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
412 // TypeInfo.first describes size in bits.
413 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
414 llvm::ConstantInt::get(llvm::Type::Int32Ty,
415 TypeInfo.second/8));
416}
417
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000418void CodeGenFunction::EmitIndirectSwitches() {
419 llvm::BasicBlock *Default;
420
Daniel Dunbar76526a52008-08-04 17:24:44 +0000421 if (IndirectSwitches.empty())
422 return;
423
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000424 if (!LabelIDs.empty()) {
425 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
426 } else {
427 // No possible targets for indirect goto, just emit an infinite
428 // loop.
Daniel Dunbar55e87422008-11-11 02:29:29 +0000429 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000430 llvm::BranchInst::Create(Default, Default);
431 }
432
433 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
434 e = IndirectSwitches.end(); i != e; ++i) {
435 llvm::SwitchInst *I = *i;
436
437 I->setSuccessor(0, Default);
438 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
439 LE = LabelIDs.end(); LI != LE; ++LI) {
440 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
441 LI->second),
442 getBasicBlockForLabel(LI->first));
443 }
444 }
445}
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000446
Anders Carlssondcc90d82008-12-12 07:19:02 +0000447llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
448{
449 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlssondcc90d82008-12-12 07:19:02 +0000450
Anders Carlssonf666b772008-12-20 20:27:15 +0000451 assert(SizeEntry && "Did not emit size for type");
452 return SizeEntry;
453}
Anders Carlssondcc90d82008-12-12 07:19:02 +0000454
Anders Carlsson60d35412008-12-20 20:46:34 +0000455llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf666b772008-12-20 20:27:15 +0000456{
Anders Carlsson60d35412008-12-20 20:46:34 +0000457 assert(Ty->isVariablyModifiedType() &&
458 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf666b772008-12-20 20:27:15 +0000459
Anders Carlsson60d35412008-12-20 20:46:34 +0000460 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
461 llvm::Value *&SizeEntry = VLASizeMap[VAT];
462
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000463 if (!SizeEntry) {
464 // Get the element size;
465 llvm::Value *ElemSize;
Anders Carlsson60d35412008-12-20 20:46:34 +0000466
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000467 QualType ElemTy = VAT->getElementType();
Anders Carlsson96f21472009-02-05 19:43:10 +0000468
469 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
470
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000471 if (ElemTy->isVariableArrayType())
472 ElemSize = EmitVLASize(ElemTy);
473 else {
Anders Carlsson96f21472009-02-05 19:43:10 +0000474 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000475 getContext().getTypeSize(ElemTy) / 8);
476 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000477
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000478 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson96f21472009-02-05 19:43:10 +0000479 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
480
Anders Carlssonfcdbb932008-12-20 21:51:53 +0000481 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlsson60d35412008-12-20 20:46:34 +0000482 }
483
Anders Carlsson60d35412008-12-20 20:46:34 +0000484 return SizeEntry;
485 } else if (const PointerType *PT = Ty->getAsPointerType())
486 EmitVLASize(PT->getPointeeType());
Anders Carlssonf666b772008-12-20 20:27:15 +0000487 else {
Anders Carlsson60d35412008-12-20 20:46:34 +0000488 assert(0 && "unknown VM type!");
Anders Carlssondcc90d82008-12-12 07:19:02 +0000489 }
Anders Carlsson60d35412008-12-20 20:46:34 +0000490
491 return 0;
Anders Carlssondcc90d82008-12-12 07:19:02 +0000492}
Eli Friedman4fd0aa52009-01-20 17:46:04 +0000493
494llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
495 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
496 return EmitScalarExpr(E);
497 }
498 return EmitLValue(E).getAddress();
499}
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000500
Anders Carlsson6fc55912009-02-08 03:22:36 +0000501void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000502{
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000503 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson6ccc4762009-02-07 22:53:43 +0000504}
Anders Carlssonc71c8452009-02-07 23:50:39 +0000505
506void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
507{
508 assert(CleanupEntries.size() >= OldCleanupStackSize &&
509 "Cleanup stack mismatch!");
510
511 while (CleanupEntries.size() > OldCleanupStackSize)
512 EmitCleanupBlock();
513}
514
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000515CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlssonc71c8452009-02-07 23:50:39 +0000516{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000517 CleanupEntry &CE = CleanupEntries.back();
518
519 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
520
521 std::vector<llvm::BasicBlock *> Blocks;
522 std::swap(Blocks, CE.Blocks);
523
524 std::vector<llvm::BranchInst *> BranchFixups;
525 std::swap(BranchFixups, CE.BranchFixups);
526
527 CleanupEntries.pop_back();
528
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000529 // Check if any branch fixups pointed to the scope we just popped. If so,
530 // we can remove them.
531 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
532 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
533 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000534
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000535 if (I == BlockScopes.end())
536 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000537
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000538 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssond66a9f92009-02-08 03:55:35 +0000539
Anders Carlssonad9d00e2009-02-08 22:45:15 +0000540 if (I->second == CleanupEntries.size()) {
541 // We don't need to do this branch fixup.
542 BranchFixups[i] = BranchFixups.back();
543 BranchFixups.pop_back();
544 i--;
545 e--;
546 continue;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000547 }
548 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000549
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000550 llvm::BasicBlock *SwitchBlock = 0;
551 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000552 if (!BranchFixups.empty()) {
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000553 SwitchBlock = createBasicBlock("cleanup.switch");
554 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000555
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000556 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
557
558 Builder.SetInsertPoint(SwitchBlock);
559
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000560 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
561 "cleanup.dst");
562 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
563
564 // Create a switch instruction to determine where to jump next.
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000565 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000566 BranchFixups.size());
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000567
Anders Carlsson46831a92009-02-08 22:13:37 +0000568 // Restore the current basic block (if any)
569 if (CurBB)
570 Builder.SetInsertPoint(CurBB);
571 else
572 Builder.ClearInsertionPoint();
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000573
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000574 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
575 llvm::BranchInst *BI = BranchFixups[i];
576 llvm::BasicBlock *Dest = BI->getSuccessor(0);
577
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000578 // Fixup the branch instruction to point to the cleanup block.
579 BI->setSuccessor(0, CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000580
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000581 if (CleanupEntries.empty()) {
Anders Carlssoncc899202009-02-08 22:46:50 +0000582 llvm::ConstantInt *ID;
583
584 // Check if we already have a destination for this block.
585 if (Dest == SI->getDefaultDest())
586 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
587 else {
588 ID = SI->findCaseDest(Dest);
589 if (!ID) {
590 // No code found, get a new unique one by using the number of
591 // switch successors.
592 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
593 SI->getNumSuccessors());
594 SI->addCase(ID, Dest);
595 }
596 }
597
598 // Store the jump destination before the branch instruction.
599 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000600 } else {
601 // We need to jump through another cleanup block. Create a pad block
602 // with a branch instruction that jumps to the final destination and
603 // add it as a branch fixup to the current cleanup scope.
604
605 // Create the pad block.
606 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlssoncc899202009-02-08 22:46:50 +0000607
608 // Create a unique case ID.
609 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
610 SI->getNumSuccessors());
611
612 // Store the jump destination before the branch instruction.
613 new llvm::StoreInst(ID, DestCodePtr, BI);
614
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000615 // Add it as the destination.
Anders Carlssoncc899202009-02-08 22:46:50 +0000616 SI->addCase(ID, CleanupPad);
Anders Carlsson1093c2c2009-02-08 01:23:05 +0000617
618 // Create the branch to the final destination.
619 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
620 CleanupPad->getInstList().push_back(BI);
621
622 // And add it as a branch fixup.
623 CleanupEntries.back().BranchFixups.push_back(BI);
624 }
625 }
626 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000627
Anders Carlssonbd6fa3d2009-02-08 00:16:35 +0000628 // Remove all blocks from the block scope map.
629 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
630 assert(BlockScopes.count(Blocks[i]) &&
631 "Did not find block in scope map!");
632
633 BlockScopes.erase(Blocks[i]);
634 }
Anders Carlssond66a9f92009-02-08 03:55:35 +0000635
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000636 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000637}
638
639void CodeGenFunction::EmitCleanupBlock()
640{
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000641 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssond66a9f92009-02-08 03:55:35 +0000642
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000643 EmitBlock(Info.CleanupBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000644
Anders Carlssonbb66f9f2009-02-08 07:46:24 +0000645 if (Info.SwitchBlock)
646 EmitBlock(Info.SwitchBlock);
647 if (Info.EndBlock)
648 EmitBlock(Info.EndBlock);
Anders Carlssond66a9f92009-02-08 03:55:35 +0000649}
650
Anders Carlsson87eaf172009-02-08 00:50:42 +0000651void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
652{
653 assert(!CleanupEntries.empty() &&
654 "Trying to add branch fixup without cleanup block!");
655
656 // FIXME: We could be more clever here and check if there's already a
657 // branch fixup for this destination and recycle it.
658 CleanupEntries.back().BranchFixups.push_back(BI);
659}
660
661void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
662{
Anders Carlsson46831a92009-02-08 22:13:37 +0000663 if (!HaveInsertPoint())
664 return;
665
Anders Carlsson87eaf172009-02-08 00:50:42 +0000666 llvm::BranchInst* BI = Builder.CreateBr(Dest);
667
Anders Carlsson46831a92009-02-08 22:13:37 +0000668 Builder.ClearInsertionPoint();
669
Anders Carlsson87eaf172009-02-08 00:50:42 +0000670 // The stack is empty, no need to do any cleanup.
671 if (CleanupEntries.empty())
672 return;
673
674 if (!Dest->getParent()) {
675 // We are trying to branch to a block that hasn't been inserted yet.
676 AddBranchFixup(BI);
677 return;
678 }
679
680 BlockScopeMap::iterator I = BlockScopes.find(Dest);
681 if (I == BlockScopes.end()) {
682 // We are trying to jump to a block that is outside of any cleanup scope.
683 AddBranchFixup(BI);
684 return;
685 }
686
687 assert(I->second < CleanupEntries.size() &&
688 "Trying to branch into cleanup region");
689
690 if (I->second == CleanupEntries.size() - 1) {
691 // We have a branch to a block in the same scope.
692 return;
693 }
694
695 AddBranchFixup(BI);
696}