blob: 909486a6d1a944a200833e0477c7b055debd3900 [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"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "llvm/Analysis/Verifier.h"
Devang Pateld9363c32007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022using namespace clang;
23using namespace CodeGen;
24
25CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patelc049e4f2007-10-08 20:57:48 +000026 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattner41110242008-06-17 18:05:57 +000027 CaseRangeBlock(NULL) {
28 LLVMIntTy = ConvertType(getContext().IntTy);
29 LLVMPointerWidth = Target.getPointerWidth(0);
30}
Reid Spencer5f016e22007-07-11 17:01:13 +000031
32ASTContext &CodeGenFunction::getContext() const {
33 return CGM.getContext();
34}
35
36
37llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
38 llvm::BasicBlock *&BB = LabelMap[S];
39 if (BB) return BB;
40
41 // Create, but don't insert, the new block.
Gabor Greif984d0b42008-04-06 20:42:52 +000042 return BB = llvm::BasicBlock::Create(S->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000043}
44
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000045llvm::Constant *
Steve Naroff248a7532008-04-15 22:42:06 +000046CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000047 return cast<llvm::Constant>(LocalDeclMap[BVD]);
48}
Reid Spencer5f016e22007-07-11 17:01:13 +000049
50const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
51 return CGM.getTypes().ConvertType(T);
52}
53
Chris Lattner41110242008-06-17 18:05:57 +000054bool CodeGenFunction::isObjCPointerType(QualType T) {
55 // All Objective-C types are pointers.
56 return T->isObjCInterfaceType() ||
57 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
58}
59
Reid Spencer5f016e22007-07-11 17:01:13 +000060bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner41110242008-06-17 18:05:57 +000061 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
62 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Reid Spencer5f016e22007-07-11 17:01:13 +000063}
64
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000065void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar0ffb1252008-08-04 16:51:22 +000066 // Finish emission of indirect switches.
67 EmitIndirectSwitches();
68
Sanjiv Guptaaf994172008-07-04 11:04:26 +000069 // Emit debug descriptor for function end.
70 CGDebugInfo *DI = CGM.getDebugInfo();
71 if (DI) {
Daniel Dunbaraf05bb92008-08-26 08:29:31 +000072 if (EndLoc.isValid()) {
73 DI->setLocation(EndLoc);
Sanjiv Guptaaf994172008-07-04 11:04:26 +000074 }
75 DI->EmitRegionEnd(CurFn, Builder);
76 }
77
Chris Lattner391d77a2008-03-30 23:03:07 +000078 // Emit a return for code that falls off the end. If insert point
79 // is a dummy block with no predecessors then remove the block itself.
80 llvm::BasicBlock *BB = Builder.GetInsertBlock();
81 if (isDummyBlock(BB))
82 BB->eraseFromParent();
83 else {
Devang Pateld9363c32007-09-28 21:49:18 +000084 // FIXME: if this is C++ main, this should return 0.
85 if (CurFn->getReturnType() == llvm::Type::VoidTy)
86 Builder.CreateRetVoid();
87 else
88 Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
89 }
Chris Lattnerda138702007-07-16 21:28:45 +000090 assert(BreakContinueStack.empty() &&
91 "mismatched push/pop in break/continue stack!");
92
Chris Lattner5a2fa142007-12-02 06:32:24 +000093 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
94 AllocaInsertPt->eraseFromParent();
95 AllocaInsertPt = 0;
96
Reid Spencer5f016e22007-07-11 17:01:13 +000097 // Verify that the function is well formed.
Chris Lattner391d77a2008-03-30 23:03:07 +000098 assert(!verifyFunction(*CurFn) && "Generated function is not well formed.");
Reid Spencer5f016e22007-07-11 17:01:13 +000099}
100
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000101void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
102 llvm::Function *Fn) {
Chris Lattner41110242008-06-17 18:05:57 +0000103 CurFuncDecl = FD;
104 FnRetTy = FD->getResultType();
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000105 CurFn = Fn;
Chris Lattner41110242008-06-17 18:05:57 +0000106 assert(CurFn->isDeclaration() && "Function already has body?");
107
108 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
109
110 // Create a marker to make it easy to insert allocas into the entryblock
111 // later. Don't create this with the builder, because we don't want it
112 // folded.
113 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
114 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
115 EntryBB);
116
117 Builder.SetInsertPoint(EntryBB);
118
Sanjiv Guptaaf994172008-07-04 11:04:26 +0000119 // Emit subprogram debug descriptor.
120 CGDebugInfo *DI = CGM.getDebugInfo();
121 if (DI) {
122 CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody());
123 if (body && body->getLBracLoc().isValid()) {
124 DI->setLocation(body->getLBracLoc());
125 }
126 DI->EmitFunctionStart(FD, CurFn, Builder);
127 }
128
Chris Lattner41110242008-06-17 18:05:57 +0000129 // Emit allocs for param decls. Give the LLVM Argument nodes names.
130 llvm::Function::arg_iterator AI = CurFn->arg_begin();
131
132 // Name the struct return argument.
133 if (hasAggregateLLVMType(FD->getResultType())) {
134 AI->setName("agg.result");
135 ++AI;
136 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000137
138 if (FD->getNumParams()) {
139 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
140 assert(FProto && "Function def must have prototype!");
141 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) {
142 assert(AI != CurFn->arg_end() && "Argument mismatch!");
143 const ParmVarDecl* CurParam = FD->getParamDecl(i);
144 llvm::Value* V = AI;
145 if (!getContext().typesAreCompatible(FProto->getArgType(i),
146 CurParam->getType())) {
147 // This must be a promotion, for something like
148 // "void a(x) short x; {..."
149 V = EmitScalarConversion(V, FProto->getArgType(i),
150 CurParam->getType());
151 }
152 EmitParmDecl(*CurParam, V);
153 }
Chris Lattner41110242008-06-17 18:05:57 +0000154 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000155
156 EmitStmt(FD->getBody());
157
158 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
159 if (S) {
160 FinishFunction(S->getRBracLoc());
161 } else {
162 FinishFunction();
163 }
Chris Lattner41110242008-06-17 18:05:57 +0000164}
165
Devang Pateld9363c32007-09-28 21:49:18 +0000166/// isDummyBlock - Return true if BB is an empty basic block
167/// with no predecessors.
168bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
Chris Lattner1e9660e2008-07-25 23:40:10 +0000169 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
Devang Pateld9363c32007-09-28 21:49:18 +0000170 return true;
171 return false;
172}
173
Devang Patel51b09f22007-10-04 23:45:31 +0000174/// StartBlock - Start new block named N. If insert block is a dummy block
175/// then reuse it.
176void CodeGenFunction::StartBlock(const char *N) {
177 llvm::BasicBlock *BB = Builder.GetInsertBlock();
178 if (!isDummyBlock(BB))
Gabor Greif984d0b42008-04-06 20:42:52 +0000179 EmitBlock(llvm::BasicBlock::Create(N));
Devang Patel51b09f22007-10-04 23:45:31 +0000180 else
181 BB->setName(N);
182}
183
Devang Patel88a981b2007-11-01 19:11:01 +0000184/// getCGRecordLayout - Return record layout info.
185const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattneraf319132008-02-05 06:55:31 +0000186 QualType Ty) {
187 const RecordType *RTy = Ty->getAsRecordType();
188 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelb84a06e2007-10-23 02:10:49 +0000189
Chris Lattneraf319132008-02-05 06:55:31 +0000190 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelb84a06e2007-10-23 02:10:49 +0000191}
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000192
Daniel Dunbar488e9932008-08-16 00:56:44 +0000193/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000194/// specified stmt yet.
Daniel Dunbar488e9932008-08-16 00:56:44 +0000195void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type) {
196 CGM.ErrorUnsupported(S, Type);
Chris Lattnerdc5e8262007-12-02 01:43:38 +0000197}
198
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000199unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
200 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
201 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
202}
203
204void CodeGenFunction::EmitIndirectSwitches() {
205 llvm::BasicBlock *Default;
206
Daniel Dunbar76526a52008-08-04 17:24:44 +0000207 if (IndirectSwitches.empty())
208 return;
209
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000210 if (!LabelIDs.empty()) {
211 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
212 } else {
213 // No possible targets for indirect goto, just emit an infinite
214 // loop.
215 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn);
216 llvm::BranchInst::Create(Default, Default);
217 }
218
219 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
220 e = IndirectSwitches.end(); i != e; ++i) {
221 llvm::SwitchInst *I = *i;
222
223 I->setSuccessor(0, Default);
224 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
225 LE = LabelIDs.end(); LI != LE; ++LI) {
226 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
227 LI->second),
228 getBasicBlockForLabel(LI->first));
229 }
230 }
231}