1 //===- OptUtils.cpp - MLIR Execution Engine optimization pass utilities ---===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the utility functions to trigger LLVM optimizations from
10 // MLIR Execution Engine.
12 //===----------------------------------------------------------------------===//
14 #include "mlir/ExecutionEngine/OptUtils.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/IR/Module.h"
18 #include "llvm/Passes/OptimizationLevel.h"
19 #include "llvm/Passes/PassBuilder.h"
20 #include "llvm/Support/Error.h"
21 #include "llvm/Support/FormatVariadic.h"
22 #include "llvm/Target/TargetMachine.h"
27 static std::optional
<OptimizationLevel
> mapToLevel(unsigned optLevel
,
31 return OptimizationLevel::O0
;
34 return OptimizationLevel::O1
;
39 return OptimizationLevel::O2
;
42 return OptimizationLevel::Os
;
45 return OptimizationLevel::Oz
;
49 return OptimizationLevel::O3
;
53 // Create and return a lambda that uses LLVM pass manager builder to set up
54 // optimizations based on the given level.
55 std::function
<Error(Module
*)>
56 mlir::makeOptimizingTransformer(unsigned optLevel
, unsigned sizeLevel
,
57 TargetMachine
*targetMachine
) {
58 return [optLevel
, sizeLevel
, targetMachine
](Module
*m
) -> Error
{
59 std::optional
<OptimizationLevel
> ol
= mapToLevel(optLevel
, sizeLevel
);
61 return make_error
<StringError
>(
62 formatv("invalid optimization/size level {0}/{1}", optLevel
,
65 inconvertibleErrorCode());
67 LoopAnalysisManager lam
;
68 FunctionAnalysisManager fam
;
69 CGSCCAnalysisManager cgam
;
70 ModuleAnalysisManager mam
;
72 PipelineTuningOptions tuningOptions
;
73 tuningOptions
.LoopUnrolling
= true;
74 tuningOptions
.LoopInterleaving
= true;
75 tuningOptions
.LoopVectorization
= true;
76 tuningOptions
.SLPVectorization
= true;
78 PassBuilder
pb(targetMachine
, tuningOptions
);
80 pb
.registerModuleAnalyses(mam
);
81 pb
.registerCGSCCAnalyses(cgam
);
82 pb
.registerFunctionAnalyses(fam
);
83 pb
.registerLoopAnalyses(lam
);
84 pb
.crossRegisterProxies(lam
, fam
, cgam
, mam
);
86 ModulePassManager mpm
;
87 mpm
.addPass(pb
.buildPerModuleDefaultPipeline(*ol
));
89 return Error::success();