blob: 12e468c12706c2c446c4a9569cc327aa75cd19a3 [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"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000019#include "clang/AST/Decl.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "llvm/Analysis/Verifier.h"
Devang Patel97299362007-09-28 21:49:18 +000021#include "llvm/Support/CFG.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23using namespace CodeGen;
24
25CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patel347ca322007-10-08 20:57:48 +000026 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattner8c7c6a12008-06-17 18:05:57 +000027 CaseRangeBlock(NULL) {
28 LLVMIntTy = ConvertType(getContext().IntTy);
29 LLVMPointerWidth = Target.getPointerWidth(0);
30}
Chris Lattner4b009652007-07-25 00:24:17 +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 Greif815e2c12008-04-06 20:42:52 +000042 return BB = llvm::BasicBlock::Create(S->getName());
Chris Lattner4b009652007-07-25 00:24:17 +000043}
44
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000045llvm::Constant *
Steve Naroff72a6ebc2008-04-15 22:42:06 +000046CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000047 return cast<llvm::Constant>(LocalDeclMap[BVD]);
48}
Chris Lattner4b009652007-07-25 00:24:17 +000049
Anders Carlsson75d86732008-09-11 09:15:33 +000050llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51{
52 return LocalDeclMap[VD];
53}
54
Chris Lattner4b009652007-07-25 00:24:17 +000055const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56 return CGM.getTypes().ConvertType(T);
57}
58
Chris Lattner8c7c6a12008-06-17 18:05:57 +000059bool CodeGenFunction::isObjCPointerType(QualType T) {
60 // All Objective-C types are pointers.
61 return T->isObjCInterfaceType() ||
62 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63}
64
Chris Lattner4b009652007-07-25 00:24:17 +000065bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner8c7c6a12008-06-17 18:05:57 +000066 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
67 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +000068}
69
Daniel Dunbar6b57d432008-08-26 08:29:31 +000070void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar879788d2008-08-04 16:51:22 +000071 // Finish emission of indirect switches.
72 EmitIndirectSwitches();
73
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +000074 // Emit debug descriptor for function end.
Daniel Dunbar9fb751f2008-09-09 21:00:17 +000075 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +000076 DI->setLocation(EndLoc);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +000077 DI->EmitRegionEnd(CurFn, Builder);
78 }
79
Chris Lattner4b009652007-07-25 00:24:17 +000080 assert(BreakContinueStack.empty() &&
81 "mismatched push/pop in break/continue stack!");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +000082
Daniel Dunbar7a57b8d2008-09-27 07:15:59 +000083 // Emit function epilog (to return). This has the nice side effect
84 // of also automatically handling code that falls off the end.
85 EmitBlock(ReturnBlock);
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +000086 EmitFunctionEpilog(FnRetTy, ReturnValue);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +000087
Chris Lattnerca929812007-12-02 06:32:24 +000088 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
89 AllocaInsertPt->eraseFromParent();
90 AllocaInsertPt = 0;
91
Chris Lattner4b009652007-07-25 00:24:17 +000092 // Verify that the function is well formed.
Daniel Dunbar55dd2bb2008-09-17 21:13:22 +000093 if (verifyFunction(*CurFn, llvm::PrintMessageAction)) {
94 CurFn->dump();
95 assert(0 && "Function failed verification!");
96 }
Chris Lattner4b009652007-07-25 00:24:17 +000097}
98
Daniel Dunbar96816832008-09-09 23:14:03 +000099void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
100 llvm::Function *Fn,
101 const FunctionArgList &Args) {
102 CurFuncDecl = D;
103 FnRetTy = RetTy;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +0000104 CurFn = Fn;
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000105 assert(CurFn->isDeclaration() && "Function already has body?");
106
107 llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000108
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000109 // Create a marker to make it easy to insert allocas into the entryblock
110 // later. Don't create this with the builder, because we don't want it
111 // folded.
112 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
113 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
114 EntryBB);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000115
Daniel Dunbar7a57b8d2008-09-27 07:15:59 +0000116 ReturnBlock = llvm::BasicBlock::Create("return");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000117 ReturnValue = 0;
Daniel Dunbar96816832008-09-09 23:14:03 +0000118 if (!RetTy->isVoidType())
119 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000120
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000121 Builder.SetInsertPoint(EntryBB);
122
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000123 // Emit subprogram debug descriptor.
Daniel Dunbar96816832008-09-09 23:14:03 +0000124 // FIXME: The cast here is a huge hack.
125 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
126 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +0000127 if (CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody()))
Daniel Dunbar96816832008-09-09 23:14:03 +0000128 DI->setLocation(body->getLBracLoc());
Daniel Dunbar96816832008-09-09 23:14:03 +0000129 DI->EmitFunctionStart(FD, CurFn, Builder);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000130 }
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000131 }
132
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +0000133 EmitFunctionProlog(CurFn, FnRetTy, Args);
Daniel Dunbar96816832008-09-09 23:14:03 +0000134}
Eli Friedman769e7302008-08-25 21:31:01 +0000135
Daniel Dunbar96816832008-09-09 23:14:03 +0000136void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
137 llvm::Function *Fn) {
138 FunctionArgList Args;
Eli Friedman769e7302008-08-25 21:31:01 +0000139 if (FD->getNumParams()) {
140 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
141 assert(FProto && "Function def must have prototype!");
Daniel Dunbar96816832008-09-09 23:14:03 +0000142
143 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
144 Args.push_back(std::make_pair(FD->getParamDecl(i),
145 FProto->getArgType(i)));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000146 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000147
Daniel Dunbar96816832008-09-09 23:14:03 +0000148 StartFunction(FD, FD->getResultType(), Fn, Args);
149
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000150 EmitStmt(FD->getBody());
151
152 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
153 if (S) {
154 FinishFunction(S->getRBracLoc());
155 } else {
156 FinishFunction();
157 }
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000158}
159
Devang Patel97299362007-09-28 21:49:18 +0000160/// isDummyBlock - Return true if BB is an empty basic block
161/// with no predecessors.
162bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
Chris Lattnerdad85512008-07-25 23:40:10 +0000163 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
Devang Patel97299362007-09-28 21:49:18 +0000164 return true;
165 return false;
166}
167
Devang Patele58e0802007-10-04 23:45:31 +0000168/// StartBlock - Start new block named N. If insert block is a dummy block
169/// then reuse it.
170void CodeGenFunction::StartBlock(const char *N) {
171 llvm::BasicBlock *BB = Builder.GetInsertBlock();
172 if (!isDummyBlock(BB))
Gabor Greif815e2c12008-04-06 20:42:52 +0000173 EmitBlock(llvm::BasicBlock::Create(N));
Devang Patele58e0802007-10-04 23:45:31 +0000174 else
175 BB->setName(N);
176}
177
Devang Patel7a78e432007-11-01 19:11:01 +0000178/// getCGRecordLayout - Return record layout info.
179const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000180 QualType Ty) {
181 const RecordType *RTy = Ty->getAsRecordType();
182 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000183
Chris Lattner7b2543e2008-02-05 06:55:31 +0000184 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000185}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000186
Daniel Dunbar9503b782008-08-16 00:56:44 +0000187/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner9d4e6202007-12-02 01:43:38 +0000188/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000189void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
190 bool OmitOnError) {
191 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000192}
193
Daniel Dunbar879788d2008-08-04 16:51:22 +0000194unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
195 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
196 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
197}
198
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000199void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
200{
201 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
202 if (DestPtr->getType() != BP)
203 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
204
205 // Get size and alignment info for this aggregate.
206 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
207
208 // FIXME: Handle variable sized types.
209 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
210
211 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
212 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
213 // TypeInfo.first describes size in bits.
214 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
215 llvm::ConstantInt::get(llvm::Type::Int32Ty,
216 TypeInfo.second/8));
217}
218
Daniel Dunbar879788d2008-08-04 16:51:22 +0000219void CodeGenFunction::EmitIndirectSwitches() {
220 llvm::BasicBlock *Default;
221
Daniel Dunbar8ccfa802008-08-04 17:24:44 +0000222 if (IndirectSwitches.empty())
223 return;
224
Daniel Dunbar879788d2008-08-04 16:51:22 +0000225 if (!LabelIDs.empty()) {
226 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
227 } else {
228 // No possible targets for indirect goto, just emit an infinite
229 // loop.
230 Default = llvm::BasicBlock::Create("indirectgoto.loop", CurFn);
231 llvm::BranchInst::Create(Default, Default);
232 }
233
234 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
235 e = IndirectSwitches.end(); i != e; ++i) {
236 llvm::SwitchInst *I = *i;
237
238 I->setSuccessor(0, Default);
239 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
240 LE = LabelIDs.end(); LI != LE; ++LI) {
241 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
242 LI->second),
243 getBasicBlockForLabel(LI->first));
244 }
245 }
246}