Debian Codegraph @

flang/tools/tco/tco.cpp

raw
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
40 using namespace llvm;
41
42 static cl::opt<std::string>
43 inputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
44
45 static cl::opt<std::string> outputFilename("o",
46 cl::desc("Specify output filename"),
47 cl::value_desc("filename"),
48 cl::init("-"));
49
50 static cl::opt<bool> emitFir("emit-fir",
51 cl::desc("Parse and pretty-print the input"),
52 cl::init(false));
53
54 static cl::opt<std::string> targetTriple("target",
55 cl::desc("specify a target triple"),
56 cl::init("native"));
57
58 static cl::opt<std::string>
59 targetCPU("target-cpu", cl::desc("specify a target CPU"), cl::init(""));
60
61 static cl::opt<std::string> tuneCPU("tune-cpu", cl::desc("specify a tune CPU"),
62 cl::init(""));
63
64 static cl::opt<std::string>
65 targetFeatures("target-features", cl::desc("specify the target features"),
66 cl::init(""));
67
68 static cl::opt<bool> codeGenLLVM(
69 "code-gen-llvm",
70 cl::desc("Run only CodeGen passes and translate FIR to LLVM IR"),
71 cl::init(false));
72
73 #include "flang/Tools/CLOptions.inc"
74
75 static void printModule(mlir::ModuleOp mod, raw_ostream &output) {
76 output << mod << '\n';
77 }
78
79 // compile a .fir file
80 static llvm::LogicalResult
81 compileFIR(const mlir::PassPipelineCLParser &passPipeline) {
82 // check that there is a file to load
83 ErrorOr<std::unique_ptr<MemoryBuffer>> fileOrErr =
84 MemoryBuffer::getFileOrSTDIN(inputFilename);
85
86 if (std::error_code EC = fileOrErr.getError()) {
87 errs() << "Could not open file: " << EC.message() << '\n';
88 return mlir::failure();
89 }
90
91 // load the file into a module
92 SourceMgr sourceMgr;
93 sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), SMLoc());
94 mlir::DialectRegistry registry;
95 fir::support::registerDialects(registry);
96 fir::support::addFIRExtensions(registry);
97 mlir::MLIRContext context(registry);
98 fir::support::loadDialects(context);
99 fir::support::registerLLVMTranslation(context);
100 auto owningRef = mlir::parseSourceFile<mlir::ModuleOp>(sourceMgr, &context);
101
102 if (!owningRef) {
103 errs() << "Error can't load file " << inputFilename << '\n';
104 return mlir::failure();
105 }
106 if (mlir::failed(owningRef->verifyInvariants())) {
107 errs() << "Error verifying FIR module\n";
108 return mlir::failure();
109 }
110
111 std::error_code ec;
112 ToolOutputFile out(outputFilename, ec, sys::fs::OF_None);
113
114 // run passes
115 fir::KindMapping kindMap{&context};
116 fir::setTargetTriple(*owningRef, targetTriple);
117 fir::setKindMapping(*owningRef, kindMap);
118 fir::setTargetCPU(*owningRef, targetCPU);
119 fir::setTuneCPU(*owningRef, tuneCPU);
120 fir::setTargetFeatures(*owningRef, targetFeatures);
121 // tco is a testing tool, so it will happily use the target independent
122 // data layout if none is on the module.
123 fir::support::setMLIRDataLayoutFromAttributes(*owningRef,
124 /*allowDefaultLayout=*/true);
125 mlir::PassManager pm((*owningRef)->getName(),
126 mlir::OpPassManager::Nesting::Implicit);
127 pm.enableVerifier(/*verifyPasses=*/true);
128 (void)mlir::applyPassManagerCLOptions(pm);
129 if (emitFir) {
130 // parse the input and pretty-print it back out
131 // -emit-fir intentionally disables all the passes
132 } else if (passPipeline.hasAnyOccurrences()) {
133 auto errorHandler = [&](const Twine &msg) {
134 mlir::emitError(mlir::UnknownLoc::get(pm.getContext())) << msg;
135 return mlir::failure();
136 };
137 if (mlir::failed(passPipeline.addToPipeline(pm, errorHandler)))
138 return mlir::failure();
139 } else {
140 MLIRToLLVMPassPipelineConfig config(llvm::OptimizationLevel::O2);
141 config.AliasAnalysis = true; // enabled when optimizing for speed
142 if (codeGenLLVM) {
143 // Run only CodeGen passes.
144 fir::createDefaultFIRCodeGenPassPipeline(pm, config);
145 } else {
146 // Run tco with O2 by default.
147 fir::registerDefaultInlinerPass(config);
148 fir::createMLIRToLLVMPassPipeline(pm, config);
149 }
150 fir::addLLVMDialectToLLVMPass(pm, out.os());
151 }
152
153 // run the pass manager
154 if (mlir::succeeded(pm.run(*owningRef))) {
155 // passes ran successfully, so keep the output
156 if ((emitFir || passPipeline.hasAnyOccurrences()) && !codeGenLLVM)
157 printModule(*owningRef, out.os());
158 out.keep();
159 return mlir::success();
160 }
161
162 // pass manager failed
163 printModule(*owningRef, errs());
164 errs() << "\n\nFAILED: " << inputFilename << '\n';
165 return mlir::failure();
166 }
167
168 int main(int argc, char **argv) {
169 // Disable the ExternalNameConversion pass by default until all the tests have
170 // been updated to pass with it enabled.
171 disableExternalNameConversion = true;
172
173 [[maybe_unused]] InitLLVM y(argc, argv);
174 fir::support::registerMLIRPassesForFortranTools();
175 fir::registerOptCodeGenPasses();
176 fir::registerOptTransformPasses();
177 mlir::registerMLIRContextCLOptions();
178 mlir::registerPassManagerCLOptions();
179 mlir::PassPipelineCLParser passPipe("", "Compiler passes to run");
180 cl::ParseCommandLineOptions(argc, argv, "Tilikum Crossing Optimizer\n");
181 return mlir::failed(compileFIR(passPipe));
182 }