blob: 427f6457bb7eb05ef4b2f54dac68a22d8373010d [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"
Devang Patel97299362007-09-28 21:49:18 +000020#include "llvm/Support/CFG.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021using namespace clang;
22using namespace CodeGen;
23
24CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
Devang Patel347ca322007-10-08 20:57:48 +000025 : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
Chris Lattner8c7c6a12008-06-17 18:05:57 +000026 CaseRangeBlock(NULL) {
27 LLVMIntTy = ConvertType(getContext().IntTy);
28 LLVMPointerWidth = Target.getPointerWidth(0);
29}
Chris Lattner4b009652007-07-25 00:24:17 +000030
31ASTContext &CodeGenFunction::getContext() const {
32 return CGM.getContext();
33}
34
35
36llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
37 llvm::BasicBlock *&BB = LabelMap[S];
38 if (BB) return BB;
39
40 // Create, but don't insert, the new block.
Daniel Dunbar72f96552008-11-11 02:29:29 +000041 return BB = createBasicBlock(S->getName());
Chris Lattner4b009652007-07-25 00:24:17 +000042}
43
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000044llvm::Constant *
Steve Naroff72a6ebc2008-04-15 22:42:06 +000045CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
Lauro Ramos Venancio934fb022008-02-26 21:41:45 +000046 return cast<llvm::Constant>(LocalDeclMap[BVD]);
47}
Chris Lattner4b009652007-07-25 00:24:17 +000048
Anders Carlsson75d86732008-09-11 09:15:33 +000049llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
50{
51 return LocalDeclMap[VD];
52}
53
Chris Lattner4b009652007-07-25 00:24:17 +000054const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
55 return CGM.getTypes().ConvertType(T);
56}
57
Chris Lattner8c7c6a12008-06-17 18:05:57 +000058bool CodeGenFunction::isObjCPointerType(QualType T) {
59 // All Objective-C types are pointers.
60 return T->isObjCInterfaceType() ||
61 T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
62}
63
Chris Lattner4b009652007-07-25 00:24:17 +000064bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
Chris Lattner8c7c6a12008-06-17 18:05:57 +000065 return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
66 !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
Chris Lattner4b009652007-07-25 00:24:17 +000067}
68
Daniel Dunbar6b57d432008-08-26 08:29:31 +000069void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
Daniel Dunbar879788d2008-08-04 16:51:22 +000070 // Finish emission of indirect switches.
71 EmitIndirectSwitches();
72
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +000073 // Emit debug descriptor for function end.
Daniel Dunbar9fb751f2008-09-09 21:00:17 +000074 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
Daniel Dunbar6fc1f972008-10-17 16:15:48 +000075 DI->setLocation(EndLoc);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +000076 DI->EmitRegionEnd(CurFn, Builder);
77 }
78
Chris Lattner4b009652007-07-25 00:24:17 +000079 assert(BreakContinueStack.empty() &&
80 "mismatched push/pop in break/continue stack!");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +000081
Daniel Dunbar7a57b8d2008-09-27 07:15:59 +000082 // Emit function epilog (to return). This has the nice side effect
83 // of also automatically handling code that falls off the end.
84 EmitBlock(ReturnBlock);
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +000085 EmitFunctionEpilog(FnRetTy, ReturnValue);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +000086
Chris Lattnerca929812007-12-02 06:32:24 +000087 // Remove the AllocaInsertPt instruction, which is just a convenience for us.
88 AllocaInsertPt->eraseFromParent();
89 AllocaInsertPt = 0;
Chris Lattner4b009652007-07-25 00:24:17 +000090}
91
Daniel Dunbar96816832008-09-09 23:14:03 +000092void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
93 llvm::Function *Fn,
Daniel Dunbar54968bf2008-10-18 18:22:23 +000094 const FunctionArgList &Args,
95 SourceLocation StartLoc) {
Daniel Dunbar96816832008-09-09 23:14:03 +000096 CurFuncDecl = D;
97 FnRetTy = RetTy;
Daniel Dunbar7bf5b3d2008-07-29 23:18:29 +000098 CurFn = Fn;
Chris Lattner8c7c6a12008-06-17 18:05:57 +000099 assert(CurFn->isDeclaration() && "Function already has body?");
100
Daniel Dunbar72f96552008-11-11 02:29:29 +0000101 llvm::BasicBlock *EntryBB = createBasicBlock("entry", CurFn);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000102
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000103 // Create a marker to make it easy to insert allocas into the entryblock
104 // later. Don't create this with the builder, because we don't want it
105 // folded.
106 llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
107 AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
108 EntryBB);
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000109
Daniel Dunbar72f96552008-11-11 02:29:29 +0000110 ReturnBlock = createBasicBlock("return");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000111 ReturnValue = 0;
Daniel Dunbar96816832008-09-09 23:14:03 +0000112 if (!RetTy->isVoidType())
113 ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
Daniel Dunbar9fb751f2008-09-09 21:00:17 +0000114
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000115 Builder.SetInsertPoint(EntryBB);
116
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000117 // Emit subprogram debug descriptor.
Daniel Dunbar96816832008-09-09 23:14:03 +0000118 // FIXME: The cast here is a huge hack.
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000119 if (CGDebugInfo *DI = CGM.getDebugInfo()) {
120 DI->setLocation(StartLoc);
121 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
122 DI->EmitFunctionStart(FD->getName(), RetTy, CurFn, Builder);
123 } else {
124 // Just use LLVM function name.
125 DI->EmitFunctionStart(Fn->getName().c_str(),
126 RetTy, CurFn, Builder);
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000127 }
Sanjiv Gupta1d340eb2008-07-04 11:04:26 +0000128 }
129
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +0000130 EmitFunctionProlog(CurFn, FnRetTy, Args);
Daniel Dunbar96816832008-09-09 23:14:03 +0000131}
Eli Friedman769e7302008-08-25 21:31:01 +0000132
Daniel Dunbar96816832008-09-09 23:14:03 +0000133void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
134 llvm::Function *Fn) {
135 FunctionArgList Args;
Eli Friedman769e7302008-08-25 21:31:01 +0000136 if (FD->getNumParams()) {
137 const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
138 assert(FProto && "Function def must have prototype!");
Daniel Dunbar96816832008-09-09 23:14:03 +0000139
140 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i)
141 Args.push_back(std::make_pair(FD->getParamDecl(i),
142 FProto->getArgType(i)));
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000143 }
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000144
Daniel Dunbar54968bf2008-10-18 18:22:23 +0000145 StartFunction(FD, FD->getResultType(), Fn, Args,
146 cast<CompoundStmt>(FD->getBody())->getLBracLoc());
Daniel Dunbar96816832008-09-09 23:14:03 +0000147
Daniel Dunbar6b57d432008-08-26 08:29:31 +0000148 EmitStmt(FD->getBody());
149
150 const CompoundStmt *S = dyn_cast<CompoundStmt>(FD->getBody());
151 if (S) {
152 FinishFunction(S->getRBracLoc());
153 } else {
154 FinishFunction();
155 }
Chris Lattner8c7c6a12008-06-17 18:05:57 +0000156}
157
Devang Patel97299362007-09-28 21:49:18 +0000158/// isDummyBlock - Return true if BB is an empty basic block
159/// with no predecessors.
160bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
Chris Lattnerdad85512008-07-25 23:40:10 +0000161 if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
Devang Patel97299362007-09-28 21:49:18 +0000162 return true;
163 return false;
164}
165
Devang Patel7a78e432007-11-01 19:11:01 +0000166/// getCGRecordLayout - Return record layout info.
167const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
Chris Lattner7b2543e2008-02-05 06:55:31 +0000168 QualType Ty) {
169 const RecordType *RTy = Ty->getAsRecordType();
170 assert (RTy && "Unexpected type. RecordType expected here.");
Devang Patelaebd83f2007-10-23 02:10:49 +0000171
Chris Lattner7b2543e2008-02-05 06:55:31 +0000172 return CGT.getCGRecordLayout(RTy->getDecl());
Devang Patelaebd83f2007-10-23 02:10:49 +0000173}
Chris Lattner9d4e6202007-12-02 01:43:38 +0000174
Daniel Dunbar9503b782008-08-16 00:56:44 +0000175/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner9d4e6202007-12-02 01:43:38 +0000176/// specified stmt yet.
Daniel Dunbar49bddf72008-09-04 03:43:08 +0000177void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
178 bool OmitOnError) {
179 CGM.ErrorUnsupported(S, Type, OmitOnError);
Chris Lattner9d4e6202007-12-02 01:43:38 +0000180}
181
Daniel Dunbar879788d2008-08-04 16:51:22 +0000182unsigned CodeGenFunction::GetIDForAddrOfLabel(const LabelStmt *L) {
183 // Use LabelIDs.size() as the new ID if one hasn't been assigned.
184 return LabelIDs.insert(std::make_pair(L, LabelIDs.size())).first->second;
185}
186
Anders Carlsson82b0d0c2008-08-30 19:51:14 +0000187void CodeGenFunction::EmitMemSetToZero(llvm::Value *DestPtr, QualType Ty)
188{
189 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
190 if (DestPtr->getType() != BP)
191 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp");
192
193 // Get size and alignment info for this aggregate.
194 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
195
196 // FIXME: Handle variable sized types.
197 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
198
199 Builder.CreateCall4(CGM.getMemSetFn(), DestPtr,
200 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty),
201 // TypeInfo.first describes size in bits.
202 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8),
203 llvm::ConstantInt::get(llvm::Type::Int32Ty,
204 TypeInfo.second/8));
205}
206
Daniel Dunbar879788d2008-08-04 16:51:22 +0000207void CodeGenFunction::EmitIndirectSwitches() {
208 llvm::BasicBlock *Default;
209
Daniel Dunbar8ccfa802008-08-04 17:24:44 +0000210 if (IndirectSwitches.empty())
211 return;
212
Daniel Dunbar879788d2008-08-04 16:51:22 +0000213 if (!LabelIDs.empty()) {
214 Default = getBasicBlockForLabel(LabelIDs.begin()->first);
215 } else {
216 // No possible targets for indirect goto, just emit an infinite
217 // loop.
Daniel Dunbar72f96552008-11-11 02:29:29 +0000218 Default = createBasicBlock("indirectgoto.loop", CurFn);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000219 llvm::BranchInst::Create(Default, Default);
220 }
221
222 for (std::vector<llvm::SwitchInst*>::iterator i = IndirectSwitches.begin(),
223 e = IndirectSwitches.end(); i != e; ++i) {
224 llvm::SwitchInst *I = *i;
225
226 I->setSuccessor(0, Default);
227 for (std::map<const LabelStmt*,unsigned>::iterator LI = LabelIDs.begin(),
228 LE = LabelIDs.end(); LI != LE; ++LI) {
229 I->addCase(llvm::ConstantInt::get(llvm::Type::Int32Ty,
230 LI->second),
231 getBasicBlockForLabel(LI->first));
232 }
233 }
234}
Anders Carlsson285611e2008-11-04 05:30:00 +0000235
236llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty)
237{
238 // FIXME: This entire method is hardcoded for 32-bit X86.
239
240 const char *TargetPrefix = getContext().Target.getTargetPrefix();
241
242 if (strcmp(TargetPrefix, "x86") != 0 ||
243 getContext().Target.getPointerWidth(0) != 32)
244 return 0;
245
246 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
247 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
248
249 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
250 "ap");
251 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
252 llvm::Value *AddrTyped =
253 Builder.CreateBitCast(Addr,
254 llvm::PointerType::getUnqual(ConvertType(Ty)));
255
256 uint64_t SizeInBytes = getContext().getTypeSize(Ty) / 8;
257 const unsigned ArgumentSizeInBytes = 4;
258 if (SizeInBytes < ArgumentSizeInBytes)
259 SizeInBytes = ArgumentSizeInBytes;
260
261 llvm::Value *NextAddr =
262 Builder.CreateGEP(Addr,
263 llvm::ConstantInt::get(llvm::Type::Int32Ty, SizeInBytes),
264 "ap.next");
265 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
266
267 return AddrTyped;
268}
269