1//===- tco.cpp - Tilikum Crossing Opt ---------------------------*- C++ -*-===//
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 is to be like LLVM's opt program, only for FIR. Such a program is
10// required for roundtrip testing, etc.
11//
12//===----------------------------------------------------------------------===//
13
14#include "flang/Optimizer/CodeGen/CodeGen.h"
15#include "flang/Optimizer/Dialect/Support/FIRContext.h"
16#include "flang/Optimizer/Dialect/Support/KindMapping.h"
17#include "flang/Optimizer/Support/DataLayout.h"
18#include "flang/Optimizer/Support/InitFIR.h"
19#include "flang/Optimizer/Support/InternalNames.h"
20#include "flang/Optimizer/Transforms/Passes.h"
21#include "flang/Tools/CrossToolHelpers.h"
22#include "mlir/IR/AsmState.h"
23#include "mlir/IR/BuiltinOps.h"
24#include "mlir/IR/MLIRContext.h"
25#include "mlir/Parser/Parser.h"
26#include "mlir/Pass/Pass.h"
27#include "mlir/Pass/PassManager.h"
28#include "mlir/Transforms/Passes.h"
29#include "llvm/Passes/OptimizationLevel.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/ErrorOr.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/InitLLVM.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/SourceMgr.h"
36#include "llvm/Support/TargetSelect.h"
37#include "llvm/Support/ToolOutputFile.h"
38#include "llvm/Support/raw_ostream.h"
39
40using namespace llvm;
41
42static cl::opt<std::string>
43 inputFilename(cl::Positional, cl::desc("<input file>"), cl::init(Val: "-"));
44
45static cl::opt<std::string> outputFilename("o",
46 cl::desc("Specify output filename"),
47 cl::value_desc("filename"),
48 cl::init(Val: "-"));
49
50static cl::opt<bool> emitFir("emit-fir",
51 cl::desc("Parse and pretty-print the input"),
52 cl::init(Val: false));
53
54static cl::opt<std::string> targetTriple("target",
55 cl::desc("specify a target triple"),
56 cl::init(Val: "native"));
57
58static cl::opt<std::string>
59 targetCPU("target-cpu", cl::desc("specify a target CPU"), cl::init(Val: ""));
60
61static cl::opt<std::string> tuneCPU("tune-cpu", cl::desc("specify a tune CPU"),
62 cl::init(Val: ""));
63
64static cl::opt<std::string>
65 targetFeatures("target-features", cl::desc("specify the target features"),
66 cl::init(Val: ""));
67
68static cl::opt<bool> codeGenLLVM(
69 "code-gen-llvm",
70 cl::desc("Run only CodeGen passes and translate FIR to LLVM IR"),
71 cl::init(Val: false));
72
73static cl::opt<bool> emitFinalMLIR(
74 "emit-final-mlir",
75 cl::desc("Only translate FIR to MLIR, do not lower to LLVM IR"),
76 cl::init(Val: false));
77
78static cl::opt<bool>
79 simplifyMLIR("simplify-mlir",
80 cl::desc("Run CSE and canonicalization on MLIR output"),
81 cl::init(Val: false));
82
83// Enabled by default to accurately reflect -O2
84static cl::opt<bool> enableAliasAnalysis("enable-aa",
85 cl::desc("Enable FIR alias analysis"),
86 cl::init(Val: true));
87
88static cl::opt<bool> testGeneratorMode(
89 "test-gen", cl::desc("-emit-final-mlir -simplify-mlir -enable-aa=false"),
90 cl::init(Val: false));
91
92#include "flang/Optimizer/Passes/CommandLineOpts.h"
93#include "flang/Optimizer/Passes/Pipelines.h"
94
95static void printModule(mlir::ModuleOp mod, raw_ostream &output) {
96 output << mod << '\n';
97}
98
99// compile a .fir file
100static llvm::LogicalResult
101compileFIR(const mlir::PassPipelineCLParser &passPipeline) {
102 // check that there is a file to load
103 ErrorOr<std::unique_ptr<MemoryBuffer>> fileOrErr =
104 MemoryBuffer::getFileOrSTDIN(Filename: inputFilename);
105
106 if (std::error_code EC = fileOrErr.getError()) {
107 errs() << "Could not open file: " << EC.message() << '\n';
108 return mlir::failure();
109 }
110
111 // load the file into a module
112 SourceMgr sourceMgr;
113 sourceMgr.AddNewSourceBuffer(F: std::move(*fileOrErr), IncludeLoc: SMLoc());
114 mlir::DialectRegistry registry;
115 fir::support::registerDialects(registry);
116 fir::support::addFIRExtensions(registry);
117 mlir::MLIRContext context(registry);
118 fir::support::loadDialects(context);
119 fir::support::registerLLVMTranslation(context);
120 auto owningRef = mlir::parseSourceFile<mlir::ModuleOp>(sourceMgr, &context);
121
122 if (!owningRef) {
123 errs() << "Error can't load file " << inputFilename << '\n';
124 return mlir::failure();
125 }
126 if (mlir::failed(owningRef->verifyInvariants())) {
127 errs() << "Error verifying FIR module\n";
128 return mlir::failure();
129 }
130
131 std::error_code ec;
132 ToolOutputFile out(outputFilename, ec, sys::fs::OF_None);
133
134 // run passes
135 fir::KindMapping kindMap{&context};
136 fir::setTargetTriple(*owningRef, targetTriple);
137 fir::setKindMapping(*owningRef, kindMap);
138 fir::setTargetCPU(*owningRef, targetCPU);
139 fir::setTuneCPU(*owningRef, tuneCPU);
140 fir::setTargetFeatures(*owningRef, targetFeatures);
141 // tco is a testing tool, so it will happily use the target independent
142 // data layout if none is on the module.
143 fir::support::setMLIRDataLayoutFromAttributes(*owningRef,
144 /*allowDefaultLayout=*/true);
145 mlir::PassManager pm((*owningRef)->getName(),
146 mlir::OpPassManager::Nesting::Implicit);
147 pm.enableVerifier(/*verifyPasses=*/true);
148 (void)mlir::applyPassManagerCLOptions(pm);
149 if (emitFir) {
150 // parse the input and pretty-print it back out
151 // -emit-fir intentionally disables all the passes
152 } else if (passPipeline.hasAnyOccurrences()) {
153 auto errorHandler = [&](const Twine &msg) {
154 mlir::emitError(mlir::UnknownLoc::get(pm.getContext())) << msg;
155 return mlir::failure();
156 };
157 if (mlir::failed(passPipeline.addToPipeline(pm, errorHandler)))
158 return mlir::failure();
159 } else {
160 MLIRToLLVMPassPipelineConfig config(llvm::OptimizationLevel::O2);
161 config.EnableOpenMP = true; // assume the input contains OpenMP
162 config.AliasAnalysis = enableAliasAnalysis && !testGeneratorMode;
163 if (codeGenLLVM) {
164 // Run only CodeGen passes.
165 fir::createDefaultFIRCodeGenPassPipeline(pm, config);
166 } else {
167 // Run tco with O2 by default.
168 fir::registerDefaultInlinerPass(config);
169 fir::createMLIRToLLVMPassPipeline(pm, config);
170 }
171 if (simplifyMLIR || testGeneratorMode) {
172 pm.addPass(mlir::createCanonicalizerPass());
173 pm.addPass(mlir::createCSEPass());
174 }
175 if (!emitFinalMLIR && !testGeneratorMode)
176 fir::addLLVMDialectToLLVMPass(pm, out.os());
177 }
178
179 // run the pass manager
180 if (mlir::succeeded(pm.run(*owningRef))) {
181 // passes ran successfully, so keep the output
182 if ((emitFir || passPipeline.hasAnyOccurrences() || emitFinalMLIR ||
183 testGeneratorMode) &&
184 !codeGenLLVM)
185 printModule(*owningRef, out.os());
186 out.keep();
187 return mlir::success();
188 }
189
190 // pass manager failed
191 printModule(*owningRef, errs());
192 errs() << "\n\nFAILED: " << inputFilename << '\n';
193 return mlir::failure();
194}
195
196int main(int argc, char **argv) {
197 // Disable the ExternalNameConversion pass by default until all the tests have
198 // been updated to pass with it enabled.
199 disableExternalNameConversion = true;
200
201 [[maybe_unused]] InitLLVM y(argc, argv);
202 fir::support::registerMLIRPassesForFortranTools();
203 fir::registerOptCodeGenPasses();
204 fir::registerOptTransformPasses();
205 mlir::registerMLIRContextCLOptions();
206 mlir::registerPassManagerCLOptions();
207 mlir::PassPipelineCLParser passPipe("", "Compiler passes to run");
208 cl::ParseCommandLineOptions(argc, argv, Overview: "Tilikum Crossing Optimizer\n");
209 return mlir::failed(compileFIR(passPipe));
210}
211

source code of flang/tools/tco/tco.cpp