22#include "llvm/Bitcode/BitcodeWriter.h"
23#include "llvm/IR/LegacyPassManager.h"
24#include "llvm/IRReader/IRReader.h"
25#include "llvm/Linker/Linker.h"
26#include "llvm/MC/TargetRegistry.h"
27#include "llvm/Support/FileSystem.h"
28#include "llvm/Support/MemoryBuffer.h"
29#include "llvm/Support/SourceMgr.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/Target/TargetMachine.h"
32#include "llvm/Transforms/IPO/Internalize.h"
53std::optional<llvm::TargetMachine *>
56 return targetMachine.get();
59 llvm::Triple parsedTriple(
triple);
60 const llvm::Target *
target =
61 llvm::TargetRegistry::lookupTarget(parsedTriple, error);
64 <<
"Failed to lookup target for triple '" <<
triple <<
"' " << error;
73 return targetMachine.get();
76std::unique_ptr<llvm::Module>
78 llvm::SMDiagnostic error;
79 std::unique_ptr<llvm::Module> library =
80 llvm::getLazyIRFileModule(path, error, context);
83 <<
", error: " << error.getMessage();
94 SmallVector<std::unique_ptr<llvm::Module>> &llvmModules,
95 bool failureOnError) {
96 for (
Attribute linkLib : librariesToLink) {
100 if (
auto filePath = dyn_cast<StringAttr>(linkLib)) {
102 if (!llvm::sys::fs::is_regular_file(filePath.strref())) {
104 <<
"File path: " << filePath <<
" does not exist or is not a file.";
109 llvmModules.push_back(std::move(bcFile));
110 else if (failureOnError)
114 if (
auto blobAttr = dyn_cast<BlobAttr>(linkLib)) {
116 llvm::SMDiagnostic error;
118 std::unique_ptr<llvm::MemoryBuffer> buffer =
119 llvm::MemoryBuffer::getMemBuffer(StringRef(data.data(), data.size()),
122 std::unique_ptr<llvm::Module> mod =
123 getLazyIRModule(std::move(buffer), error, context);
127 llvmModules.push_back(std::move(mod));
128 }
else if (failureOnError) {
130 <<
"Couldn't load LLVM library for linking: " << error.getMessage();
135 if (failureOnError) {
137 <<
"Unknown attribute describing LLVM library to load: " << linkLib;
144std::unique_ptr<llvm::Module>
151 SmallVector<std::unique_ptr<llvm::Module>> &&libs) {
154 llvm::Linker linker(
module);
155 for (std::unique_ptr<llvm::Module> &libModule : libs) {
162 bool err = linker.linkInModule(
163 std::move(libModule), llvm::Linker::Flags::LinkOnlyNeeded,
165 llvm::internalizeModule(m, [&gvs](
const llvm::GlobalValue &gv) {
166 return !gv.hasName() || (gvs.count(gv.getName()) == 0);
184 <<
"Invalid optimization level: " <<
optLevel <<
".";
186 std::optional<llvm::TargetMachine *> targetMachine =
190 <<
"Target Machine unavailable for triple " <<
triple
191 <<
", can't optimize with LLVM\n";
192 (*targetMachine)->setOptLevel(
static_cast<llvm::CodeGenOptLevel
>(
optLevel));
196 auto error = transformer(&
module);
199 llvm::handleAllErrors(
200 std::move(error), [&mlirError](
const llvm::ErrorInfoBase &ei) {
201 mlirError <<
"Could not optimize LLVM IR: " << ei.message() <<
"\n";
208std::optional<std::string>
210 llvm::TargetMachine &targetMachine) {
211 std::string targetISA;
212 llvm::raw_string_ostream stream(targetISA);
215 llvm::buffer_ostream pstream(stream);
216 llvm::legacy::PassManager codegenPasses;
218 if (targetMachine.addPassesToEmitFile(codegenPasses, pstream,
nullptr,
219 llvm::CodeGenFileType::AssemblyFile))
222 codegenPasses.run(llvmModule);
229 std::optional<llvm::TargetMachine *> targetMachine =
233 module.setDataLayout((*targetMachine)->createDataLayout());
234 module.setTargetTriple((*targetMachine)->getTargetTriple());
238std::optional<SmallVector<char, 0>>
242 llvm::raw_svector_ostream outputStream(binaryData);
243 llvm::WriteBitcodeToFile(llvmModule, outputStream);
249 llvm::LLVMContext llvmContext;
267 if (failed(
linkFiles(*llvmModule, std::move(*libs))))
Attributes are known-constant values of operations.
This class represents a diagnostic that is inflight and set to be reported.
LogicalResult loadBitcodeFilesFromList(llvm::LLVMContext &context, ArrayRef< Attribute > librariesToLink, SmallVector< std::unique_ptr< llvm::Module > > &llvmModules, bool failureOnError=true)
Loads multiple bitcode files.
StringRef features
Target features.
std::unique_ptr< llvm::Module > translateToLLVMIR(llvm::LLVMContext &llvmContext)
Translates the operation to LLVM IR.
virtual std::optional< SmallVector< char, 0 > > run()
Runs the serialization pipeline, returning std::nullopt on error.
static std::optional< std::string > translateToISA(llvm::Module &llvmModule, llvm::TargetMachine &targetMachine)
Utility function for translating to ISA, returns std::nullopt on failure.
function_ref< void(llvm::Module &)> initialLlvmIRCallback
Callback invoked with the initial LLVM IR for the device module.
function_ref< void(llvm::Module &)> optimizedLlvmIRCallback
Callback invoked with LLVM IR for the device module after LLVM optimizations but before codegen.
virtual std::optional< SmallVector< char, 0 > > moduleToObject(llvm::Module &llvmModule)
Serializes the LLVM IR bitcode to an object file, by default it serializes to LLVM bitcode.
virtual void setDataLayoutAndTriple(llvm::Module &module)
Hook for computing the Datalayout.
virtual void handleModulePreLink(llvm::Module &module)
Hook for performing additional actions on the llvmModule pre linking.
StringRef triple
Target triple.
int optLevel
Optimization level.
virtual LogicalResult handleBitcodeFile(llvm::Module &module)
Hook for performing additional actions on a loaded bitcode file.
std::optional< llvm::TargetMachine * > getOrCreateTargetMachine()
Create the target machine based on the target triple and chip.
Operation & getOperation()
Returns the operation being serialized.
LogicalResult linkFiles(llvm::Module &module, SmallVector< std::unique_ptr< llvm::Module > > &&libs)
Link the llvmModule to other bitcode file.
function_ref< void(StringRef)> isaCallback
Callback invoked with the target ISA for the device, for example PTX assembly.
virtual std::optional< SmallVector< std::unique_ptr< llvm::Module > > > loadBitcodeFiles(llvm::Module &module)
Hook for loading bitcode files, returns std::nullopt on failure.
virtual LogicalResult optimizeModule(llvm::Module &module, int optL)
Optimize the module.
virtual ~ModuleToObject()
function_ref< void(llvm::Module &)> linkedLlvmIRCallback
Callback invoked with LLVM IR for the device module after linking the device libraries.
StringRef chip
Target chip.
std::unique_ptr< llvm::Module > loadBitcodeFile(llvm::LLVMContext &context, StringRef path)
Loads a bitcode file from path.
virtual void handleModulePostLink(llvm::Module &module)
Hook for performing additional actions on the llvmModule post linking.
ModuleToObject(Operation &module, StringRef triple, StringRef chip, StringRef features={}, int optLevel=3, function_ref< void(llvm::Module &)> initialLlvmIRCallback={}, function_ref< void(llvm::Module &)> linkedLlvmIRCallback={}, function_ref< void(llvm::Module &)> optimizedLlvmIRCallback={}, function_ref< void(StringRef)> isaCallback={})
Operation & module
Module to transform to a binary object.
Operation is the basic unit of execution within MLIR.
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Include the generated interface declarations.
std::function< llvm::Error(llvm::Module *)> makeOptimizingTransformer(unsigned optLevel, unsigned sizeLevel, llvm::TargetMachine *targetMachine)
Create a module transformer function for MLIR ExecutionEngine that runs LLVM IR passes corresponding ...
std::unique_ptr< llvm::Module > translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext, llvm::StringRef name="LLVMDialectModule", bool disableVerification=false)
Translates a given LLVM dialect module into an LLVM IR module living in the given context.
llvm::StringSet< AllocatorTy > StringSet
llvm::function_ref< Fn > function_ref