From dbe0d734b5687e0aa7da911684912163cea07bd2 Mon Sep 17 00:00:00 2001 From: "Tung D. Le" Date: Mon, 3 Aug 2020 12:46:21 +0900 Subject: [PATCH] Call LLVM opt to optimize bitcode (#245) * Call LLVM opt to optimize bitcode * Rename variables --- src/ExternalUtil.hpp.in | 1 + src/MainUtils.cpp | 22 +++++++++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/ExternalUtil.hpp.in b/src/ExternalUtil.hpp.in index 4d3662f..becf736 100644 --- a/src/ExternalUtil.hpp.in +++ b/src/ExternalUtil.hpp.in @@ -5,6 +5,7 @@ namespace onnx_mlir { std::string kExecPath = "@CMAKE_INSTALL_PREFIX@/bin/onnx-mlir"; /* fallback if not set by main */ const std::string kInstPath = "@CMAKE_INSTALL_PREFIX@"; +const std::string kOptPath = "@LLVM_PROJ_BUILD@/bin/opt"; const std::string kLlcPath = "@LLVM_PROJ_BUILD@/bin/llc"; const std::string kCxxPath = "@CMAKE_CXX_COMPILER@"; const std::string kLinkerPath = "@CMAKE_LINKER@"; diff --git a/src/MainUtils.cpp b/src/MainUtils.cpp index cf6a259..20816f5 100644 --- a/src/MainUtils.cpp +++ b/src/MainUtils.cpp @@ -250,16 +250,28 @@ void genConstPackObj(const mlir::OwningModuleRef &module, #endif } -// Write LLVM bitcode. -void genLLVMBitcode(const mlir::OwningModuleRef &module, string bitcodePath) { +// Write LLVM optimized bitcode. +void genLLVMBitcode(const mlir::OwningModuleRef &module, + string optimizedBitcodePath, string outputBaseName) { error_code error; + // Write bitcode to a file. + string unoptimizedBitcodePath = outputBaseName + ".unoptimized.bc"; + llvm::FileRemover unoptimzedBitcodeRemover(unoptimizedBitcodePath); + llvm::raw_fd_ostream moduleBitcodeStream( - bitcodePath, error, llvm::sys::fs::F_None); + unoptimizedBitcodePath, error, llvm::sys::fs::F_None); llvm::WriteBitcodeToFile( *mlir::translateModuleToLLVMIR(*module), moduleBitcodeStream); moduleBitcodeStream.flush(); + + // Use the LLVM's 'opt' command to optimize the bitcode. + Command optBitcode(/*exePath=*/kOptPath); + optBitcode.appendStr("-O3") + .appendList({"-o", optimizedBitcodePath}) + .appendStr(unoptimizedBitcodePath) + .exec(); } // Compile LLVM bitcode to object file. @@ -319,7 +331,7 @@ void compileModuleToSharedLibrary( llvm::FileRemover constPackObjRemover(constPackObjPath.getValue()); string bitcodePath = outputBaseName + ".bc"; - genLLVMBitcode(module, bitcodePath); + genLLVMBitcode(module, bitcodePath, outputBaseName); llvm::FileRemover bitcodeRemover(bitcodePath); string modelObjPath = outputBaseName + ".o"; @@ -340,7 +352,7 @@ void compileModuleToJniJar( llvm::FileRemover constPackObjRemover(constPackObjPath.getValue()); string bitcodePath = outputBaseName + ".bc"; - genLLVMBitcode(module, bitcodePath); + genLLVMBitcode(module, bitcodePath, outputBaseName); llvm::FileRemover bitcodeRemover(bitcodePath); string modelObjPath = outputBaseName + ".o";