How to save IR to a file and build it to an executable file?

白昼怎懂夜的黑 提交于 2020-08-22 12:52:50

问题


Now I use clang build my .c file to .s file. And I have used the llvm API modify the IR. However, now I can't save my modified IR to a file. I want to use "LLVMWriteBitcodeToFile", but I can't find the struct of "LLVMOpaqueModule"; I want to use "WriteBitcodeToFile", it always show me "type mismatch". And I also want to know how to build an IR file to a executable file.

Next are two methods I use to save a module:

1、First use WriteBitcodeToFile

bool unbuffered = false; 
llvm::raw_ostream ro(unbuffered); 
WriteBitcodeToFile(m, ro); 

2、Second use LLVMWriteBitcodeToFile

const char *Path = "hello2.s"; 
int ans = LLVMWriteBitcodeToFile(m, Path); 

note: m is a point of Module instance


回答1:


  1. For saving the IR into a file, see the answer to this question: writing module to .bc bitcode file
  2. For compiling IR to an object file, look at the llc tool and follow what its main function does.



回答2:


Check out these functions in llvm-c/TargetMachine.h:

/** Emits an asm or object file for the given module to the filename. This
  wraps several c++ only classes (among them a file stream). Returns any
  error in ErrorMessage. Use LLVMDisposeMessage to dispose the message. */
LLVMBool LLVMTargetMachineEmitToFile(LLVMTargetMachineRef T, LLVMModuleRef M,
  char *Filename, LLVMCodeGenFileType codegen, char **ErrorMessage);

/** Compile the LLVM IR stored in \p M and store the result in \p OutMemBuf. */
LLVMBool LLVMTargetMachineEmitToMemoryBuffer(LLVMTargetMachineRef T, LLVMModuleRef M,
  LLVMCodeGenFileType codegen, char** ErrorMessage, LLVMMemoryBufferRef *OutMemBuf);

See also How to generate machine code with llvm




回答3:


for writing llvm bitcode to file what I do is :

std::error_code EC;
llvm::raw_fd_ostream OS("module", EC, llvm::sys::fs::F_None);
WriteBitcodeToFile(pBiFModule, OS);
OS.flush();

and then disassemble using llvm-dis.



来源:https://stackoverflow.com/questions/13928250/how-to-save-ir-to-a-file-and-build-it-to-an-executable-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!