1 //===--- CodeGenFunction.cpp - Emit LLVM Code from ASTs for a Function ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-function state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGDebugInfo.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Support/CFG.h"
22 using namespace clang;
23 using namespace CodeGen;
24 
25 CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
26   : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
27     CaseRangeBlock(NULL) {
28     LLVMIntTy = ConvertType(getContext().IntTy);
29     LLVMPointerWidth = Target.getPointerWidth(0);
30 }
31 
32 ASTContext &CodeGenFunction::getContext() const {
33   return CGM.getContext();
34 }
35 
36 
37 llvm::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.
42   return BB = llvm::BasicBlock::Create(S->getName());
43 }
44 
45 llvm::Constant *
46 CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
47   return cast<llvm::Constant>(LocalDeclMap[BVD]);
48 }
49 
50 llvm::Value *CodeGenFunction::GetAddrOfLocalVar(const VarDecl *VD)
51 {
52   return LocalDeclMap[VD];
53 }
54 
55 const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
56   return CGM.getTypes().ConvertType(T);
57 }
58 
59 bool CodeGenFunction::isObjCPointerType(QualType T) {
60   // All Objective-C types are pointers.
61   return T->isObjCInterfaceType() ||
62     T->isObjCQualifiedInterfaceType() || T->isObjCQualifiedIdType();
63 }
64 
65 bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
66   return !isObjCPointerType(T) &&!T->isRealType() && !T->isPointerLikeType() &&
67     !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
68 }
69 
70 void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
71   // Finish emission of indirect switches.
72   EmitIndirectSwitches();
73 
74   // Emit debug descriptor for function end.
75   if (CGDebugInfo *DI = CGM.getDebugInfo()) {
76     DI->setLocation(EndLoc);
77     DI->EmitRegionEnd(CurFn, Builder);
78   }
79 
80   assert(BreakContinueStack.empty() &&
81          "mismatched push/pop in break/continue stack!");
82 
83   // 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);
86   EmitFunctionEpilog(FnRetTy, ReturnValue);
87 
88   // Remove the AllocaInsertPt instruction, which is just a convenience for us.
89   AllocaInsertPt->eraseFromParent();
90   AllocaInsertPt = 0;
91 
92   // Verify that the function is well formed.
93   if (verifyFunction(*CurFn, llvm::PrintMessageAction)) {
94     CurFn->dump();
95     assert(0 && "Function failed verification!");
96   }
97 }
98 
99 void CodeGenFunction::StartFunction(const Decl *D, QualType RetTy,
100                                     llvm::Function *Fn,
101                                     const FunctionArgList &Args) {
102   CurFuncDecl = D;
103   FnRetTy = RetTy;
104   CurFn = Fn;
105   assert(CurFn->isDeclaration() && "Function already has body?");
106 
107   llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
108 
109   // 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);
115 
116   ReturnBlock = llvm::BasicBlock::Create("return");
117   ReturnValue = 0;
118   if (!RetTy->isVoidType())
119     ReturnValue = CreateTempAlloca(ConvertType(RetTy), "retval");
120 
121   Builder.SetInsertPoint(EntryBB);
122 
123   // Emit subprogram debug descriptor.
124   // FIXME: The cast here is a huge hack.
125   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
126     if (CGDebugInfo *DI = CGM.getDebugInfo()) {
127       if (CompoundStmt* body = dyn_cast<CompoundStmt>(FD->getBody()))
128         DI->setLocation(body->getLBracLoc());
129       DI->EmitFunctionStart(FD, CurFn, Builder);
130     }
131   }
132 
133   EmitFunctionProlog(CurFn, FnRetTy, Args);
134 }
135 
136 void CodeGenFunction::GenerateCode(const FunctionDecl *FD,
137                                    llvm::Function *Fn) {
138   FunctionArgList Args;
139   if (FD->getNumParams()) {
140     const FunctionTypeProto* FProto = FD->getType()->getAsFunctionTypeProto();
141     assert(FProto && "Function def must have prototype!");
142 
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)));
146   }
147 
148   StartFunction(FD, FD->getResultType(), Fn, Args);
149 
150   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   }
158 }
159 
160 /// isDummyBlock - Return true if BB is an empty basic block
161 /// with no predecessors.
162 bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
163   if (BB->empty() && pred_begin(BB) == pred_end(BB) && !BB->hasName())
164     return true;
165   return false;
166 }
167 
168 /// StartBlock - Start new block named N. If insert block is a dummy block
169 /// then reuse it.
170 void CodeGenFunction::StartBlock(const char *N) {
171   llvm::BasicBlock *BB = Builder.GetInsertBlock();
172   if (!isDummyBlock(BB))
173     EmitBlock(llvm::BasicBlock::Create(N));
174   else
175     BB->setName(N);
176 }
177 
178 /// getCGRecordLayout - Return record layout info.
179 const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
180                                                          QualType Ty) {
181   const RecordType *RTy = Ty->getAsRecordType();
182   assert (RTy && "Unexpected type. RecordType expected here.");
183 
184   return CGT.getCGRecordLayout(RTy->getDecl());
185 }
186 
187 /// ErrorUnsupported - Print out an error that codegen doesn't support the
188 /// specified stmt yet.
189 void CodeGenFunction::ErrorUnsupported(const Stmt *S, const char *Type,
190                                        bool OmitOnError) {
191   CGM.ErrorUnsupported(S, Type, OmitOnError);
192 }
193 
194 unsigned 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 
199 void 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 
219 void CodeGenFunction::EmitIndirectSwitches() {
220   llvm::BasicBlock *Default;
221 
222   if (IndirectSwitches.empty())
223     return;
224 
225   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 }
247