blob: c05ead5233b516d2544b28b45f46fe3e699c0229 [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"
Anders Carlssonaa3afc72009-04-04 20:47:02 +000021#include "clang/AST/DeclCXX.h"
Devang Patel97299362007-09-28 21:49:18 +000022#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000023#include "llvm/Target/TargetData.h"
Chris Lattner4b009652007-07-25 00:24:17 +000024using namespace clang;
25using namespace CodeGen;
26
27CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Mike Stumpecd79422009-03-06 01:33:24 +000028 : BlockFunction(cgm, *this, Builder), CGM(cgm),
29 Target(CGM.getContext().Target),
Anders Carlssonaa3afc72009-04-04 20:47:02 +000030 DebugInfo(0), SwitchInsn(0), CaseRangeBlock(0), InvokeDest(0),
31 CXXThisDecl(0) {
Mike Stumpfca5da02009-02-21 20:00:35 +000032 LLVMIntTy = ConvertType(getContext().IntTy);
33 LLVMPointerWidth = Target.getPointerWidth(0);
Chris Lattner8c7c6a12008-06-17 18:05:57 +000034}
Chris Lattner4b009652007-07-25 00:24:17 +000035
36ASTContext &CodeGenFunction::getContext() const {
37 return CGM.getContext();
38}
39
40
41llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
42 llvm::BasicBlock *&BB = LabelMap[S];
43 if (BB) return BB;
44
45 // Create, but don't insert, the new block.
Daniel Dunbar72f96552008-11-11 02:29:29 +000046 return BB = createBasicBlock(S->getName());
Chris Lattner4b009652007-07-25 00:24:17 +000047}
48
Daniel Dunbardea59212009-02-25 19:24:29 +000049llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD) {
50 llvm::Value *Res = LocalDeclMap[VD];
51 assert(Res && "Invalid argument to GetAddrOfLocalVar(), no decl!");
52 return Res;
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000053}
Chris Lattner4b009652007-07-25 00:24:17 +000054
Daniel Dunbardea59212009-02-25 19:24:29 +000055llvm::Constant *
56CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
57 return cast<llvm::Constant>(GetAddrOfLocalVar(BVD));
Anders Carlsson75d86732008-09-11 09:15:33 +000058}
59
Daniel Dunbar706059f2009-02-03 23:03:55 +000060const llvm::Type *CodeGenFunction::ConvertTypeForMem(QualType T) {
61 return CGM.getTypes().ConvertTypeForMem(T);
62}
63
Chris Lattner4b009652007-07-25 00:24:17 +000064const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
65 return CGM.getTypes().ConvertType(T);
66}
67
68bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Daniel Dunbar96891242009-01-09 02:44:18 +000069 // FIXME: Use positive checks instead of negative ones to be more
70 // robust in the face of extension.
Daniel Dunbarfc096bf2009-02-26 20:52:22 +000071 return !T->hasPointerRepresentation() &&!T->isRealType() &&
72 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType() &&
Daniel Dunbar96891242009-01-09 02:44:18 +000073 !T->isBlockPointerType();
Chris Lattner4b009652007-07-25 00:24:17 +000074}
75
Daniel Dunbar924f4ea2009-01-26 23:27:52 +000076void CodeGenFunction::EmitReturnBlock() {
77 // For cleanliness, we try to avoid emitting the return block for
78 // simple cases.
79 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
80
81 if (CurBB) {
82 assert(!CurBB->getTerminator() && "Unexpected terminated block.");
83
84 // We have a valid insert point, reuse it if there are no explicit
85 // jumps to the return block.
86 if (ReturnBlock->use_empty())
87 delete ReturnBlock;
88 else
89 EmitBlock(ReturnBlock);
90 return;
91 }
92
93 // Otherwise, if the return block is the target of a single direct
94 // branch then we can just put the code in that block instead. This
95 // cleans up functions which started with a unified return block.
96 if (ReturnBlock->hasOneUse()) {
97 llvm::BranchInst *BI =
98 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
99 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
100 // Reset insertion point and delete the branch.
101 Builder.SetInsertPoint(BI->getParent());
102 BI->eraseFromParent();
103 delete ReturnBlock;
104 return;
105 }
106 }
107
108 // FIXME: We are at an unreachable point, there is no reason to emit
109 // the block unless it has uses. However, we still need a place to
110 // put the debug region.end for now.
111
112 EmitBlock(ReturnBlock);
113}
114
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000115void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar879788d2008-08-04 16:51:22 +0000116 // Finish emission of indirect switches.
117 EmitIndirectSwitches();
118
Chris Lattner4b009652007-07-25 00:24:17 +0000119 assert(BreakContinueStack.empty() &&
120 "mismatched push/pop in break/continue stack!");
Anders Carlssone7de3522009-02-08 00:16:35 +0000121 assert(BlockScopes.empty() &&
122 "did not remove all blocks from block scope map!");
123 assert(CleanupEntries.empty() &&
124 "mismatched push/pop in cleanup stack!");
125
Daniel Dunbar924f4ea2009-01-26 23:27:52 +0000126 // Emit function epilog (to return).
127 EmitReturnBlock();
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000128
129 // Emit debug descriptor for function end.
Anders Carlsson73007792009-02-13 08:11:52 +0000130 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000131 DI->setLocation(EndLoc);
132 DI->EmitRegionEnd(CurFn, Builder);
133 }
134
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000135 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000136
Chris Lattnerca929812007-12-02 06:32:24 +0000137 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattnerfea1a662009-03-31 22:17:44 +0000138 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerca929812007-12-02 06:32:24 +0000139 AllocaInsertPt = 0;
Chris Lattnerfea1a662009-03-31 22:17:44 +0000140 Ptr->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000141}
142
Daniel Dunbar96816832008-09-09 23:14:03 +0000143void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
144 llvm::Function *Fn,
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000145 const FunctionArgList &Args,
146 SourceLocation StartLoc) {
Anders Carlsson60c4c402009-02-09 20:20:56 +0000147 DidCallStackSave = false;
Chris Lattnerf6279ae2009-04-23 05:30:27 +0000148 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar96816832008-09-09 23:14:03 +0000149 FnRetTy = RetTy;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000150 CurFn = Fn;
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000151 assert(CurFn->isDeclaration() && "Function already has body?");
152
Daniel Dunbar72f96552008-11-11 02:29:29 +0000153 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000154
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000155 // Create a marker to make it easy to insert allocas into the entryblock
156 // later. Don't create this with the builder, because we don't want it
157 // folded.
158 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
Chris Lattner7fbb70d2009-03-22 00:24:14 +0000159 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000160 EntryBB);
Chris Lattner7fbb70d2009-03-22 00:24:14 +0000161 if (Builder.isNamePreserving())
162 AllocaInsertPt->setName("allocapt");
163
Daniel Dunbar72f96552008-11-11 02:29:29 +0000164 ReturnBlock = createBasicBlock("return");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000165 ReturnValue = 0;
Daniel Dunbar96816832008-09-09 23:14:03 +0000166 if (!RetTy->isVoidType())
167 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000168
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000169 Builder.SetInsertPoint(EntryBB);
170
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000171 // Emit subprogram debug descriptor.
Daniel Dunbar96816832008-09-09 23:14:03 +0000172 // FIXME: The cast here is a huge hack.
Anders Carlsson73007792009-02-13 08:11:52 +0000173 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000174 DI->setLocation(StartLoc);
175 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000176 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000177 } else {
178 // Just use LLVM function name.
179 DI->EmitFunctionStart(Fn->getName().c_str(),
180 RetTy, CurFn, Builder);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000181 }
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000182 }
183
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000184 // FIXME: Leaked.
Daniel Dunbar34bda882009-02-02 23:23:47 +0000185 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000186 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson21cecd42008-12-20 21:28:43 +0000187
188 // If any of the arguments have a variably modified type, make sure to
189 // emit the type size.
190 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
191 i != e; ++i) {
192 QualType Ty = i->second;
193
194 if (Ty->isVariablyModifiedType())
195 EmitVLASize(Ty);
196 }
Daniel Dunbar96816832008-09-09 23:14:03 +0000197}
Eli Friedman769e7302008-08-25 21:31:01 +0000198
Daniel Dunbar96816832008-09-09 23:14:03 +0000199void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
200 llvm::Function *Fn) {
Anders Carlsson73007792009-02-13 08:11:52 +0000201 // Check if we should generate debug info for this function.
Daniel Dunbar78582862009-04-13 21:08:27 +0000202 if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
Anders Carlsson73007792009-02-13 08:11:52 +0000203 DebugInfo = CGM.getDebugInfo();
204
Daniel Dunbar96816832008-09-09 23:14:03 +0000205 FunctionArgList Args;
Anders Carlssonaa3afc72009-04-04 20:47:02 +0000206
207 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
208 if (MD->isInstance()) {
209 // Create the implicit 'this' decl.
210 // FIXME: I'm not entirely sure I like using a fake decl just for code
211 // generation. Maybe we can come up with a better way?
212 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
213 &getContext().Idents.get("this"),
214 MD->getThisType(getContext()));
215 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
216 }
217 }
218
Eli Friedman769e7302008-08-25 21:31:01 +0000219 if (FD->getNumParams()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000220 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedman769e7302008-08-25 21:31:01 +0000221 assert(FProto && "Function def must have prototype!");
Daniel Dunbar96816832008-09-09 23:14:03 +0000222
223 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
224 Args.push_back(std::make_pair(FD->getParamDecl(i),
225 FProto->getArgType(i)));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000226 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000227
Douglas Gregore3241e92009-04-18 00:02:19 +0000228 const CompoundStmt *S = FD->getBody(getContext());
Daniel Dunbar96816832008-09-09 23:14:03 +0000229
Anders Carlsson92226632009-04-15 04:10:19 +0000230 StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
231 EmitStmt(S);
232 FinishFunction(S->getRBracLoc());
Anders Carlssonaa3afc72009-04-04 20:47:02 +0000233
234 // Destroy the 'this' declaration.
235 if (CXXThisDecl)
236 CXXThisDecl->Destroy(getContext());
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000237}
238
Chris Lattner3f73d0d2008-11-11 07:41:27 +0000239/// ContainsLabel - Return true if the statement contains a label in it. If
240/// this statement is not executed normally, it not containing a label means
241/// that we can just remove the code.
242bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
243 // Null statement, not a label!
244 if (S == 0) return false;
245
246 // If this is a label, we have to emit the code, consider something like:
247 // if (0) { ... foo: bar(); } goto foo;
248 if (isa<LabelStmt>(S))
249 return true;
250
251 // If this is a case/default statement, and we haven't seen a switch, we have
252 // to emit the code.
253 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
254 return true;
255
256 // If this is a switch statement, we want to ignore cases below it.
257 if (isa<SwitchStmt>(S))
258 IgnoreCaseStmts = true;
259
260 // Scan subexpressions for verboten labels.
261 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
262 I != E; ++I)
263 if (ContainsLabel(*I, IgnoreCaseStmts))
264 return true;
265
266 return false;
267}
268
Chris Lattner3d6606b2008-11-12 08:04:58 +0000269
270/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
271/// a constant, or if it does but contains a label, return 0. If it constant
272/// folds to 'true' and does not contain a label, return 1, if it constant folds
273/// to 'false' and does not contain a label, return -1.
274int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar14937022008-11-12 22:37:10 +0000275 // FIXME: Rename and handle conversion of other evaluatable things
276 // to bool.
Anders Carlsson90d85f32008-12-01 02:46:24 +0000277 Expr::EvalResult Result;
278 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
279 Result.HasSideEffects)
Anders Carlssonea3c6ab2008-11-22 22:32:07 +0000280 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner3d6606b2008-11-12 08:04:58 +0000281
282 if (CodeGenFunction::ContainsLabel(Cond))
283 return 0; // Contains a label.
284
Anders Carlsson90d85f32008-12-01 02:46:24 +0000285 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner3d6606b2008-11-12 08:04:58 +0000286}
287
288
289/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
290/// statement) to the specified blocks. Based on the condition, this might try
291/// to simplify the codegen of the conditional based on the branch.
292///
293void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
294 llvm::BasicBlock *TrueBlock,
295 llvm::BasicBlock *FalseBlock) {
296 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
297 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
298
299 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
300 // Handle X && Y in a condition.
301 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
302 // If we have "1 && X", simplify the code. "0 && X" would have constant
303 // folded if the case was simple enough.
304 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
305 // br(1 && X) -> br(X).
306 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
307 }
308
309 // If we have "X && 1", simplify the code to use an uncond branch.
310 // "X && 0" would have been constant folded to 0.
311 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
312 // br(X && 1) -> br(X).
313 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
314 }
315
316 // Emit the LHS as a conditional. If the LHS conditional is false, we
317 // want to jump to the FalseBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000318 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000319 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
320 EmitBlock(LHSTrue);
321
322 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
323 return;
324 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
325 // If we have "0 || X", simplify the code. "1 || X" would have constant
326 // folded if the case was simple enough.
327 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
328 // br(0 || X) -> br(X).
329 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
330 }
331
332 // If we have "X || 0", simplify the code to use an uncond branch.
333 // "X || 1" would have been constant folded to 1.
334 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
335 // br(X || 0) -> br(X).
336 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
337 }
338
339 // Emit the LHS as a conditional. If the LHS conditional is true, we
340 // want to jump to the TrueBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000341 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000342 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
343 EmitBlock(LHSFalse);
344
345 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
346 return;
347 }
Chris Lattnercfbfe912008-11-12 08:13:36 +0000348 }
349
350 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
351 // br(!x, t, f) -> br(x, f, t)
352 if (CondUOp->getOpcode() == UnaryOperator::LNot)
353 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000354 }
355
Daniel Dunbarab81c632008-11-12 10:30:32 +0000356 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
357 // Handle ?: operator.
358
359 // Just ignore GNU ?: extension.
360 if (CondOp->getLHS()) {
361 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
362 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
363 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
364 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
365 EmitBlock(LHSBlock);
366 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
367 EmitBlock(RHSBlock);
368 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
369 return;
370 }
371 }
372
Chris Lattner3d6606b2008-11-12 08:04:58 +0000373 // Emit the code with the fully general case.
374 llvm::Value *CondV = EvaluateExprAsBool(Cond);
375 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
376}
377
Devang Patel7a78e432007-11-01 19:11:01 +0000378/// getCGRecordLayout - Return record layout info.
379const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000380 QualType Ty) {
381 const RecordType *RTy = Ty->getAsRecordType();
382 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000383
Chris Lattner7b2543e2008-02-05 06:55:31 +0000384 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000385}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000386
Daniel Dunbar9503b782008-08-16 00:56:44 +0000387/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner9d4e6202007-12-02 01:43:38 +0000388/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000389void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
390 bool OmitOnError) {
391 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000392}
393
Daniel Dunbar879788d2008-08-04 16:51:22 +0000394unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
395 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
396 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
397}
398
Chris Lattner96086d82009-04-21 17:59:23 +0000399void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000400 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
Chris Lattner96086d82009-04-21 17:59:23 +0000407 // Don't bother emitting a zero-byte memset.
408 if (TypeInfo.first == 0)
409 return;
410
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000411 // FIXME: Handle variable sized types.
412 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
413
414 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
415 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
416 // TypeInfo.first describes size in bits.
417 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
418 llvm::ConstantInt::get(llvm::Type::Int32Ty,
419 TypeInfo.second/8));
420}
421
Daniel Dunbar879788d2008-08-04 16:51:22 +0000422void CodeGenFunction::EmitIndirectSwitches() {
423 llvm::BasicBlock *Default;
424
Daniel Dunbar8ccfa802008-08-04 17:24:44 +0000425 if (IndirectSwitches.empty())
426 return;
427
Daniel Dunbar879788d2008-08-04 16:51:22 +0000428 if (!LabelIDs.empty()) {
429 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
430 } else {
431 // No possible targets for indirect goto, just emit an infinite
432 // loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000433 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000434 llvm::BranchInst::Create(Default, Default);
435 }
436
437 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
438 e = IndirectSwitches.end(); i != e; ++i) {
439 llvm::SwitchInst *I = *i;
440
441 I->setSuccessor(0, Default);
442 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
443 LE = LabelIDs.end(); LI != LE; ++LI) {
444 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
445 LI->second),
446 getBasicBlockForLabel(LI->first));
447 }
448 }
449}
Anders Carlsson285611e2008-11-04 05:30:00 +0000450
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000451llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT)
452{
453 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000454
Anders Carlssonf860e022008-12-20 20:27:15 +0000455 assert(SizeEntry && "Did not emit size for type");
456 return SizeEntry;
457}
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000458
Anders Carlssond9767612008-12-20 20:46:34 +0000459llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty)
Anders Carlssonf860e022008-12-20 20:27:15 +0000460{
Anders Carlssond9767612008-12-20 20:46:34 +0000461 assert(Ty->isVariablyModifiedType() &&
462 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf860e022008-12-20 20:27:15 +0000463
Anders Carlssond9767612008-12-20 20:46:34 +0000464 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
465 llvm::Value *&SizeEntry = VLASizeMap[VAT];
466
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000467 if (!SizeEntry) {
468 // Get the element size;
469 llvm::Value *ElemSize;
Anders Carlssond9767612008-12-20 20:46:34 +0000470
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000471 QualType ElemTy = VAT->getElementType();
Anders Carlsson8f30de92009-02-05 19:43:10 +0000472
473 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
474
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000475 if (ElemTy->isVariableArrayType())
476 ElemSize = EmitVLASize(ElemTy);
477 else {
Anders Carlsson8f30de92009-02-05 19:43:10 +0000478 ElemSize = llvm::ConstantInt::get(SizeTy,
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000479 getContext().getTypeSize(ElemTy) / 8);
480 }
Anders Carlssond9767612008-12-20 20:46:34 +0000481
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000482 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson8f30de92009-02-05 19:43:10 +0000483 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
484
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000485 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlssond9767612008-12-20 20:46:34 +0000486 }
487
Anders Carlssond9767612008-12-20 20:46:34 +0000488 return SizeEntry;
489 } else if (const PointerType *PT = Ty->getAsPointerType())
490 EmitVLASize(PT->getPointeeType());
Anders Carlssonf860e022008-12-20 20:27:15 +0000491 else {
Anders Carlssond9767612008-12-20 20:46:34 +0000492 assert(0 && "unknown VM type!");
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000493 }
Anders Carlssond9767612008-12-20 20:46:34 +0000494
495 return 0;
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000496}
Eli Friedman8f5e8782009-01-20 17:46:04 +0000497
498llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
499 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
500 return EmitScalarExpr(E);
501 }
502 return EmitLValue(E).getAddress();
503}
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000504
Anders Carlsson459ee362009-02-08 03:22:36 +0000505void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000506{
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000507 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000508}
Anders Carlsson883fa552009-02-07 23:50:39 +0000509
510void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
511{
512 assert(CleanupEntries.size() >= OldCleanupStackSize &&
513 "Cleanup stack mismatch!");
514
515 while (CleanupEntries.size() > OldCleanupStackSize)
516 EmitCleanupBlock();
517}
518
Anders Carlssondf274192009-02-08 07:46:24 +0000519CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlsson883fa552009-02-07 23:50:39 +0000520{
Anders Carlssondf274192009-02-08 07:46:24 +0000521 CleanupEntry &CE = CleanupEntries.back();
522
523 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
524
525 std::vector<llvm::BasicBlock *> Blocks;
526 std::swap(Blocks, CE.Blocks);
527
528 std::vector<llvm::BranchInst *> BranchFixups;
529 std::swap(BranchFixups, CE.BranchFixups);
530
531 CleanupEntries.pop_back();
532
Anders Carlsson98720f02009-02-08 22:45:15 +0000533 // Check if any branch fixups pointed to the scope we just popped. If so,
534 // we can remove them.
535 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
536 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
537 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000538
Anders Carlsson98720f02009-02-08 22:45:15 +0000539 if (I == BlockScopes.end())
540 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000541
Anders Carlsson98720f02009-02-08 22:45:15 +0000542 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000543
Anders Carlsson98720f02009-02-08 22:45:15 +0000544 if (I->second == CleanupEntries.size()) {
545 // We don't need to do this branch fixup.
546 BranchFixups[i] = BranchFixups.back();
547 BranchFixups.pop_back();
548 i--;
549 e--;
550 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000551 }
552 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000553
Anders Carlssondf274192009-02-08 07:46:24 +0000554 llvm::BasicBlock *SwitchBlock = 0;
555 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson9b399792009-02-08 01:23:05 +0000556 if (!BranchFixups.empty()) {
Anders Carlssondf274192009-02-08 07:46:24 +0000557 SwitchBlock = createBasicBlock("cleanup.switch");
558 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson9b399792009-02-08 01:23:05 +0000559
Anders Carlssondf274192009-02-08 07:46:24 +0000560 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000561
Anders Carlssondf274192009-02-08 07:46:24 +0000562 Builder.SetInsertPoint(SwitchBlock);
563
Anders Carlsson9b399792009-02-08 01:23:05 +0000564 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
565 "cleanup.dst");
566 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
567
568 // Create a switch instruction to determine where to jump next.
Anders Carlssondf274192009-02-08 07:46:24 +0000569 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson9b399792009-02-08 01:23:05 +0000570 BranchFixups.size());
Anders Carlssondf274192009-02-08 07:46:24 +0000571
Anders Carlsson32fffb72009-02-08 22:13:37 +0000572 // Restore the current basic block (if any)
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000573 if (CurBB) {
Anders Carlsson32fffb72009-02-08 22:13:37 +0000574 Builder.SetInsertPoint(CurBB);
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000575
576 // If we had a current basic block, we also need to emit an instruction
577 // to initialize the cleanup destination.
578 Builder.CreateStore(llvm::Constant::getNullValue(llvm::Type::Int32Ty),
579 DestCodePtr);
580 } else
Anders Carlsson32fffb72009-02-08 22:13:37 +0000581 Builder.ClearInsertionPoint();
Anders Carlssondf274192009-02-08 07:46:24 +0000582
Anders Carlsson9b399792009-02-08 01:23:05 +0000583 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
584 llvm::BranchInst *BI = BranchFixups[i];
585 llvm::BasicBlock *Dest = BI->getSuccessor(0);
586
Anders Carlsson9b399792009-02-08 01:23:05 +0000587 // Fixup the branch instruction to point to the cleanup block.
588 BI->setSuccessor(0, CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000589
Anders Carlsson9b399792009-02-08 01:23:05 +0000590 if (CleanupEntries.empty()) {
Anders Carlsson8be63402009-02-08 22:46:50 +0000591 llvm::ConstantInt *ID;
592
593 // Check if we already have a destination for this block.
594 if (Dest == SI->getDefaultDest())
595 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
596 else {
597 ID = SI->findCaseDest(Dest);
598 if (!ID) {
599 // No code found, get a new unique one by using the number of
600 // switch successors.
601 ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
602 SI->getNumSuccessors());
603 SI->addCase(ID, Dest);
604 }
605 }
606
607 // Store the jump destination before the branch instruction.
608 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson9b399792009-02-08 01:23:05 +0000609 } else {
610 // We need to jump through another cleanup block. Create a pad block
611 // with a branch instruction that jumps to the final destination and
612 // add it as a branch fixup to the current cleanup scope.
613
614 // Create the pad block.
615 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson8be63402009-02-08 22:46:50 +0000616
617 // Create a unique case ID.
618 llvm::ConstantInt *ID = llvm::ConstantInt::get(llvm::Type::Int32Ty,
619 SI->getNumSuccessors());
620
621 // Store the jump destination before the branch instruction.
622 new llvm::StoreInst(ID, DestCodePtr, BI);
623
Anders Carlsson9b399792009-02-08 01:23:05 +0000624 // Add it as the destination.
Anders Carlsson8be63402009-02-08 22:46:50 +0000625 SI->addCase(ID, CleanupPad);
Anders Carlsson9b399792009-02-08 01:23:05 +0000626
627 // Create the branch to the final destination.
628 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
629 CleanupPad->getInstList().push_back(BI);
630
631 // And add it as a branch fixup.
632 CleanupEntries.back().BranchFixups.push_back(BI);
633 }
634 }
635 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000636
Anders Carlssone7de3522009-02-08 00:16:35 +0000637 // Remove all blocks from the block scope map.
638 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
639 assert(BlockScopes.count(Blocks[i]) &&
640 "Did not find block in scope map!");
641
642 BlockScopes.erase(Blocks[i]);
643 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000644
Anders Carlssondf274192009-02-08 07:46:24 +0000645 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000646}
647
648void CodeGenFunction::EmitCleanupBlock()
649{
Anders Carlssondf274192009-02-08 07:46:24 +0000650 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000651
Anders Carlssondf274192009-02-08 07:46:24 +0000652 EmitBlock(Info.CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000653
Anders Carlssondf274192009-02-08 07:46:24 +0000654 if (Info.SwitchBlock)
655 EmitBlock(Info.SwitchBlock);
656 if (Info.EndBlock)
657 EmitBlock(Info.EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000658}
659
Anders Carlssoned536bc2009-02-08 00:50:42 +0000660void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
661{
662 assert(!CleanupEntries.empty() &&
663 "Trying to add branch fixup without cleanup block!");
664
665 // FIXME: We could be more clever here and check if there's already a
666 // branch fixup for this destination and recycle it.
667 CleanupEntries.back().BranchFixups.push_back(BI);
668}
669
670void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
671{
Anders Carlsson32fffb72009-02-08 22:13:37 +0000672 if (!HaveInsertPoint())
673 return;
674
Anders Carlssoned536bc2009-02-08 00:50:42 +0000675 llvm::BranchInst* BI = Builder.CreateBr(Dest);
676
Anders Carlsson32fffb72009-02-08 22:13:37 +0000677 Builder.ClearInsertionPoint();
678
Anders Carlssoned536bc2009-02-08 00:50:42 +0000679 // The stack is empty, no need to do any cleanup.
680 if (CleanupEntries.empty())
681 return;
682
683 if (!Dest->getParent()) {
684 // We are trying to branch to a block that hasn't been inserted yet.
685 AddBranchFixup(BI);
686 return;
687 }
688
689 BlockScopeMap::iterator I = BlockScopes.find(Dest);
690 if (I == BlockScopes.end()) {
691 // We are trying to jump to a block that is outside of any cleanup scope.
692 AddBranchFixup(BI);
693 return;
694 }
695
696 assert(I->second < CleanupEntries.size() &&
697 "Trying to branch into cleanup region");
698
699 if (I->second == CleanupEntries.size() - 1) {
700 // We have a branch to a block in the same scope.
701 return;
702 }
703
704 AddBranchFixup(BI);
705}