1 //===- ConvertToLLVMIR.cpp - MLIR to LLVM IR conversion -------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements a translation between the MLIR LLVM dialect and LLVM IR. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "mlir/Target/LLVMIR.h" 14 15 #include "mlir/Dialect/OpenMP/OpenMPDialect.h" 16 #include "mlir/Target/LLVMIR/ModuleTranslation.h" 17 #include "mlir/Translation.h" 18 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/IR/Module.h" 21 #include "llvm/IR/Verifier.h" 22 #include "llvm/Support/ToolOutputFile.h" 23 24 using namespace mlir; 25 26 std::unique_ptr<llvm::Module> 27 mlir::translateModuleToLLVMIR(ModuleOp m, llvm::LLVMContext &llvmContext, 28 StringRef name) { 29 auto llvmModule = 30 LLVM::ModuleTranslation::translateModule<>(m, llvmContext, name); 31 if (!llvmModule) 32 emitError(m.getLoc(), "Fail to convert MLIR to LLVM IR"); 33 else if (verifyModule(*llvmModule)) 34 emitError(m.getLoc(), "LLVM IR fails to verify"); 35 return llvmModule; 36 } 37 38 namespace mlir { 39 void registerToLLVMIRTranslation() { 40 TranslateFromMLIRRegistration registration( 41 "mlir-to-llvmir", 42 [](ModuleOp module, raw_ostream &output) { 43 llvm::LLVMContext llvmContext; 44 auto llvmModule = LLVM::ModuleTranslation::translateModule<>( 45 module, llvmContext, "LLVMDialectModule"); 46 if (!llvmModule) 47 return failure(); 48 49 llvmModule->print(output, nullptr); 50 return success(); 51 }, 52 [](DialectRegistry ®istry) { 53 registry.insert<LLVM::LLVMDialect, omp::OpenMPDialect>(); 54 }); 55 } 56 } // namespace mlir 57