1 //===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
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 //===----------------------------------------------------------------------===//
10 /// This file is just a split of the code that logically belongs in opt.cpp but
11 /// that includes the new pass manager headers.
13 //===----------------------------------------------------------------------===//
15 #include "NewPMDriver.h"
16 #include "PassPrinters.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/CGSCCPassManager.h"
21 #include "llvm/Bitcode/BitcodeWriterPass.h"
22 #include "llvm/Config/llvm-config.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IRPrintingPasses.h"
25 #include "llvm/IR/LLVMContext.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/PassManager.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Passes/PassBuilder.h"
30 #include "llvm/Passes/PassPlugin.h"
31 #include "llvm/Passes/StandardInstrumentations.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/ToolOutputFile.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
37 #include "llvm/Transforms/Scalar/LoopPassManager.h"
38 #include "llvm/Transforms/Utils/Debugify.h"
41 using namespace opt_tool;
44 DebugPM("debug-pass-manager", cl::Hidden,
45 cl::desc("Print pass management debugging information"));
47 static cl::list<std::string>
48 PassPlugins("load-pass-plugin",
49 cl::desc("Load passes from plugin library"));
51 // This flag specifies a textual description of the alias analysis pipeline to
52 // use when querying for aliasing information. It only works in concert with
53 // the "passes" flag above.
54 static cl::opt<std::string>
55 AAPipeline("aa-pipeline",
56 cl::desc("A textual description of the alias analysis "
57 "pipeline for handling managed aliasing queries"),
60 /// {{@ These options accept textual pipeline descriptions which will be
61 /// inserted into default pipelines at the respective extension points
62 static cl::opt<std::string> PeepholeEPPipeline(
64 cl::desc("A textual description of the function pass pipeline inserted at "
65 "the Peephole extension points into default pipelines"),
67 static cl::opt<std::string> LateLoopOptimizationsEPPipeline(
68 "passes-ep-late-loop-optimizations",
70 "A textual description of the loop pass pipeline inserted at "
71 "the LateLoopOptimizations extension point into default pipelines"),
73 static cl::opt<std::string> LoopOptimizerEndEPPipeline(
74 "passes-ep-loop-optimizer-end",
75 cl::desc("A textual description of the loop pass pipeline inserted at "
76 "the LoopOptimizerEnd extension point into default pipelines"),
78 static cl::opt<std::string> ScalarOptimizerLateEPPipeline(
79 "passes-ep-scalar-optimizer-late",
80 cl::desc("A textual description of the function pass pipeline inserted at "
81 "the ScalarOptimizerLate extension point into default pipelines"),
83 static cl::opt<std::string> CGSCCOptimizerLateEPPipeline(
84 "passes-ep-cgscc-optimizer-late",
85 cl::desc("A textual description of the cgscc pass pipeline inserted at "
86 "the CGSCCOptimizerLate extension point into default pipelines"),
88 static cl::opt<std::string> VectorizerStartEPPipeline(
89 "passes-ep-vectorizer-start",
90 cl::desc("A textual description of the function pass pipeline inserted at "
91 "the VectorizerStart extension point into default pipelines"),
93 static cl::opt<std::string> PipelineStartEPPipeline(
94 "passes-ep-pipeline-start",
95 cl::desc("A textual description of the function pass pipeline inserted at "
96 "the PipelineStart extension point into default pipelines"),
98 static cl::opt<std::string> OptimizerLastEPPipeline(
99 "passes-ep-optimizer-last",
100 cl::desc("A textual description of the function pass pipeline inserted at "
101 "the OptimizerLast extension point into default pipelines"),
104 // Individual pipeline tuning options.
105 extern cl::opt<bool> DisableLoopUnrolling;
107 extern cl::opt<PGOKind> PGOKindFlag;
108 extern cl::opt<std::string> ProfileFile;
109 extern cl::opt<CSPGOKind> CSPGOKindFlag;
110 extern cl::opt<std::string> CSProfileGenFile;
112 static cl::opt<std::string>
113 ProfileRemappingFile("profile-remapping-file",
114 cl::desc("Path to the profile remapping file."),
116 static cl::opt<bool> DebugInfoForProfiling(
117 "new-pm-debug-info-for-profiling", cl::init(false), cl::Hidden,
118 cl::desc("Emit special debug info to enable PGO profile generation."));
121 template <typename PassManagerT>
122 bool tryParsePipelineText(PassBuilder &PB,
123 const cl::opt<std::string> &PipelineOpt) {
124 if (PipelineOpt.empty())
127 // Verify the pipeline is parseable:
129 if (auto Err = PB.parsePassPipeline(PM, PipelineOpt)) {
130 errs() << "Could not parse -" << PipelineOpt.ArgStr
131 << " pipeline: " << toString(std::move(Err))
132 << "... I'm going to ignore it.\n";
138 /// If one of the EPPipeline command line options was given, register callbacks
139 /// for parsing and inserting the given pipeline
140 static void registerEPCallbacks(PassBuilder &PB, bool VerifyEachPass,
142 if (tryParsePipelineText<FunctionPassManager>(PB, PeepholeEPPipeline))
143 PB.registerPeepholeEPCallback(
144 [&PB, VerifyEachPass, DebugLogging](
145 FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) {
146 ExitOnError Err("Unable to parse PeepholeEP pipeline: ");
147 Err(PB.parsePassPipeline(PM, PeepholeEPPipeline, VerifyEachPass,
150 if (tryParsePipelineText<LoopPassManager>(PB,
151 LateLoopOptimizationsEPPipeline))
152 PB.registerLateLoopOptimizationsEPCallback(
153 [&PB, VerifyEachPass, DebugLogging](
154 LoopPassManager &PM, PassBuilder::OptimizationLevel Level) {
155 ExitOnError Err("Unable to parse LateLoopOptimizationsEP pipeline: ");
156 Err(PB.parsePassPipeline(PM, LateLoopOptimizationsEPPipeline,
157 VerifyEachPass, DebugLogging));
159 if (tryParsePipelineText<LoopPassManager>(PB, LoopOptimizerEndEPPipeline))
160 PB.registerLoopOptimizerEndEPCallback(
161 [&PB, VerifyEachPass, DebugLogging](
162 LoopPassManager &PM, PassBuilder::OptimizationLevel Level) {
163 ExitOnError Err("Unable to parse LoopOptimizerEndEP pipeline: ");
164 Err(PB.parsePassPipeline(PM, LoopOptimizerEndEPPipeline,
165 VerifyEachPass, DebugLogging));
167 if (tryParsePipelineText<FunctionPassManager>(PB,
168 ScalarOptimizerLateEPPipeline))
169 PB.registerScalarOptimizerLateEPCallback(
170 [&PB, VerifyEachPass, DebugLogging](
171 FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) {
172 ExitOnError Err("Unable to parse ScalarOptimizerLateEP pipeline: ");
173 Err(PB.parsePassPipeline(PM, ScalarOptimizerLateEPPipeline,
174 VerifyEachPass, DebugLogging));
176 if (tryParsePipelineText<CGSCCPassManager>(PB, CGSCCOptimizerLateEPPipeline))
177 PB.registerCGSCCOptimizerLateEPCallback(
178 [&PB, VerifyEachPass, DebugLogging](
179 CGSCCPassManager &PM, PassBuilder::OptimizationLevel Level) {
180 ExitOnError Err("Unable to parse CGSCCOptimizerLateEP pipeline: ");
181 Err(PB.parsePassPipeline(PM, CGSCCOptimizerLateEPPipeline,
182 VerifyEachPass, DebugLogging));
184 if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerStartEPPipeline))
185 PB.registerVectorizerStartEPCallback(
186 [&PB, VerifyEachPass, DebugLogging](
187 FunctionPassManager &PM, PassBuilder::OptimizationLevel Level) {
188 ExitOnError Err("Unable to parse VectorizerStartEP pipeline: ");
189 Err(PB.parsePassPipeline(PM, VectorizerStartEPPipeline,
190 VerifyEachPass, DebugLogging));
192 if (tryParsePipelineText<ModulePassManager>(PB, PipelineStartEPPipeline))
193 PB.registerPipelineStartEPCallback(
194 [&PB, VerifyEachPass, DebugLogging](ModulePassManager &PM) {
195 ExitOnError Err("Unable to parse PipelineStartEP pipeline: ");
196 Err(PB.parsePassPipeline(PM, PipelineStartEPPipeline, VerifyEachPass,
199 if (tryParsePipelineText<FunctionPassManager>(PB, OptimizerLastEPPipeline))
200 PB.registerOptimizerLastEPCallback(
201 [&PB, VerifyEachPass, DebugLogging](ModulePassManager &PM,
202 PassBuilder::OptimizationLevel) {
203 ExitOnError Err("Unable to parse OptimizerLastEP pipeline: ");
204 Err(PB.parsePassPipeline(PM, OptimizerLastEPPipeline, VerifyEachPass,
209 #define HANDLE_EXTENSION(Ext) \
210 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
211 #include "llvm/Support/Extension.def"
213 bool llvm::runPassPipeline(StringRef Arg0, Module &M, TargetMachine *TM,
214 ToolOutputFile *Out, ToolOutputFile *ThinLTOLinkOut,
215 ToolOutputFile *OptRemarkFile,
216 StringRef PassPipeline, ArrayRef<StringRef> Passes,
217 OutputKind OK, VerifierKind VK,
218 bool ShouldPreserveAssemblyUseListOrder,
219 bool ShouldPreserveBitcodeUseListOrder,
220 bool EmitSummaryIndex, bool EmitModuleHash,
221 bool EnableDebugify, bool Coroutines) {
222 bool VerifyEachPass = VK == VK_VerifyEachPass;
224 Optional<PGOOptions> P;
225 switch (PGOKindFlag) {
227 P = PGOOptions(ProfileFile, "", "", PGOOptions::IRInstr);
230 P = PGOOptions(ProfileFile, "", ProfileRemappingFile, PGOOptions::IRUse);
233 P = PGOOptions(ProfileFile, "", ProfileRemappingFile,
234 PGOOptions::SampleUse);
237 if (DebugInfoForProfiling)
238 P = PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
243 if (CSPGOKindFlag != NoCSPGO) {
244 if (P && (P->Action == PGOOptions::IRInstr ||
245 P->Action == PGOOptions::SampleUse))
246 errs() << "CSPGOKind cannot be used with IRInstr or SampleUse";
247 if (CSPGOKindFlag == CSInstrGen) {
248 if (CSProfileGenFile.empty())
249 errs() << "CSInstrGen needs to specify CSProfileGenFile";
251 P->CSAction = PGOOptions::CSIRInstr;
252 P->CSProfileGenFile = CSProfileGenFile;
254 P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile,
255 PGOOptions::NoAction, PGOOptions::CSIRInstr);
256 } else /* CSPGOKindFlag == CSInstrUse */ {
258 errs() << "CSInstrUse needs to be together with InstrUse";
259 P->CSAction = PGOOptions::CSIRUse;
262 PassInstrumentationCallbacks PIC;
263 StandardInstrumentations SI;
264 SI.registerCallbacks(PIC);
266 PipelineTuningOptions PTO;
267 // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized
268 // to false above so we shouldn't necessarily need to check whether or not the
269 // option has been enabled.
270 PTO.LoopUnrolling = !DisableLoopUnrolling;
271 PTO.Coroutines = Coroutines;
272 PassBuilder PB(TM, PTO, P, &PIC);
273 registerEPCallbacks(PB, VerifyEachPass, DebugPM);
275 // Load requested pass plugins and let them register pass builder callbacks
276 for (auto &PluginFN : PassPlugins) {
277 auto PassPlugin = PassPlugin::Load(PluginFN);
279 errs() << "Failed to load passes from '" << PluginFN
280 << "'. Request ignored.\n";
284 PassPlugin->registerPassBuilderCallbacks(PB);
287 // Register a callback that creates the debugify passes as needed.
288 PB.registerPipelineParsingCallback(
289 [](StringRef Name, ModulePassManager &MPM,
290 ArrayRef<PassBuilder::PipelineElement>) {
291 if (Name == "debugify") {
292 MPM.addPass(NewPMDebugifyPass());
294 } else if (Name == "check-debugify") {
295 MPM.addPass(NewPMCheckDebugifyPass());
301 #define HANDLE_EXTENSION(Ext) \
302 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
303 #include "llvm/Support/Extension.def"
305 // Specially handle the alias analysis manager so that we can register
306 // a custom pipeline of AA passes with it.
308 if (!AAPipeline.empty()) {
309 assert(Passes.empty() &&
310 "--aa-pipeline and -foo-pass should not both be specified");
311 if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) {
312 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
316 // For compatibility with legacy pass manager.
317 // Alias analyses are not specially specified when using the legacy PM.
318 SmallVector<StringRef, 4> NonAAPasses;
319 for (auto PassName : Passes) {
320 if (PB.isAAPassName(PassName)) {
321 if (auto Err = PB.parseAAPipeline(AA, PassName)) {
322 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
326 NonAAPasses.push_back(PassName);
330 LoopAnalysisManager LAM(DebugPM);
331 FunctionAnalysisManager FAM(DebugPM);
332 CGSCCAnalysisManager CGAM(DebugPM);
333 ModuleAnalysisManager MAM(DebugPM);
335 // Register the AA manager first so that our version is the one used.
336 FAM.registerPass([&] { return std::move(AA); });
338 // Register all the basic analyses with the managers.
339 PB.registerModuleAnalyses(MAM);
340 PB.registerCGSCCAnalyses(CGAM);
341 PB.registerFunctionAnalyses(FAM);
342 PB.registerLoopAnalyses(LAM);
343 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
345 ModulePassManager MPM(DebugPM);
346 if (VK > VK_NoVerifier)
347 MPM.addPass(VerifierPass());
349 MPM.addPass(NewPMDebugifyPass());
351 if (!PassPipeline.empty()) {
352 assert(Passes.empty() &&
353 "PassPipeline and Passes should not both contain passes");
355 PB.parsePassPipeline(MPM, PassPipeline, VerifyEachPass, DebugPM)) {
356 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
360 for (auto PassName : NonAAPasses) {
361 std::string ModifiedPassName(PassName.begin(), PassName.end());
362 if (PB.isAnalysisPassName(PassName))
363 ModifiedPassName = "require<" + ModifiedPassName + ">";
364 if (auto Err = PB.parsePassPipeline(MPM, ModifiedPassName, VerifyEachPass,
366 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
371 if (VK > VK_NoVerifier)
372 MPM.addPass(VerifierPass());
374 MPM.addPass(NewPMCheckDebugifyPass());
376 // Add any relevant output pass at the end of the pipeline.
379 break; // No output pass needed.
380 case OK_OutputAssembly:
382 PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder));
384 case OK_OutputBitcode:
385 MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
386 EmitSummaryIndex, EmitModuleHash));
388 case OK_OutputThinLTOBitcode:
389 MPM.addPass(ThinLTOBitcodeWriterPass(
390 Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
394 // Before executing passes, print the final values of the LLVM options.
395 cl::PrintOptionValues();
397 // Now that we have all of the passes ready, run them.
401 if (OK != OK_NoOutput) {
403 if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut)
404 ThinLTOLinkOut->keep();
408 OptRemarkFile->keep();