xref: /freebsd/contrib/llvm-project/llvm/tools/opt/NewPMDriver.cpp (revision 972a253a57b6f144b0e4a3e2080a2a0076ec55a0)
1 //===- NewPMDriver.cpp - Driver for opt with new PM -----------------------===//
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 /// \file
9 ///
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.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "NewPMDriver.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Analysis/CGSCCPassManager.h"
20 #include "llvm/Analysis/TargetLibraryInfo.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/ErrorHandling.h"
33 #include "llvm/Support/ToolOutputFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
36 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
37 #include "llvm/Transforms/Scalar/LoopPassManager.h"
38 #include "llvm/Transforms/Utils/Debugify.h"
39 
40 using namespace llvm;
41 using namespace opt_tool;
42 
43 namespace llvm {
44 cl::opt<bool> DebugifyEach(
45     "debugify-each",
46     cl::desc("Start each pass with debugify and end it with check-debugify"));
47 
48 cl::opt<std::string>
49     DebugifyExport("debugify-export",
50                    cl::desc("Export per-pass debugify statistics to this file"),
51                    cl::value_desc("filename"));
52 
53 cl::opt<bool> VerifyEachDebugInfoPreserve(
54     "verify-each-debuginfo-preserve",
55     cl::desc("Start each pass with collecting and end it with checking of "
56              "debug info preservation."));
57 
58 cl::opt<std::string>
59     VerifyDIPreserveExport("verify-di-preserve-export",
60                    cl::desc("Export debug info preservation failures into "
61                             "specified (JSON) file (should be abs path as we use"
62                             " append mode to insert new JSON objects)"),
63                    cl::value_desc("filename"), cl::init(""));
64 
65 } // namespace llvm
66 
67 enum class DebugLogging { None, Normal, Verbose, Quiet };
68 
69 static cl::opt<DebugLogging> DebugPM(
70     "debug-pass-manager", cl::Hidden, cl::ValueOptional,
71     cl::desc("Print pass management debugging information"),
72     cl::init(DebugLogging::None),
73     cl::values(
74         clEnumValN(DebugLogging::Normal, "", ""),
75         clEnumValN(DebugLogging::Quiet, "quiet",
76                    "Skip printing info about analyses"),
77         clEnumValN(
78             DebugLogging::Verbose, "verbose",
79             "Print extra information about adaptors and pass managers")));
80 
81 // This flag specifies a textual description of the alias analysis pipeline to
82 // use when querying for aliasing information. It only works in concert with
83 // the "passes" flag above.
84 static cl::opt<std::string>
85     AAPipeline("aa-pipeline",
86                cl::desc("A textual description of the alias analysis "
87                         "pipeline for handling managed aliasing queries"),
88                cl::Hidden, cl::init("default"));
89 
90 /// {{@ These options accept textual pipeline descriptions which will be
91 /// inserted into default pipelines at the respective extension points
92 static cl::opt<std::string> PeepholeEPPipeline(
93     "passes-ep-peephole",
94     cl::desc("A textual description of the function pass pipeline inserted at "
95              "the Peephole extension points into default pipelines"),
96     cl::Hidden);
97 static cl::opt<std::string> LateLoopOptimizationsEPPipeline(
98     "passes-ep-late-loop-optimizations",
99     cl::desc(
100         "A textual description of the loop pass pipeline inserted at "
101         "the LateLoopOptimizations extension point into default pipelines"),
102     cl::Hidden);
103 static cl::opt<std::string> LoopOptimizerEndEPPipeline(
104     "passes-ep-loop-optimizer-end",
105     cl::desc("A textual description of the loop pass pipeline inserted at "
106              "the LoopOptimizerEnd extension point into default pipelines"),
107     cl::Hidden);
108 static cl::opt<std::string> ScalarOptimizerLateEPPipeline(
109     "passes-ep-scalar-optimizer-late",
110     cl::desc("A textual description of the function pass pipeline inserted at "
111              "the ScalarOptimizerLate extension point into default pipelines"),
112     cl::Hidden);
113 static cl::opt<std::string> CGSCCOptimizerLateEPPipeline(
114     "passes-ep-cgscc-optimizer-late",
115     cl::desc("A textual description of the cgscc pass pipeline inserted at "
116              "the CGSCCOptimizerLate extension point into default pipelines"),
117     cl::Hidden);
118 static cl::opt<std::string> VectorizerStartEPPipeline(
119     "passes-ep-vectorizer-start",
120     cl::desc("A textual description of the function pass pipeline inserted at "
121              "the VectorizerStart extension point into default pipelines"),
122     cl::Hidden);
123 static cl::opt<std::string> PipelineStartEPPipeline(
124     "passes-ep-pipeline-start",
125     cl::desc("A textual description of the module pass pipeline inserted at "
126              "the PipelineStart extension point into default pipelines"),
127     cl::Hidden);
128 static cl::opt<std::string> PipelineEarlySimplificationEPPipeline(
129     "passes-ep-pipeline-early-simplification",
130     cl::desc("A textual description of the module pass pipeline inserted at "
131              "the EarlySimplification extension point into default pipelines"),
132     cl::Hidden);
133 static cl::opt<std::string> OptimizerEarlyEPPipeline(
134     "passes-ep-optimizer-early",
135     cl::desc("A textual description of the module pass pipeline inserted at "
136              "the OptimizerEarly extension point into default pipelines"),
137     cl::Hidden);
138 static cl::opt<std::string> OptimizerLastEPPipeline(
139     "passes-ep-optimizer-last",
140     cl::desc("A textual description of the module pass pipeline inserted at "
141              "the OptimizerLast extension point into default pipelines"),
142     cl::Hidden);
143 static cl::opt<std::string> FullLinkTimeOptimizationEarlyEPPipeline(
144     "passes-ep-full-link-time-optimization-early",
145     cl::desc("A textual description of the module pass pipeline inserted at "
146              "the FullLinkTimeOptimizationEarly extension point into default "
147              "pipelines"),
148     cl::Hidden);
149 static cl::opt<std::string> FullLinkTimeOptimizationLastEPPipeline(
150     "passes-ep-full-link-time-optimization-last",
151     cl::desc("A textual description of the module pass pipeline inserted at "
152              "the FullLinkTimeOptimizationLast extension point into default "
153              "pipelines"),
154     cl::Hidden);
155 
156 // Individual pipeline tuning options.
157 extern cl::opt<bool> DisableLoopUnrolling;
158 
159 namespace llvm {
160 extern cl::opt<PGOKind> PGOKindFlag;
161 extern cl::opt<std::string> ProfileFile;
162 extern cl::opt<CSPGOKind> CSPGOKindFlag;
163 extern cl::opt<std::string> CSProfileGenFile;
164 extern cl::opt<bool> DisableBasicAA;
165 extern cl::opt<bool> PrintPipelinePasses;
166 } // namespace llvm
167 
168 static cl::opt<std::string>
169     ProfileRemappingFile("profile-remapping-file",
170                          cl::desc("Path to the profile remapping file."),
171                          cl::Hidden);
172 static cl::opt<bool> DebugInfoForProfiling(
173     "new-pm-debug-info-for-profiling", cl::init(false), cl::Hidden,
174     cl::desc("Emit special debug info to enable PGO profile generation."));
175 static cl::opt<bool> PseudoProbeForProfiling(
176     "new-pm-pseudo-probe-for-profiling", cl::init(false), cl::Hidden,
177     cl::desc("Emit pseudo probes to enable PGO profile generation."));
178 /// @}}
179 
180 template <typename PassManagerT>
181 bool tryParsePipelineText(PassBuilder &PB,
182                           const cl::opt<std::string> &PipelineOpt) {
183   if (PipelineOpt.empty())
184     return false;
185 
186   // Verify the pipeline is parseable:
187   PassManagerT PM;
188   if (auto Err = PB.parsePassPipeline(PM, PipelineOpt)) {
189     errs() << "Could not parse -" << PipelineOpt.ArgStr
190            << " pipeline: " << toString(std::move(Err))
191            << "... I'm going to ignore it.\n";
192     return false;
193   }
194   return true;
195 }
196 
197 /// If one of the EPPipeline command line options was given, register callbacks
198 /// for parsing and inserting the given pipeline
199 static void registerEPCallbacks(PassBuilder &PB) {
200   if (tryParsePipelineText<FunctionPassManager>(PB, PeepholeEPPipeline))
201     PB.registerPeepholeEPCallback(
202         [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
203           ExitOnError Err("Unable to parse PeepholeEP pipeline: ");
204           Err(PB.parsePassPipeline(PM, PeepholeEPPipeline));
205         });
206   if (tryParsePipelineText<LoopPassManager>(PB,
207                                             LateLoopOptimizationsEPPipeline))
208     PB.registerLateLoopOptimizationsEPCallback(
209         [&PB](LoopPassManager &PM, OptimizationLevel Level) {
210           ExitOnError Err("Unable to parse LateLoopOptimizationsEP pipeline: ");
211           Err(PB.parsePassPipeline(PM, LateLoopOptimizationsEPPipeline));
212         });
213   if (tryParsePipelineText<LoopPassManager>(PB, LoopOptimizerEndEPPipeline))
214     PB.registerLoopOptimizerEndEPCallback(
215         [&PB](LoopPassManager &PM, OptimizationLevel Level) {
216           ExitOnError Err("Unable to parse LoopOptimizerEndEP pipeline: ");
217           Err(PB.parsePassPipeline(PM, LoopOptimizerEndEPPipeline));
218         });
219   if (tryParsePipelineText<FunctionPassManager>(PB,
220                                                 ScalarOptimizerLateEPPipeline))
221     PB.registerScalarOptimizerLateEPCallback(
222         [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
223           ExitOnError Err("Unable to parse ScalarOptimizerLateEP pipeline: ");
224           Err(PB.parsePassPipeline(PM, ScalarOptimizerLateEPPipeline));
225         });
226   if (tryParsePipelineText<CGSCCPassManager>(PB, CGSCCOptimizerLateEPPipeline))
227     PB.registerCGSCCOptimizerLateEPCallback(
228         [&PB](CGSCCPassManager &PM, OptimizationLevel Level) {
229           ExitOnError Err("Unable to parse CGSCCOptimizerLateEP pipeline: ");
230           Err(PB.parsePassPipeline(PM, CGSCCOptimizerLateEPPipeline));
231         });
232   if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerStartEPPipeline))
233     PB.registerVectorizerStartEPCallback(
234         [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
235           ExitOnError Err("Unable to parse VectorizerStartEP pipeline: ");
236           Err(PB.parsePassPipeline(PM, VectorizerStartEPPipeline));
237         });
238   if (tryParsePipelineText<ModulePassManager>(PB, PipelineStartEPPipeline))
239     PB.registerPipelineStartEPCallback(
240         [&PB](ModulePassManager &PM, OptimizationLevel) {
241           ExitOnError Err("Unable to parse PipelineStartEP pipeline: ");
242           Err(PB.parsePassPipeline(PM, PipelineStartEPPipeline));
243         });
244   if (tryParsePipelineText<ModulePassManager>(
245           PB, PipelineEarlySimplificationEPPipeline))
246     PB.registerPipelineEarlySimplificationEPCallback(
247         [&PB](ModulePassManager &PM, OptimizationLevel) {
248           ExitOnError Err("Unable to parse EarlySimplification pipeline: ");
249           Err(PB.parsePassPipeline(PM, PipelineEarlySimplificationEPPipeline));
250         });
251   if (tryParsePipelineText<ModulePassManager>(PB, OptimizerEarlyEPPipeline))
252     PB.registerOptimizerEarlyEPCallback(
253         [&PB](ModulePassManager &PM, OptimizationLevel) {
254           ExitOnError Err("Unable to parse OptimizerEarlyEP pipeline: ");
255           Err(PB.parsePassPipeline(PM, OptimizerEarlyEPPipeline));
256         });
257   if (tryParsePipelineText<ModulePassManager>(PB, OptimizerLastEPPipeline))
258     PB.registerOptimizerLastEPCallback(
259         [&PB](ModulePassManager &PM, OptimizationLevel) {
260           ExitOnError Err("Unable to parse OptimizerLastEP pipeline: ");
261           Err(PB.parsePassPipeline(PM, OptimizerLastEPPipeline));
262         });
263   if (tryParsePipelineText<ModulePassManager>(
264           PB, FullLinkTimeOptimizationEarlyEPPipeline))
265     PB.registerFullLinkTimeOptimizationEarlyEPCallback(
266         [&PB](ModulePassManager &PM, OptimizationLevel) {
267           ExitOnError Err(
268               "Unable to parse FullLinkTimeOptimizationEarlyEP pipeline: ");
269           Err(PB.parsePassPipeline(PM,
270                                    FullLinkTimeOptimizationEarlyEPPipeline));
271         });
272   if (tryParsePipelineText<ModulePassManager>(
273           PB, FullLinkTimeOptimizationLastEPPipeline))
274     PB.registerFullLinkTimeOptimizationLastEPCallback(
275         [&PB](ModulePassManager &PM, OptimizationLevel) {
276           ExitOnError Err(
277               "Unable to parse FullLinkTimeOptimizationLastEP pipeline: ");
278           Err(PB.parsePassPipeline(PM, FullLinkTimeOptimizationLastEPPipeline));
279         });
280 }
281 
282 #define HANDLE_EXTENSION(Ext)                                                  \
283   llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
284 #include "llvm/Support/Extension.def"
285 
286 bool llvm::runPassPipeline(StringRef Arg0, Module &M, TargetMachine *TM,
287                            TargetLibraryInfoImpl *TLII, ToolOutputFile *Out,
288                            ToolOutputFile *ThinLTOLinkOut,
289                            ToolOutputFile *OptRemarkFile,
290                            StringRef PassPipeline, ArrayRef<StringRef> Passes,
291                            ArrayRef<PassPlugin> PassPlugins,
292                            OutputKind OK, VerifierKind VK,
293                            bool ShouldPreserveAssemblyUseListOrder,
294                            bool ShouldPreserveBitcodeUseListOrder,
295                            bool EmitSummaryIndex, bool EmitModuleHash,
296                            bool EnableDebugify, bool VerifyDIPreserve) {
297   bool VerifyEachPass = VK == VK_VerifyEachPass;
298 
299   Optional<PGOOptions> P;
300   switch (PGOKindFlag) {
301   case InstrGen:
302     P = PGOOptions(ProfileFile, "", "", PGOOptions::IRInstr);
303     break;
304   case InstrUse:
305     P = PGOOptions(ProfileFile, "", ProfileRemappingFile, PGOOptions::IRUse);
306     break;
307   case SampleUse:
308     P = PGOOptions(ProfileFile, "", ProfileRemappingFile,
309                    PGOOptions::SampleUse);
310     break;
311   case NoPGO:
312     if (DebugInfoForProfiling || PseudoProbeForProfiling)
313       P = PGOOptions("", "", "", PGOOptions::NoAction, PGOOptions::NoCSAction,
314                      DebugInfoForProfiling, PseudoProbeForProfiling);
315     else
316       P = None;
317   }
318   if (CSPGOKindFlag != NoCSPGO) {
319     if (P && (P->Action == PGOOptions::IRInstr ||
320               P->Action == PGOOptions::SampleUse))
321       errs() << "CSPGOKind cannot be used with IRInstr or SampleUse";
322     if (CSPGOKindFlag == CSInstrGen) {
323       if (CSProfileGenFile.empty())
324         errs() << "CSInstrGen needs to specify CSProfileGenFile";
325       if (P) {
326         P->CSAction = PGOOptions::CSIRInstr;
327         P->CSProfileGenFile = CSProfileGenFile;
328       } else
329         P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile,
330                        PGOOptions::NoAction, PGOOptions::CSIRInstr);
331     } else /* CSPGOKindFlag == CSInstrUse */ {
332       if (!P)
333         errs() << "CSInstrUse needs to be together with InstrUse";
334       P->CSAction = PGOOptions::CSIRUse;
335     }
336   }
337   if (TM)
338     TM->setPGOOption(P);
339 
340   LoopAnalysisManager LAM;
341   FunctionAnalysisManager FAM;
342   CGSCCAnalysisManager CGAM;
343   ModuleAnalysisManager MAM;
344 
345   PassInstrumentationCallbacks PIC;
346   PrintPassOptions PrintPassOpts;
347   PrintPassOpts.Verbose = DebugPM == DebugLogging::Verbose;
348   PrintPassOpts.SkipAnalyses = DebugPM == DebugLogging::Quiet;
349   StandardInstrumentations SI(DebugPM != DebugLogging::None, VerifyEachPass,
350                               PrintPassOpts);
351   SI.registerCallbacks(PIC, &FAM);
352   DebugifyEachInstrumentation Debugify;
353   DebugifyStatsMap DIStatsMap;
354   DebugInfoPerPass DebugInfoBeforePass;
355   if (DebugifyEach) {
356     Debugify.setDIStatsMap(DIStatsMap);
357     Debugify.setDebugifyMode(DebugifyMode::SyntheticDebugInfo);
358     Debugify.registerCallbacks(PIC);
359   } else if (VerifyEachDebugInfoPreserve) {
360     Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
361     Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
362     Debugify.setOrigDIVerifyBugsReportFilePath(
363       VerifyDIPreserveExport);
364     Debugify.registerCallbacks(PIC);
365   }
366 
367   PipelineTuningOptions PTO;
368   // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized
369   // to false above so we shouldn't necessarily need to check whether or not the
370   // option has been enabled.
371   PTO.LoopUnrolling = !DisableLoopUnrolling;
372   PassBuilder PB(TM, PTO, P, &PIC);
373   registerEPCallbacks(PB);
374 
375   // For any loaded plugins, let them register pass builder callbacks.
376   for (auto &PassPlugin : PassPlugins)
377     PassPlugin.registerPassBuilderCallbacks(PB);
378 
379   PB.registerPipelineParsingCallback(
380       [](StringRef Name, ModulePassManager &MPM,
381          ArrayRef<PassBuilder::PipelineElement>) {
382         AddressSanitizerOptions Opts;
383         if (Name == "asan-pipeline") {
384           MPM.addPass(ModuleAddressSanitizerPass(Opts));
385           return true;
386         }
387         return false;
388       });
389 
390 #define HANDLE_EXTENSION(Ext)                                                  \
391   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
392 #include "llvm/Support/Extension.def"
393 
394   // Specially handle the alias analysis manager so that we can register
395   // a custom pipeline of AA passes with it.
396   AAManager AA;
397   if (Passes.empty()) {
398     if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) {
399       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
400       return false;
401     }
402   }
403 
404   // For compatibility with the legacy PM AA pipeline.
405   // AAResultsWrapperPass by default provides basic-aa in the legacy PM
406   // unless -disable-basic-aa is specified.
407   // TODO: remove this once tests implicitly requiring basic-aa use -passes= and
408   // -aa-pipeline=basic-aa.
409   if (!Passes.empty() && !DisableBasicAA) {
410     if (auto Err = PB.parseAAPipeline(AA, "basic-aa")) {
411       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
412       return false;
413     }
414   }
415 
416   // For compatibility with legacy pass manager.
417   // Alias analyses are not specially specified when using the legacy PM.
418   for (auto PassName : Passes) {
419     if (PB.isAAPassName(PassName)) {
420       if (auto Err = PB.parseAAPipeline(AA, PassName)) {
421         errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
422         return false;
423       }
424     }
425   }
426 
427   // Register the AA manager first so that our version is the one used.
428   FAM.registerPass([&] { return std::move(AA); });
429   // Register our TargetLibraryInfoImpl.
430   FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
431 
432   // Register all the basic analyses with the managers.
433   PB.registerModuleAnalyses(MAM);
434   PB.registerCGSCCAnalyses(CGAM);
435   PB.registerFunctionAnalyses(FAM);
436   PB.registerLoopAnalyses(LAM);
437   PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
438 
439   ModulePassManager MPM;
440   if (VK > VK_NoVerifier)
441     MPM.addPass(VerifierPass());
442   if (EnableDebugify)
443     MPM.addPass(NewPMDebugifyPass());
444   if (VerifyDIPreserve)
445     MPM.addPass(NewPMDebugifyPass(DebugifyMode::OriginalDebugInfo, "",
446                                   &DebugInfoBeforePass));
447 
448   // Add passes according to the -passes options.
449   if (!PassPipeline.empty()) {
450     assert(Passes.empty() &&
451            "PassPipeline and Passes should not both contain passes");
452     if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) {
453       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
454       return false;
455     }
456   }
457   // Add passes specified using the legacy PM syntax (i.e. not using
458   // -passes). This should be removed later when such support has been
459   // deprecated, i.e. when all lit tests running opt (and not using
460   // -enable-new-pm=0) have been updated to use -passes.
461   for (auto PassName : Passes) {
462     std::string ModifiedPassName(PassName.begin(), PassName.end());
463     if (PB.isAnalysisPassName(PassName))
464       ModifiedPassName = "require<" + ModifiedPassName + ">";
465     // FIXME: These translations are supposed to be removed when lit tests that
466     // use these names have been updated to use the -passes syntax (and when the
467     // support for using the old syntax to specify passes is considered as
468     // deprecated for the new PM).
469     if (ModifiedPassName == "early-cse-memssa")
470       ModifiedPassName = "early-cse<memssa>";
471     else if (ModifiedPassName == "post-inline-ee-instrument")
472       ModifiedPassName = "ee-instrument<post-inline>";
473     else if (ModifiedPassName == "loop-extract-single")
474       ModifiedPassName = "loop-extract<single>";
475     else if (ModifiedPassName == "lower-matrix-intrinsics-minimal")
476       ModifiedPassName = "lower-matrix-intrinsics<minimal>";
477     if (auto Err = PB.parsePassPipeline(MPM, ModifiedPassName)) {
478       errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
479       return false;
480     }
481   }
482 
483   if (VK > VK_NoVerifier)
484     MPM.addPass(VerifierPass());
485   if (EnableDebugify)
486     MPM.addPass(NewPMCheckDebugifyPass(false, "", &DIStatsMap));
487   if (VerifyDIPreserve)
488     MPM.addPass(NewPMCheckDebugifyPass(
489         false, "", nullptr, DebugifyMode::OriginalDebugInfo, &DebugInfoBeforePass,
490         VerifyDIPreserveExport));
491 
492   // Add any relevant output pass at the end of the pipeline.
493   switch (OK) {
494   case OK_NoOutput:
495     break; // No output pass needed.
496   case OK_OutputAssembly:
497     MPM.addPass(
498         PrintModulePass(Out->os(), "", ShouldPreserveAssemblyUseListOrder));
499     break;
500   case OK_OutputBitcode:
501     MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
502                                   EmitSummaryIndex, EmitModuleHash));
503     break;
504   case OK_OutputThinLTOBitcode:
505     MPM.addPass(ThinLTOBitcodeWriterPass(
506         Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
507     break;
508   }
509 
510   // Before executing passes, print the final values of the LLVM options.
511   cl::PrintOptionValues();
512 
513   // Print a textual, '-passes=' compatible, representation of pipeline if
514   // requested.
515   if (PrintPipelinePasses) {
516     MPM.printPipeline(outs(), [&PIC](StringRef ClassName) {
517       auto PassName = PIC.getPassNameForClassName(ClassName);
518       return PassName.empty() ? ClassName : PassName;
519     });
520     outs() << "\n";
521     return true;
522   }
523 
524   // Now that we have all of the passes ready, run them.
525   MPM.run(M, MAM);
526 
527   // Declare success.
528   if (OK != OK_NoOutput) {
529     Out->keep();
530     if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut)
531       ThinLTOLinkOut->keep();
532   }
533 
534   if (OptRemarkFile)
535     OptRemarkFile->keep();
536 
537   if (DebugifyEach && !DebugifyExport.empty())
538     exportDebugifyStats(DebugifyExport, Debugify.getDebugifyStatsMap());
539 
540   return true;
541 }
542 
543 void llvm::printPasses(raw_ostream &OS) {
544   PassBuilder PB;
545   PB.printPassNames(OS);
546 }
547