1 /*
2 * Copyright (c) 2021-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <iomanip>
17 #include "pass_manager.h"
18 #include "compiler_logger.h"
19 #include "trace/trace.h"
20
21 #include "optimizer/ir/graph.h"
22 #include "optimizer/ir/graph_checker.h"
23 #include "optimizer/ir/visualizer_printer.h"
24
25 #include "optimizer/analysis/alias_analysis.h"
26 #include "optimizer/analysis/bounds_analysis.h"
27 #include "optimizer/analysis/catch_inputs.h"
28 #include "optimizer/analysis/dominators_tree.h"
29 #include "optimizer/analysis/linear_order.h"
30 #include "optimizer/analysis/liveness_analyzer.h"
31 #include "optimizer/analysis/live_registers.h"
32 #include "optimizer/analysis/loop_analyzer.h"
33 #include "optimizer/analysis/monitor_analysis.h"
34 #include "optimizer/analysis/object_type_propagation.h"
35 #include "optimizer/analysis/reg_alloc_verifier.h"
36 #include "optimizer/analysis/rpo.h"
37 #include "optimizer/analysis/types_analysis.h"
38 #include "optimizer/optimizations/cleanup.h"
39
40 // NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
41 #define ENABLE_IR_DUMP
42
43 #ifdef ENABLE_IR_DUMP
44
45 #include <fstream>
46 #include <ctime>
47 #include "os/filesystem.h"
48 #endif // ENABLE_IR_DUMP
49
50 namespace panda::compiler {
PassManager(Graph * graph,PassManager * parentPm)51 PassManager::PassManager(Graph *graph, PassManager *parentPm)
52 : graph_(graph),
53 optimizations_(graph->GetAllocator()->Adapter()),
54 analyses_(details::PredefinedAnalyses::Instantiate<Analysis *>(graph_->GetAllocator(), graph_)),
55 stats_((parentPm == nullptr) ? graph->GetAllocator()->New<PassManagerStatistics>(graph)
56 : parentPm->GetStatistics())
57 {
58 }
59
60 #ifdef ENABLE_IR_DUMP
ClearFileName(std::string str,std::string_view suffix)61 static std::string ClearFileName(std::string str, std::string_view suffix)
62 {
63 std::string delimiters = "~`@#$%^&*()-+=\\|/\"<>;,.[]";
64 for (const char &c : delimiters) {
65 std::replace(str.begin(), str.end(), c, '_');
66 }
67 return str.substr(0, NAME_MAX - suffix.size());
68 }
69 #endif
70
GetFileName(const char * passName,const std::string & suffix)71 std::string PassManager::GetFileName([[maybe_unused]] const char *passName, [[maybe_unused]] const std::string &suffix)
72 {
73 #ifdef ENABLE_IR_DUMP
74 std::stringstream ssFilename;
75 std::stringstream ssFullpath;
76 ASSERT(GetGraph()->GetRuntime() != nullptr);
77
78 std::string folderName(g_options.GetCompilerDumpFolder());
79
80 os::CreateDirectories(folderName);
81 constexpr auto IMM_3 = 3;
82 constexpr auto IMM_4 = 4;
83 ssFilename << std::setw(IMM_3) << std::setfill('0') << executionCounter_ << "_";
84 if (passName != nullptr) {
85 ssFilename << "pass_" << std::setw(IMM_4) << std::setfill('0') << stats_->GetCurrentPassIndex() << "_";
86 }
87 if (GetGraph()->GetParentGraph() != nullptr) {
88 ssFilename << "inlined_";
89 }
90 ssFilename << GetGraph()->GetRuntime()->GetClassNameFromMethod(GetGraph()->GetMethod()) << "_"
91 << GetGraph()->GetRuntime()->GetMethodName(GetGraph()->GetMethod());
92 if (GetGraph()->IsOsrMode()) {
93 ssFilename << "_OSR";
94 }
95 if (passName != nullptr) {
96 ssFilename << "_" << passName;
97 }
98 ssFullpath << folderName.c_str() << "/" << ClearFileName(ssFilename.str(), suffix) << suffix;
99 return ssFullpath.str();
100 #else
101 return "";
102 #endif // ENABLE_IR_DUMP
103 }
DumpGraph(const char * passName)104 void PassManager::DumpGraph([[maybe_unused]] const char *passName)
105 {
106 #ifdef ENABLE_IR_DUMP
107 std::ofstream strm(GetFileName(passName, ".ir"));
108 if (!strm.is_open()) {
109 std::cerr << errno << " ERROR: " << strerror(errno) << "\n" << GetFileName(passName, ".ir") << std::endl;
110 }
111 ASSERT(strm.is_open());
112 GetGraph()->Dump(&strm);
113 #endif // ENABLE_IR_DUMP
114 }
DumpLifeIntervals(const char * passName)115 void PassManager::DumpLifeIntervals([[maybe_unused]] const char *passName)
116 {
117 #ifdef ENABLE_IR_DUMP
118 if (!GetGraph()->IsAnalysisValid<LivenessAnalyzer>()) {
119 return;
120 }
121 std::ofstream strm(GetFileName(passName, ".li"));
122 if (!strm.is_open()) {
123 std::cerr << errno << " ERROR: " << strerror(errno) << "\n" << GetFileName(passName, ".li") << std::endl;
124 }
125
126 ASSERT(strm.is_open());
127 GetGraph()->GetAnalysis<LivenessAnalyzer>().DumpLifeIntervals(strm);
128 #endif // ENABLE_IR_DUMP
129 }
InitialDumpVisualizerGraph()130 void PassManager::InitialDumpVisualizerGraph()
131 {
132 #ifdef ENABLE_IR_DUMP
133 std::ofstream strm(GetFileName());
134 strm << "begin_compilation\n";
135 strm << " name \"" << GetGraph()->GetRuntime()->GetClassNameFromMethod(GetGraph()->GetMethod()) << "_"
136 << GetGraph()->GetRuntime()->GetMethodName(GetGraph()->GetMethod()) << "\"\n";
137 strm << " method \"" << GetGraph()->GetRuntime()->GetClassNameFromMethod(GetGraph()->GetMethod()) << "_"
138 << GetGraph()->GetRuntime()->GetMethodName(GetGraph()->GetMethod()) << "\"\n";
139 strm << " date " << std::time(nullptr) << "\n";
140 strm << "end_compilation\n";
141 strm.close();
142 #endif // ENABLE_IR_DUMP
143 }
144
DumpVisualizerGraph(const char * passName)145 void PassManager::DumpVisualizerGraph([[maybe_unused]] const char *passName)
146 {
147 #ifdef ENABLE_IR_DUMP
148 std::ofstream strm(GetFileName(), std::ios::app);
149 VisualizerPrinter(GetGraph(), &strm, passName).Print();
150 strm.close();
151 #endif // ENABLE_IR_DUMP
152 }
153
RunPass(Pass * pass,size_t localMemSizeBeforePass)154 bool PassManager::RunPass(Pass *pass, size_t localMemSizeBeforePass)
155 {
156 if (pass->IsAnalysis() && pass->IsValid()) {
157 return true;
158 }
159
160 if (!pass->IsAnalysis() && !static_cast<Optimization *>(pass)->IsEnable()) {
161 return false;
162 }
163
164 if (!IsCheckMode()) {
165 stats_->ProcessBeforeRun(*pass);
166 if (firstExecution_ && GetGraph()->GetParentGraph() == nullptr) {
167 StartExecution();
168 firstExecution_ = false;
169 }
170 }
171
172 #ifndef NDEBUG
173 if (g_options.IsCompilerEnableTracing()) {
174 trace::BeginTracePoint(pass->GetPassName());
175 }
176 #endif // NDEBUG
177
178 bool result = pass->Run();
179
180 #ifndef NDEBUG
181 if (g_options.IsCompilerEnableTracing()) {
182 trace::EndTracePoint();
183 }
184 #endif // NDEBUG
185
186 if (!IsCheckMode()) {
187 ASSERT(graph_->GetLocalAllocator()->GetAllocatedSize() >= localMemSizeBeforePass);
188 stats_->ProcessAfterRun(graph_->GetLocalAllocator()->GetAllocatedSize() - localMemSizeBeforePass);
189 }
190
191 if (pass->IsAnalysis()) {
192 pass->SetValid(result);
193 }
194 bool isCodegen = std::string("Codegen") == pass->GetPassName();
195 if (g_options.IsCompilerDump() && pass->ShouldDump() && !IsCheckMode()) {
196 if (!g_options.IsCompilerDumpFinal() || isCodegen) {
197 DumpGraph(pass->GetPassName());
198 }
199 }
200
201 if (g_options.IsCompilerVisualizerDump() && pass->ShouldDump()) {
202 DumpVisualizerGraph(pass->GetPassName());
203 }
204
205 #ifndef NDEBUG
206 RunPassChecker(pass, result, isCodegen);
207 #endif
208 return result;
209 }
210
RunPassChecker(Pass * pass,bool result,bool isCodegen)211 void PassManager::RunPassChecker(Pass *pass, bool result, bool isCodegen)
212 {
213 bool checkerEnabled = g_options.IsCompilerCheckGraph();
214 if (g_options.IsCompilerCheckFinal()) {
215 checkerEnabled = isCodegen;
216 }
217 if (result && !pass->IsAnalysis() && checkerEnabled) {
218 GraphChecker(graph_, pass->GetPassName()).Check();
219 }
220 }
221
GetAllocator()222 ArenaAllocator *PassManager::GetAllocator()
223 {
224 return graph_->GetAllocator();
225 }
226
GetLocalAllocator()227 ArenaAllocator *PassManager::GetLocalAllocator()
228 {
229 return graph_->GetLocalAllocator();
230 }
231
Finalize() const232 void PassManager::Finalize() const
233 {
234 if (g_options.IsCompilerPrintStats()) {
235 stats_->PrintStatistics();
236 }
237 if (g_options.WasSetCompilerDumpStatsCsv()) {
238 stats_->DumpStatisticsCsv();
239 }
240 }
241 } // namespace panda::compiler
242