CodeGenFunction.cpp 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/AST/AST.h"
  17. #include "llvm/CallingConv.h"
  18. #include "llvm/Constants.h"
  19. #include "llvm/DerivedTypes.h"
  20. #include "llvm/Function.h"
  21. #include "llvm/Analysis/Verifier.h"
  22. #include "llvm/Support/CFG.h"
  23. using namespace clang;
  24. using namespace CodeGen;
  25. CodeGenFunction::CodeGenFunction(CodeGenModule &cgm)
  26. : CGM(cgm), Target(CGM.getContext().Target), SwitchInsn(NULL),
  27. CaseRangeBlock(NULL) {}
  28. ASTContext &CodeGenFunction::getContext() const {
  29. return CGM.getContext();
  30. }
  31. llvm::BasicBlock *CodeGenFunction::getBasicBlockForLabel(const LabelStmt *S) {
  32. llvm::BasicBlock *&BB = LabelMap[S];
  33. if (BB) return BB;
  34. // Create, but don't insert, the new block.
  35. return BB = llvm::BasicBlock::Create(S->getName());
  36. }
  37. llvm::Constant *
  38. CodeGenFunction::GetAddrOfStaticLocalVar(const VarDecl *BVD) {
  39. return cast<llvm::Constant>(LocalDeclMap[BVD]);
  40. }
  41. const llvm::Type *CodeGenFunction::ConvertType(QualType T) {
  42. return CGM.getTypes().ConvertType(T);
  43. }
  44. bool CodeGenFunction::hasAggregateLLVMType(QualType T) {
  45. return !T->isRealType() && !T->isPointerLikeType() &&
  46. !T->isVoidType() && !T->isVectorType() && !T->isFunctionType();
  47. }
  48. /// Generate an Objective-C method. An Objective-C method is a C function with
  49. /// its pointer, name, and types registered in the class struture.
  50. // FIXME: This method contains a lot of code copied and pasted from
  51. // GenerateCode. This should be factored out.
  52. void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
  53. llvm::SmallVector<const llvm::Type *, 16> ParamTypes;
  54. for (unsigned i=0 ; i<OMD->param_size() ; i++) {
  55. ParamTypes.push_back(ConvertType(OMD->getParamDecl(i)->getType()));
  56. }
  57. CurFn =CGM.getObjCRuntime()->MethodPreamble(ConvertType(OMD->getResultType()),
  58. llvm::PointerType::getUnqual(llvm::Type::Int32Ty),
  59. ParamTypes.begin(),
  60. OMD->param_size(),
  61. OMD->isVariadic());
  62. llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
  63. // Create a marker to make it easy to insert allocas into the entryblock
  64. // later. Don't create this with the builder, because we don't want it
  65. // folded.
  66. llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
  67. AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
  68. EntryBB);
  69. FnRetTy = OMD->getResultType();
  70. Builder.SetInsertPoint(EntryBB);
  71. // Emit allocs for param decls. Give the LLVM Argument nodes names.
  72. llvm::Function::arg_iterator AI = CurFn->arg_begin();
  73. // Name the struct return argument.
  74. // FIXME: Probably should be in the runtime, or it will trample the other
  75. // hidden arguments.
  76. if (hasAggregateLLVMType(OMD->getResultType())) {
  77. AI->setName("agg.result");
  78. ++AI;
  79. }
  80. // Add implicit parameters to the decl map.
  81. // TODO: Add something to AST to let the runtime specify the names and types
  82. // of these.
  83. llvm::Value *&DMEntry = LocalDeclMap[&(*OMD->getSelfDecl())];
  84. const llvm::Type *SelfTy = AI->getType();
  85. llvm::Value *DeclPtr = new llvm::AllocaInst(SelfTy, 0, "self.addr",
  86. AllocaInsertPt);
  87. // Store the initial value into the alloca.
  88. Builder.CreateStore(AI, DeclPtr);
  89. DMEntry = DeclPtr;
  90. ++AI; ++AI;
  91. for (unsigned i = 0, e = OMD->getNumParams(); i != e; ++i, ++AI) {
  92. assert(AI != CurFn->arg_end() && "Argument mismatch!");
  93. EmitParmDecl(*OMD->getParamDecl(i), AI);
  94. }
  95. // Emit the function body.
  96. EmitStmt(OMD->getBody());
  97. // Emit a return for code that falls off the end. If insert point
  98. // is a dummy block with no predecessors then remove the block itself.
  99. llvm::BasicBlock *BB = Builder.GetInsertBlock();
  100. if (isDummyBlock(BB))
  101. BB->eraseFromParent();
  102. else {
  103. if (CurFn->getReturnType() == llvm::Type::VoidTy)
  104. Builder.CreateRetVoid();
  105. else
  106. Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
  107. }
  108. assert(BreakContinueStack.empty() &&
  109. "mismatched push/pop in break/continue stack!");
  110. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  111. AllocaInsertPt->eraseFromParent();
  112. AllocaInsertPt = 0;
  113. // Verify that the function is well formed.
  114. assert(!verifyFunction(*CurFn) && "Generated method is not well formed.");
  115. }
  116. llvm::Value *CodeGenFunction::LoadObjCSelf(void)
  117. {
  118. if(const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurFuncDecl)) {
  119. llvm::Value *SelfPtr = LocalDeclMap[&(*OMD->getSelfDecl())];
  120. return Builder.CreateLoad(SelfPtr, "self");
  121. }
  122. return NULL;
  123. }
  124. void CodeGenFunction::GenerateCode(const FunctionDecl *FD) {
  125. LLVMIntTy = ConvertType(getContext().IntTy);
  126. LLVMPointerWidth = static_cast<unsigned>(
  127. getContext().getTypeSize(getContext().getPointerType(getContext().VoidTy)));
  128. CurFuncDecl = FD;
  129. FnRetTy = FD->getType()->getAsFunctionType()->getResultType();
  130. CurFn = cast<llvm::Function>(CGM.GetAddrOfFunctionDecl(FD, true));
  131. assert(CurFn->isDeclaration() && "Function already has body?");
  132. // TODO: Set up linkage and many other things. Note, this is a simple
  133. // approximation of what we really want.
  134. if (FD->getAttr<DLLImportAttr>())
  135. CurFn->setLinkage(llvm::Function::DLLImportLinkage);
  136. else if (FD->getAttr<DLLExportAttr>())
  137. CurFn->setLinkage(llvm::Function::DLLExportLinkage);
  138. else if (FD->getAttr<WeakAttr>() || FD->isInline())
  139. CurFn->setLinkage(llvm::Function::WeakLinkage);
  140. else if (FD->getStorageClass() == FunctionDecl::Static)
  141. CurFn->setLinkage(llvm::Function::InternalLinkage);
  142. if (FD->getAttr<FastCallAttr>())
  143. CurFn->setCallingConv(llvm::CallingConv::Fast);
  144. if (const VisibilityAttr *attr = FD->getAttr<VisibilityAttr>())
  145. CurFn->setVisibility(attr->getVisibility());
  146. // FIXME: else handle -fvisibility
  147. unsigned FuncAttrs = 0;
  148. if (FD->getAttr<NoThrowAttr>())
  149. FuncAttrs |= llvm::ParamAttr::NoUnwind;
  150. if (FD->getAttr<NoReturnAttr>())
  151. FuncAttrs |= llvm::ParamAttr::NoReturn;
  152. if (FuncAttrs) {
  153. llvm::ParamAttrsWithIndex PAWI =
  154. llvm::ParamAttrsWithIndex::get(0, FuncAttrs);
  155. CurFn->setParamAttrs(llvm::PAListPtr::get(&PAWI, 1));
  156. }
  157. llvm::BasicBlock *EntryBB = llvm::BasicBlock::Create("entry", CurFn);
  158. // Create a marker to make it easy to insert allocas into the entryblock
  159. // later. Don't create this with the builder, because we don't want it
  160. // folded.
  161. llvm::Value *Undef = llvm::UndefValue::get(llvm::Type::Int32Ty);
  162. AllocaInsertPt = new llvm::BitCastInst(Undef, llvm::Type::Int32Ty, "allocapt",
  163. EntryBB);
  164. Builder.SetInsertPoint(EntryBB);
  165. // Emit allocs for param decls. Give the LLVM Argument nodes names.
  166. llvm::Function::arg_iterator AI = CurFn->arg_begin();
  167. // Name the struct return argument.
  168. if (hasAggregateLLVMType(FD->getResultType())) {
  169. AI->setName("agg.result");
  170. ++AI;
  171. }
  172. for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i, ++AI) {
  173. assert(AI != CurFn->arg_end() && "Argument mismatch!");
  174. EmitParmDecl(*FD->getParamDecl(i), AI);
  175. }
  176. // Emit the function body.
  177. EmitStmt(FD->getBody());
  178. // Emit a return for code that falls off the end. If insert point
  179. // is a dummy block with no predecessors then remove the block itself.
  180. llvm::BasicBlock *BB = Builder.GetInsertBlock();
  181. if (isDummyBlock(BB))
  182. BB->eraseFromParent();
  183. else {
  184. // FIXME: if this is C++ main, this should return 0.
  185. if (CurFn->getReturnType() == llvm::Type::VoidTy)
  186. Builder.CreateRetVoid();
  187. else
  188. Builder.CreateRet(llvm::UndefValue::get(CurFn->getReturnType()));
  189. }
  190. assert(BreakContinueStack.empty() &&
  191. "mismatched push/pop in break/continue stack!");
  192. // Remove the AllocaInsertPt instruction, which is just a convenience for us.
  193. AllocaInsertPt->eraseFromParent();
  194. AllocaInsertPt = 0;
  195. // Verify that the function is well formed.
  196. assert(!verifyFunction(*CurFn) && "Generated function is not well formed.");
  197. }
  198. /// isDummyBlock - Return true if BB is an empty basic block
  199. /// with no predecessors.
  200. bool CodeGenFunction::isDummyBlock(const llvm::BasicBlock *BB) {
  201. if (BB->empty() && pred_begin(BB) == pred_end(BB))
  202. return true;
  203. return false;
  204. }
  205. /// StartBlock - Start new block named N. If insert block is a dummy block
  206. /// then reuse it.
  207. void CodeGenFunction::StartBlock(const char *N) {
  208. llvm::BasicBlock *BB = Builder.GetInsertBlock();
  209. if (!isDummyBlock(BB))
  210. EmitBlock(llvm::BasicBlock::Create(N));
  211. else
  212. BB->setName(N);
  213. }
  214. /// getCGRecordLayout - Return record layout info.
  215. const CGRecordLayout *CodeGenFunction::getCGRecordLayout(CodeGenTypes &CGT,
  216. QualType Ty) {
  217. const RecordType *RTy = Ty->getAsRecordType();
  218. assert (RTy && "Unexpected type. RecordType expected here.");
  219. return CGT.getCGRecordLayout(RTy->getDecl());
  220. }
  221. /// WarnUnsupported - Print out a warning that codegen doesn't support the
  222. /// specified stmt yet.
  223. void CodeGenFunction::WarnUnsupported(const Stmt *S, const char *Type) {
  224. CGM.WarnUnsupported(S, Type);
  225. }