blob: 4bfebe5c31d1d5589c1046f824bb8c0c5c65e1d6 [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"
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),
Owen Anderson215780a2009-07-08 20:52:20 +000029 Builder(cgm.getModule().getContext()),
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) {
Mike Stumpba2cb0e2009-05-16 07:57:57 +000069 // FIXME: Use positive checks instead of negative ones to be more robust in
70 // 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
Daniel Dunbarac8dae22009-07-19 08:24:34 +000084 // We have a valid insert point, reuse it if it is empty or there are no
85 // explicit jumps to the return block.
86 if (CurBB->empty() || ReturnBlock->use_empty()) {
87 ReturnBlock->replaceAllUsesWith(CurBB);
Daniel Dunbar924f4ea2009-01-26 23:27:52 +000088 delete ReturnBlock;
Daniel Dunbarac8dae22009-07-19 08:24:34 +000089 } else
Daniel Dunbar924f4ea2009-01-26 23:27:52 +000090 EmitBlock(ReturnBlock);
91 return;
92 }
93
94 // Otherwise, if the return block is the target of a single direct
95 // branch then we can just put the code in that block instead. This
96 // cleans up functions which started with a unified return block.
97 if (ReturnBlock->hasOneUse()) {
98 llvm::BranchInst *BI =
99 dyn_cast<llvm::BranchInst>(*ReturnBlock->use_begin());
100 if (BI && BI->isUnconditional() && BI->getSuccessor(0) == ReturnBlock) {
101 // Reset insertion point and delete the branch.
102 Builder.SetInsertPoint(BI->getParent());
103 BI->eraseFromParent();
104 delete ReturnBlock;
105 return;
106 }
107 }
108
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000109 // FIXME: We are at an unreachable point, there is no reason to emit the block
110 // unless it has uses. However, we still need a place to put the debug
111 // region.end for now.
Daniel Dunbar924f4ea2009-01-26 23:27:52 +0000112
113 EmitBlock(ReturnBlock);
114}
115
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000116void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar879788d2008-08-04 16:51:22 +0000117 // Finish emission of indirect switches.
118 EmitIndirectSwitches();
119
Chris Lattner4b009652007-07-25 00:24:17 +0000120 assert(BreakContinueStack.empty() &&
121 "mismatched push/pop in break/continue stack!");
Anders Carlssone7de3522009-02-08 00:16:35 +0000122 assert(BlockScopes.empty() &&
123 "did not remove all blocks from block scope map!");
124 assert(CleanupEntries.empty() &&
125 "mismatched push/pop in cleanup stack!");
126
Daniel Dunbar924f4ea2009-01-26 23:27:52 +0000127 // Emit function epilog (to return).
128 EmitReturnBlock();
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000129
130 // Emit debug descriptor for function end.
Anders Carlsson73007792009-02-13 08:11:52 +0000131 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar03f7ae12008-11-11 20:59:54 +0000132 DI->setLocation(EndLoc);
133 DI->EmitRegionEnd(CurFn, Builder);
134 }
135
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000136 EmitFunctionEpilog(*CurFnInfo, ReturnValue);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000137
Chris Lattnerca929812007-12-02 06:32:24 +0000138 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
Chris Lattnerfea1a662009-03-31 22:17:44 +0000139 llvm::Instruction *Ptr = AllocaInsertPt;
Chris Lattnerca929812007-12-02 06:32:24 +0000140 AllocaInsertPt = 0;
Chris Lattnerfea1a662009-03-31 22:17:44 +0000141 Ptr->eraseFromParent();
Chris Lattner4b009652007-07-25 00:24:17 +0000142}
143
Fariborz Jahanian77cf9fa2009-07-20 22:35:22 +0000144/// EmitCtorPrologue - This routine generates necessary code to initialize
145/// base classes and non-static data members belonging to this constructor.
146void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD) {
147 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
148 E = CD->init_end();
149 B != E; ++B) {
150 CXXBaseOrMemberInitializer *Member = (*B);
151 if (Member->isBaseInitializer()) {
152 // FIXME. Added base initialilzers here.
153 ;
154 }
155 else {
156 // non-static data member initilaizers.
157 FieldDecl *Field = Member->getMember();
158 QualType FieldType = getContext().getCanonicalType((Field)->getType());
159 assert(!getContext().getAsArrayType(FieldType)
160 && "Field arrays initialization unsupported");
161 assert(!FieldType->getAsRecordType()
162 && "Field class initialization unsupported");
163 llvm::Value *LoadOfThis = LoadCXXThis();
164 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0);
165
166 assert(Member->getNumArgs() == 1 && "Initializer count must be 1 only");
167 Expr *RhsExpr = *Member->begin();
168 llvm::Value *RHS = EmitScalarExpr(RhsExpr, true);
169 if (LHS.isBitfield())
170 EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, FieldType, 0);
171 else
172 EmitStoreThroughLValue(RValue::get(RHS), LHS, FieldType);
173 }
174 }
175}
176
Daniel Dunbar96816832008-09-09 23:14:03 +0000177void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
178 llvm::Function *Fn,
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000179 const FunctionArgList &Args,
180 SourceLocation StartLoc) {
Anders Carlsson60c4c402009-02-09 20:20:56 +0000181 DidCallStackSave = false;
Chris Lattnerf6279ae2009-04-23 05:30:27 +0000182 CurCodeDecl = CurFuncDecl = D;
Daniel Dunbar96816832008-09-09 23:14:03 +0000183 FnRetTy = RetTy;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000184 CurFn = Fn;
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000185 assert(CurFn->isDeclaration() && "Function already has body?");
186
Daniel Dunbar72f96552008-11-11 02:29:29 +0000187 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000188
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000189 // Create a marker to make it easy to insert allocas into the entryblock
190 // later. Don't create this with the builder, because we don't want it
191 // folded.
Owen Anderson73e7f802009-07-14 23:10:40 +0000192 llvm::Value *Undef = VMContext.getUndef(llvm::Type::Int32Ty);
Chris Lattner7fbb70d2009-03-22 00:24:14 +0000193 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "",
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000194 EntryBB);
Chris Lattner7fbb70d2009-03-22 00:24:14 +0000195 if (Builder.isNamePreserving())
196 AllocaInsertPt->setName("allocapt");
197
Daniel Dunbar72f96552008-11-11 02:29:29 +0000198 ReturnBlock = createBasicBlock("return");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000199 ReturnValue = 0;
Daniel Dunbar96816832008-09-09 23:14:03 +0000200 if (!RetTy->isVoidType())
201 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000202
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000203 Builder.SetInsertPoint(EntryBB);
204
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000205 // Emit subprogram debug descriptor.
Daniel Dunbar96816832008-09-09 23:14:03 +0000206 // FIXME: The cast here is a huge hack.
Anders Carlsson73007792009-02-13 08:11:52 +0000207 if (CGDebugInfo *DI = getDebugInfo()) {
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000208 DI->setLocation(StartLoc);
209 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3c3c4542009-02-18 23:53:56 +0000210 DI->EmitFunctionStart(CGM.getMangledName(FD), RetTy, CurFn, Builder);
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000211 } else {
212 // Just use LLVM function name.
213 DI->EmitFunctionStart(Fn->getName().c_str(),
214 RetTy, CurFn, Builder);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000215 }
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000216 }
217
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000218 // FIXME: Leaked.
Daniel Dunbar34bda882009-02-02 23:23:47 +0000219 CurFnInfo = &CGM.getTypes().getFunctionInfo(FnRetTy, Args);
Daniel Dunbar6ee022b2009-02-02 22:03:45 +0000220 EmitFunctionProlog(*CurFnInfo, CurFn, Args);
Anders Carlsson21cecd42008-12-20 21:28:43 +0000221
222 // If any of the arguments have a variably modified type, make sure to
223 // emit the type size.
224 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
225 i != e; ++i) {
226 QualType Ty = i->second;
227
228 if (Ty->isVariablyModifiedType())
229 EmitVLASize(Ty);
230 }
Daniel Dunbar96816832008-09-09 23:14:03 +0000231}
Eli Friedman769e7302008-08-25 21:31:01 +0000232
Daniel Dunbar96816832008-09-09 23:14:03 +0000233void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
234 llvm::Function *Fn) {
Anders Carlsson73007792009-02-13 08:11:52 +0000235 // Check if we should generate debug info for this function.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +0000236 if (CGM.getDebugInfo() && !FD->hasAttr<NodebugAttr>())
Anders Carlsson73007792009-02-13 08:11:52 +0000237 DebugInfo = CGM.getDebugInfo();
238
Daniel Dunbar96816832008-09-09 23:14:03 +0000239 FunctionArgList Args;
Anders Carlssonaa3afc72009-04-04 20:47:02 +0000240
241 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
242 if (MD->isInstance()) {
243 // Create the implicit 'this' decl.
244 // FIXME: I'm not entirely sure I like using a fake decl just for code
245 // generation. Maybe we can come up with a better way?
246 CXXThisDecl = ImplicitParamDecl::Create(getContext(), 0, SourceLocation(),
247 &getContext().Idents.get("this"),
248 MD->getThisType(getContext()));
249 Args.push_back(std::make_pair(CXXThisDecl, CXXThisDecl->getType()));
250 }
251 }
252
Eli Friedman769e7302008-08-25 21:31:01 +0000253 if (FD->getNumParams()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000254 const FunctionProtoType* FProto = FD->getType()->getAsFunctionProtoType();
Eli Friedman769e7302008-08-25 21:31:01 +0000255 assert(FProto && "Function def must have prototype!");
Daniel Dunbar96816832008-09-09 23:14:03 +0000256
257 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
258 Args.push_back(std::make_pair(FD->getParamDecl(i),
259 FProto->getArgType(i)));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000260 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000261
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000262 // FIXME: Support CXXTryStmt here, too.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +0000263 if (const CompoundStmt *S = FD->getCompoundBody()) {
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000264 StartFunction(FD, FD->getResultType(), Fn, Args, S->getLBracLoc());
Fariborz Jahanian77cf9fa2009-07-20 22:35:22 +0000265 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
266 EmitCtorPrologue(CD);
Sebastian Redlbc9ef252009-04-26 20:35:05 +0000267 EmitStmt(S);
268 FinishFunction(S->getRBracLoc());
269 }
Daniel Dunbar96816832008-09-09 23:14:03 +0000270
Anders Carlssonaa3afc72009-04-04 20:47:02 +0000271 // Destroy the 'this' declaration.
272 if (CXXThisDecl)
273 CXXThisDecl->Destroy(getContext());
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000274}
275
Chris Lattner3f73d0d2008-11-11 07:41:27 +0000276/// ContainsLabel - Return true if the statement contains a label in it. If
277/// this statement is not executed normally, it not containing a label means
278/// that we can just remove the code.
279bool CodeGenFunction::ContainsLabel(const Stmt *S, bool IgnoreCaseStmts) {
280 // Null statement, not a label!
281 if (S == 0) return false;
282
283 // If this is a label, we have to emit the code, consider something like:
284 // if (0) { ... foo: bar(); } goto foo;
285 if (isa<LabelStmt>(S))
286 return true;
287
288 // If this is a case/default statement, and we haven't seen a switch, we have
289 // to emit the code.
290 if (isa<SwitchCase>(S) && !IgnoreCaseStmts)
291 return true;
292
293 // If this is a switch statement, we want to ignore cases below it.
294 if (isa<SwitchStmt>(S))
295 IgnoreCaseStmts = true;
296
297 // Scan subexpressions for verboten labels.
298 for (Stmt::const_child_iterator I = S->child_begin(), E = S->child_end();
299 I != E; ++I)
300 if (ContainsLabel(*I, IgnoreCaseStmts))
301 return true;
302
303 return false;
304}
305
Chris Lattner3d6606b2008-11-12 08:04:58 +0000306
307/// ConstantFoldsToSimpleInteger - If the sepcified expression does not fold to
308/// a constant, or if it does but contains a label, return 0. If it constant
309/// folds to 'true' and does not contain a label, return 1, if it constant folds
310/// to 'false' and does not contain a label, return -1.
311int CodeGenFunction::ConstantFoldsToSimpleInteger(const Expr *Cond) {
Daniel Dunbar14937022008-11-12 22:37:10 +0000312 // FIXME: Rename and handle conversion of other evaluatable things
313 // to bool.
Anders Carlsson90d85f32008-12-01 02:46:24 +0000314 Expr::EvalResult Result;
315 if (!Cond->Evaluate(Result, getContext()) || !Result.Val.isInt() ||
316 Result.HasSideEffects)
Anders Carlssonea3c6ab2008-11-22 22:32:07 +0000317 return 0; // Not foldable, not integer or not fully evaluatable.
Chris Lattner3d6606b2008-11-12 08:04:58 +0000318
319 if (CodeGenFunction::ContainsLabel(Cond))
320 return 0; // Contains a label.
321
Anders Carlsson90d85f32008-12-01 02:46:24 +0000322 return Result.Val.getInt().getBoolValue() ? 1 : -1;
Chris Lattner3d6606b2008-11-12 08:04:58 +0000323}
324
325
326/// EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g. for an if
327/// statement) to the specified blocks. Based on the condition, this might try
328/// to simplify the codegen of the conditional based on the branch.
329///
330void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
331 llvm::BasicBlock *TrueBlock,
332 llvm::BasicBlock *FalseBlock) {
333 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond))
334 return EmitBranchOnBoolExpr(PE->getSubExpr(), TrueBlock, FalseBlock);
335
336 if (const BinaryOperator *CondBOp = dyn_cast<BinaryOperator>(Cond)) {
337 // Handle X && Y in a condition.
338 if (CondBOp->getOpcode() == BinaryOperator::LAnd) {
339 // If we have "1 && X", simplify the code. "0 && X" would have constant
340 // folded if the case was simple enough.
341 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == 1) {
342 // br(1 && X) -> br(X).
343 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
344 }
345
346 // If we have "X && 1", simplify the code to use an uncond branch.
347 // "X && 0" would have been constant folded to 0.
348 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == 1) {
349 // br(X && 1) -> br(X).
350 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
351 }
352
353 // Emit the LHS as a conditional. If the LHS conditional is false, we
354 // want to jump to the FalseBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000355 llvm::BasicBlock *LHSTrue = createBasicBlock("land.lhs.true");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000356 EmitBranchOnBoolExpr(CondBOp->getLHS(), LHSTrue, FalseBlock);
357 EmitBlock(LHSTrue);
358
359 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
360 return;
361 } else if (CondBOp->getOpcode() == BinaryOperator::LOr) {
362 // If we have "0 || X", simplify the code. "1 || X" would have constant
363 // folded if the case was simple enough.
364 if (ConstantFoldsToSimpleInteger(CondBOp->getLHS()) == -1) {
365 // br(0 || X) -> br(X).
366 return EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
367 }
368
369 // If we have "X || 0", simplify the code to use an uncond branch.
370 // "X || 1" would have been constant folded to 1.
371 if (ConstantFoldsToSimpleInteger(CondBOp->getRHS()) == -1) {
372 // br(X || 0) -> br(X).
373 return EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, FalseBlock);
374 }
375
376 // Emit the LHS as a conditional. If the LHS conditional is true, we
377 // want to jump to the TrueBlock.
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +0000378 llvm::BasicBlock *LHSFalse = createBasicBlock("lor.lhs.false");
Chris Lattner3d6606b2008-11-12 08:04:58 +0000379 EmitBranchOnBoolExpr(CondBOp->getLHS(), TrueBlock, LHSFalse);
380 EmitBlock(LHSFalse);
381
382 EmitBranchOnBoolExpr(CondBOp->getRHS(), TrueBlock, FalseBlock);
383 return;
384 }
Chris Lattnercfbfe912008-11-12 08:13:36 +0000385 }
386
387 if (const UnaryOperator *CondUOp = dyn_cast<UnaryOperator>(Cond)) {
388 // br(!x, t, f) -> br(x, f, t)
389 if (CondUOp->getOpcode() == UnaryOperator::LNot)
390 return EmitBranchOnBoolExpr(CondUOp->getSubExpr(), FalseBlock, TrueBlock);
Chris Lattner3d6606b2008-11-12 08:04:58 +0000391 }
392
Daniel Dunbarab81c632008-11-12 10:30:32 +0000393 if (const ConditionalOperator *CondOp = dyn_cast<ConditionalOperator>(Cond)) {
394 // Handle ?: operator.
395
396 // Just ignore GNU ?: extension.
397 if (CondOp->getLHS()) {
398 // br(c ? x : y, t, f) -> br(c, br(x, t, f), br(y, t, f))
399 llvm::BasicBlock *LHSBlock = createBasicBlock("cond.true");
400 llvm::BasicBlock *RHSBlock = createBasicBlock("cond.false");
401 EmitBranchOnBoolExpr(CondOp->getCond(), LHSBlock, RHSBlock);
402 EmitBlock(LHSBlock);
403 EmitBranchOnBoolExpr(CondOp->getLHS(), TrueBlock, FalseBlock);
404 EmitBlock(RHSBlock);
405 EmitBranchOnBoolExpr(CondOp->getRHS(), TrueBlock, FalseBlock);
406 return;
407 }
408 }
409
Chris Lattner3d6606b2008-11-12 08:04:58 +0000410 // Emit the code with the fully general case.
411 llvm::Value *CondV = EvaluateExprAsBool(Cond);
412 Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
413}
414
Devang Patel7a78e432007-11-01 19:11:01 +0000415/// getCGRecordLayout - Return record layout info.
416const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000417 QualType Ty) {
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000418 const RecordType *RTy = Ty->getAsRecordType();
Chris Lattner7b2543e2008-02-05 06:55:31 +0000419 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000420
Chris Lattner7b2543e2008-02-05 06:55:31 +0000421 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000422}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000423
Daniel Dunbar9503b782008-08-16 00:56:44 +0000424/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner9d4e6202007-12-02 01:43:38 +0000425/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000426void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
427 bool OmitOnError) {
428 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000429}
430
Daniel Dunbar879788d2008-08-04 16:51:22 +0000431unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
432 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
433 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
434}
435
Chris Lattner96086d82009-04-21 17:59:23 +0000436void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty) {
Owen Anderson73e7f802009-07-14 23:10:40 +0000437 const llvm::Type *BP = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000438 if (DestPtr->getType() != BP)
439 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
440
441 // Get size and alignment info for this aggregate.
442 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
443
Chris Lattner96086d82009-04-21 17:59:23 +0000444 // Don't bother emitting a zero-byte memset.
445 if (TypeInfo.first == 0)
446 return;
447
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000448 // FIXME: Handle variable sized types.
Owen Anderson73e7f802009-07-14 23:10:40 +0000449 const llvm::Type *IntPtr = VMContext.getIntegerType(LLVMPointerWidth);
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000450
451 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
Owen Anderson5f1adc22009-07-13 04:10:07 +0000452 getLLVMContext().getNullValue(llvm::Type::Int8Ty),
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000453 // TypeInfo.first describes size in bits.
Owen Anderson73e7f802009-07-14 23:10:40 +0000454 VMContext.getConstantInt(IntPtr, TypeInfo.first/8),
455 VMContext.getConstantInt(llvm::Type::Int32Ty,
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000456 TypeInfo.second/8));
457}
458
Daniel Dunbar879788d2008-08-04 16:51:22 +0000459void CodeGenFunction::EmitIndirectSwitches() {
460 llvm::BasicBlock *Default;
461
Daniel Dunbar8ccfa802008-08-04 17:24:44 +0000462 if (IndirectSwitches.empty())
463 return;
464
Daniel Dunbar879788d2008-08-04 16:51:22 +0000465 if (!LabelIDs.empty()) {
466 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
467 } else {
468 // No possible targets for indirect goto, just emit an infinite
469 // loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000470 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000471 llvm::BranchInst::Create(Default, Default);
472 }
473
474 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
475 e = IndirectSwitches.end(); i != e; ++i) {
476 llvm::SwitchInst *I = *i;
477
478 I->setSuccessor(0, Default);
479 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
480 LE = LabelIDs.end(); LI != LE; ++LI) {
Owen Anderson73e7f802009-07-14 23:10:40 +0000481 I->addCase(VMContext.getConstantInt(llvm::Type::Int32Ty,
Daniel Dunbar879788d2008-08-04 16:51:22 +0000482 LI->second),
483 getBasicBlockForLabel(LI->first));
484 }
485 }
486}
Anders Carlsson285611e2008-11-04 05:30:00 +0000487
Daniel Dunbare94e4862009-07-19 06:58:07 +0000488llvm::Value *CodeGenFunction::GetVLASize(const VariableArrayType *VAT) {
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000489 llvm::Value *&SizeEntry = VLASizeMap[VAT];
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000490
Anders Carlssonf860e022008-12-20 20:27:15 +0000491 assert(SizeEntry && "Did not emit size for type");
492 return SizeEntry;
493}
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000494
Daniel Dunbare94e4862009-07-19 06:58:07 +0000495llvm::Value *CodeGenFunction::EmitVLASize(QualType Ty) {
Anders Carlssond9767612008-12-20 20:46:34 +0000496 assert(Ty->isVariablyModifiedType() &&
497 "Must pass variably modified type to EmitVLASizes!");
Anders Carlssonf860e022008-12-20 20:27:15 +0000498
Daniel Dunbare94e4862009-07-19 06:58:07 +0000499 EnsureInsertPoint();
500
Anders Carlssond9767612008-12-20 20:46:34 +0000501 if (const VariableArrayType *VAT = getContext().getAsVariableArrayType(Ty)) {
502 llvm::Value *&SizeEntry = VLASizeMap[VAT];
503
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000504 if (!SizeEntry) {
505 // Get the element size;
506 llvm::Value *ElemSize;
Anders Carlssond9767612008-12-20 20:46:34 +0000507
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000508 QualType ElemTy = VAT->getElementType();
Anders Carlsson8f30de92009-02-05 19:43:10 +0000509
510 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
511
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000512 if (ElemTy->isVariableArrayType())
513 ElemSize = EmitVLASize(ElemTy);
514 else {
Owen Anderson73e7f802009-07-14 23:10:40 +0000515 ElemSize = VMContext.getConstantInt(SizeTy,
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000516 getContext().getTypeSize(ElemTy) / 8);
517 }
Anders Carlssond9767612008-12-20 20:46:34 +0000518
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000519 llvm::Value *NumElements = EmitScalarExpr(VAT->getSizeExpr());
Anders Carlsson8f30de92009-02-05 19:43:10 +0000520 NumElements = Builder.CreateIntCast(NumElements, SizeTy, false, "tmp");
521
Anders Carlssonef2f7df2008-12-20 21:51:53 +0000522 SizeEntry = Builder.CreateMul(ElemSize, NumElements);
Anders Carlssond9767612008-12-20 20:46:34 +0000523 }
524
Anders Carlssond9767612008-12-20 20:46:34 +0000525 return SizeEntry;
Eli Friedman16444cf2009-05-29 19:23:46 +0000526 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
527 EmitVLASize(AT->getElementType());
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000528 } else if (const PointerType *PT = Ty->getAsPointerType())
Anders Carlssond9767612008-12-20 20:46:34 +0000529 EmitVLASize(PT->getPointeeType());
Anders Carlssonf860e022008-12-20 20:27:15 +0000530 else {
Anders Carlssond9767612008-12-20 20:46:34 +0000531 assert(0 && "unknown VM type!");
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000532 }
Anders Carlssond9767612008-12-20 20:46:34 +0000533
534 return 0;
Anders Carlsson32aa0c22008-12-12 07:19:02 +0000535}
Eli Friedman8f5e8782009-01-20 17:46:04 +0000536
537llvm::Value* CodeGenFunction::EmitVAListRef(const Expr* E) {
538 if (CGM.getContext().getBuiltinVaListType()->isArrayType()) {
539 return EmitScalarExpr(E);
540 }
541 return EmitLValue(E).getAddress();
542}
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000543
Anders Carlsson459ee362009-02-08 03:22:36 +0000544void CodeGenFunction::PushCleanupBlock(llvm::BasicBlock *CleanupBlock)
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000545{
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000546 CleanupEntries.push_back(CleanupEntry(CleanupBlock));
Anders Carlsson9c5b2a42009-02-07 22:53:43 +0000547}
Anders Carlsson883fa552009-02-07 23:50:39 +0000548
549void CodeGenFunction::EmitCleanupBlocks(size_t OldCleanupStackSize)
550{
551 assert(CleanupEntries.size() >= OldCleanupStackSize &&
552 "Cleanup stack mismatch!");
553
554 while (CleanupEntries.size() > OldCleanupStackSize)
555 EmitCleanupBlock();
556}
557
Anders Carlssondf274192009-02-08 07:46:24 +0000558CodeGenFunction::CleanupBlockInfo CodeGenFunction::PopCleanupBlock()
Anders Carlsson883fa552009-02-07 23:50:39 +0000559{
Anders Carlssondf274192009-02-08 07:46:24 +0000560 CleanupEntry &CE = CleanupEntries.back();
561
562 llvm::BasicBlock *CleanupBlock = CE.CleanupBlock;
563
564 std::vector<llvm::BasicBlock *> Blocks;
565 std::swap(Blocks, CE.Blocks);
566
567 std::vector<llvm::BranchInst *> BranchFixups;
568 std::swap(BranchFixups, CE.BranchFixups);
569
570 CleanupEntries.pop_back();
571
Anders Carlsson98720f02009-02-08 22:45:15 +0000572 // Check if any branch fixups pointed to the scope we just popped. If so,
573 // we can remove them.
574 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
575 llvm::BasicBlock *Dest = BranchFixups[i]->getSuccessor(0);
576 BlockScopeMap::iterator I = BlockScopes.find(Dest);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000577
Anders Carlsson98720f02009-02-08 22:45:15 +0000578 if (I == BlockScopes.end())
579 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000580
Anders Carlsson98720f02009-02-08 22:45:15 +0000581 assert(I->second <= CleanupEntries.size() && "Invalid branch fixup!");
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000582
Anders Carlsson98720f02009-02-08 22:45:15 +0000583 if (I->second == CleanupEntries.size()) {
584 // We don't need to do this branch fixup.
585 BranchFixups[i] = BranchFixups.back();
586 BranchFixups.pop_back();
587 i--;
588 e--;
589 continue;
Anders Carlsson9b399792009-02-08 01:23:05 +0000590 }
591 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000592
Anders Carlssondf274192009-02-08 07:46:24 +0000593 llvm::BasicBlock *SwitchBlock = 0;
594 llvm::BasicBlock *EndBlock = 0;
Anders Carlsson9b399792009-02-08 01:23:05 +0000595 if (!BranchFixups.empty()) {
Anders Carlssondf274192009-02-08 07:46:24 +0000596 SwitchBlock = createBasicBlock("cleanup.switch");
597 EndBlock = createBasicBlock("cleanup.end");
Anders Carlsson9b399792009-02-08 01:23:05 +0000598
Anders Carlssondf274192009-02-08 07:46:24 +0000599 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000600
Anders Carlssondf274192009-02-08 07:46:24 +0000601 Builder.SetInsertPoint(SwitchBlock);
602
Anders Carlsson9b399792009-02-08 01:23:05 +0000603 llvm::Value *DestCodePtr = CreateTempAlloca(llvm::Type::Int32Ty,
604 "cleanup.dst");
605 llvm::Value *DestCode = Builder.CreateLoad(DestCodePtr, "tmp");
606
607 // Create a switch instruction to determine where to jump next.
Anders Carlssondf274192009-02-08 07:46:24 +0000608 llvm::SwitchInst *SI = Builder.CreateSwitch(DestCode, EndBlock,
Anders Carlsson9b399792009-02-08 01:23:05 +0000609 BranchFixups.size());
Anders Carlssondf274192009-02-08 07:46:24 +0000610
Anders Carlsson32fffb72009-02-08 22:13:37 +0000611 // Restore the current basic block (if any)
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000612 if (CurBB) {
Anders Carlsson32fffb72009-02-08 22:13:37 +0000613 Builder.SetInsertPoint(CurBB);
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000614
615 // If we had a current basic block, we also need to emit an instruction
616 // to initialize the cleanup destination.
Owen Anderson5f1adc22009-07-13 04:10:07 +0000617 Builder.CreateStore(getLLVMContext().getNullValue(llvm::Type::Int32Ty),
Anders Carlsson031eb3e2009-03-17 05:53:35 +0000618 DestCodePtr);
619 } else
Anders Carlsson32fffb72009-02-08 22:13:37 +0000620 Builder.ClearInsertionPoint();
Anders Carlssondf274192009-02-08 07:46:24 +0000621
Anders Carlsson9b399792009-02-08 01:23:05 +0000622 for (size_t i = 0, e = BranchFixups.size(); i != e; ++i) {
623 llvm::BranchInst *BI = BranchFixups[i];
624 llvm::BasicBlock *Dest = BI->getSuccessor(0);
625
Anders Carlsson9b399792009-02-08 01:23:05 +0000626 // Fixup the branch instruction to point to the cleanup block.
627 BI->setSuccessor(0, CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000628
Anders Carlsson9b399792009-02-08 01:23:05 +0000629 if (CleanupEntries.empty()) {
Anders Carlsson8be63402009-02-08 22:46:50 +0000630 llvm::ConstantInt *ID;
631
632 // Check if we already have a destination for this block.
633 if (Dest == SI->getDefaultDest())
Owen Anderson73e7f802009-07-14 23:10:40 +0000634 ID = VMContext.getConstantInt(llvm::Type::Int32Ty, 0);
Anders Carlsson8be63402009-02-08 22:46:50 +0000635 else {
636 ID = SI->findCaseDest(Dest);
637 if (!ID) {
638 // No code found, get a new unique one by using the number of
639 // switch successors.
Owen Anderson73e7f802009-07-14 23:10:40 +0000640 ID = VMContext.getConstantInt(llvm::Type::Int32Ty,
Anders Carlsson8be63402009-02-08 22:46:50 +0000641 SI->getNumSuccessors());
642 SI->addCase(ID, Dest);
643 }
644 }
645
646 // Store the jump destination before the branch instruction.
647 new llvm::StoreInst(ID, DestCodePtr, BI);
Anders Carlsson9b399792009-02-08 01:23:05 +0000648 } else {
649 // We need to jump through another cleanup block. Create a pad block
650 // with a branch instruction that jumps to the final destination and
651 // add it as a branch fixup to the current cleanup scope.
652
653 // Create the pad block.
654 llvm::BasicBlock *CleanupPad = createBasicBlock("cleanup.pad", CurFn);
Anders Carlsson8be63402009-02-08 22:46:50 +0000655
656 // Create a unique case ID.
Owen Anderson73e7f802009-07-14 23:10:40 +0000657 llvm::ConstantInt *ID = VMContext.getConstantInt(llvm::Type::Int32Ty,
Anders Carlsson8be63402009-02-08 22:46:50 +0000658 SI->getNumSuccessors());
659
660 // Store the jump destination before the branch instruction.
661 new llvm::StoreInst(ID, DestCodePtr, BI);
662
Anders Carlsson9b399792009-02-08 01:23:05 +0000663 // Add it as the destination.
Anders Carlsson8be63402009-02-08 22:46:50 +0000664 SI->addCase(ID, CleanupPad);
Anders Carlsson9b399792009-02-08 01:23:05 +0000665
666 // Create the branch to the final destination.
667 llvm::BranchInst *BI = llvm::BranchInst::Create(Dest);
668 CleanupPad->getInstList().push_back(BI);
669
670 // And add it as a branch fixup.
671 CleanupEntries.back().BranchFixups.push_back(BI);
672 }
673 }
674 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000675
Anders Carlssone7de3522009-02-08 00:16:35 +0000676 // Remove all blocks from the block scope map.
677 for (size_t i = 0, e = Blocks.size(); i != e; ++i) {
678 assert(BlockScopes.count(Blocks[i]) &&
679 "Did not find block in scope map!");
680
681 BlockScopes.erase(Blocks[i]);
682 }
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000683
Anders Carlssondf274192009-02-08 07:46:24 +0000684 return CleanupBlockInfo(CleanupBlock, SwitchBlock, EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000685}
686
687void CodeGenFunction::EmitCleanupBlock()
688{
Anders Carlssondf274192009-02-08 07:46:24 +0000689 CleanupBlockInfo Info = PopCleanupBlock();
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000690
Anders Carlsson93690d62009-05-31 00:33:20 +0000691 llvm::BasicBlock *CurBB = Builder.GetInsertBlock();
692 if (CurBB && !CurBB->getTerminator() &&
693 Info.CleanupBlock->getNumUses() == 0) {
694 CurBB->getInstList().splice(CurBB->end(), Info.CleanupBlock->getInstList());
695 delete Info.CleanupBlock;
696 } else
697 EmitBlock(Info.CleanupBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000698
Anders Carlssondf274192009-02-08 07:46:24 +0000699 if (Info.SwitchBlock)
700 EmitBlock(Info.SwitchBlock);
701 if (Info.EndBlock)
702 EmitBlock(Info.EndBlock);
Anders Carlssone75ae4d2009-02-08 03:55:35 +0000703}
704
Anders Carlssoned536bc2009-02-08 00:50:42 +0000705void CodeGenFunction::AddBranchFixup(llvm::BranchInst *BI)
706{
707 assert(!CleanupEntries.empty() &&
708 "Trying to add branch fixup without cleanup block!");
709
Mike Stumpba2cb0e2009-05-16 07:57:57 +0000710 // FIXME: We could be more clever here and check if there's already a branch
711 // fixup for this destination and recycle it.
Anders Carlssoned536bc2009-02-08 00:50:42 +0000712 CleanupEntries.back().BranchFixups.push_back(BI);
713}
714
715void CodeGenFunction::EmitBranchThroughCleanup(llvm::BasicBlock *Dest)
716{
Anders Carlsson32fffb72009-02-08 22:13:37 +0000717 if (!HaveInsertPoint())
718 return;
719
Anders Carlssoned536bc2009-02-08 00:50:42 +0000720 llvm::BranchInst* BI = Builder.CreateBr(Dest);
721
Anders Carlsson32fffb72009-02-08 22:13:37 +0000722 Builder.ClearInsertionPoint();
723
Anders Carlssoned536bc2009-02-08 00:50:42 +0000724 // The stack is empty, no need to do any cleanup.
725 if (CleanupEntries.empty())
726 return;
727
728 if (!Dest->getParent()) {
729 // We are trying to branch to a block that hasn't been inserted yet.
730 AddBranchFixup(BI);
731 return;
732 }
733
734 BlockScopeMap::iterator I = BlockScopes.find(Dest);
735 if (I == BlockScopes.end()) {
736 // We are trying to jump to a block that is outside of any cleanup scope.
737 AddBranchFixup(BI);
738 return;
739 }
740
741 assert(I->second < CleanupEntries.size() &&
742 "Trying to branch into cleanup region");
743
744 if (I->second == CleanupEntries.size() - 1) {
745 // We have a branch to a block in the same scope.
746 return;
747 }
748
749 AddBranchFixup(BI);
750}