1 //===- mlir-reduce.cpp - The MLIR reducer ---------------------------------===// 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 the general framework of the MLIR reducer tool. It 10 // parses the command line arguments, parses the initial MLIR test case and sets 11 // up the testing environment. It outputs the most reduced test case variant 12 // after executing the reduction passes. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "mlir/Tools/mlir-reduce/MlirReduceMain.h" 17 #include "mlir/IR/PatternMatch.h" 18 #include "mlir/Parser.h" 19 #include "mlir/Pass/Pass.h" 20 #include "mlir/Pass/PassManager.h" 21 #include "mlir/Reducer/Passes.h" 22 #include "mlir/Rewrite/FrozenRewritePatternSet.h" 23 #include "mlir/Support/FileUtilities.h" 24 #include "mlir/Support/LogicalResult.h" 25 #include "llvm/Support/InitLLVM.h" 26 #include "llvm/Support/ToolOutputFile.h" 27 28 using namespace mlir; 29 30 // Parse and verify the input MLIR file. 31 static LogicalResult loadModule(MLIRContext &context, OwningModuleRef &module, 32 StringRef inputFilename) { 33 module = parseSourceFile(inputFilename, &context); 34 if (!module) 35 return failure(); 36 37 return success(); 38 } 39 40 LogicalResult mlir::mlirReduceMain(int argc, char **argv, 41 MLIRContext &context) { 42 static llvm::cl::opt<std::string> inputFilename( 43 llvm::cl::Positional, llvm::cl::Required, llvm::cl::desc("<input file>")); 44 45 static llvm::cl::opt<std::string> outputFilename( 46 "o", llvm::cl::desc("Output filename for the reduced test case"), 47 llvm::cl::init("-")); 48 49 llvm::InitLLVM y(argc, argv); 50 51 registerReducerPasses(); 52 registerMLIRContextCLOptions(); 53 registerPassManagerCLOptions(); 54 55 PassPipelineCLParser parser("", "Reduction Passes to Run"); 56 llvm::cl::ParseCommandLineOptions(argc, argv, 57 "MLIR test case reduction tool.\n"); 58 59 std::string errorMessage; 60 61 auto output = openOutputFile(outputFilename, &errorMessage); 62 if (!output) 63 return failure(); 64 65 mlir::OwningModuleRef moduleRef; 66 if (failed(loadModule(context, moduleRef, inputFilename))) 67 return failure(); 68 69 auto errorHandler = [&](const Twine &msg) { 70 return emitError(UnknownLoc::get(&context)) << msg; 71 }; 72 73 // Reduction pass pipeline. 74 PassManager pm(&context); 75 if (failed(parser.addToPipeline(pm, errorHandler))) 76 return failure(); 77 78 ModuleOp m = moduleRef.get().clone(); 79 80 if (failed(pm.run(m))) 81 return failure(); 82 83 m.print(output->os()); 84 output->keep(); 85 86 return success(); 87 } 88