[clang][bytecode][NFC] Only get expr when checking for UB (#125397)
[llvm-project.git] / llvm / tools / opt / NewPMDriver.cpp
blob5ed42b054316befd15f855b3c8fa184683c81d1b
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 //===----------------------------------------------------------------------===//
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/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/IR/PassManager.h"
27 #include "llvm/IR/Verifier.h"
28 #include "llvm/IRPrinter/IRPrintingPasses.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/Support/VirtualFileSystem.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
38 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
39 #include "llvm/Transforms/Scalar/LoopPassManager.h"
40 #include "llvm/Transforms/Utils/Debugify.h"
42 using namespace llvm;
43 using namespace opt_tool;
45 namespace llvm {
46 cl::opt<bool> DebugifyEach(
47 "debugify-each",
48 cl::desc("Start each pass with debugify and end it with check-debugify"));
50 cl::opt<std::string>
51 DebugifyExport("debugify-export",
52 cl::desc("Export per-pass debugify statistics to this file"),
53 cl::value_desc("filename"));
55 cl::opt<bool> VerifyEachDebugInfoPreserve(
56 "verify-each-debuginfo-preserve",
57 cl::desc("Start each pass with collecting and end it with checking of "
58 "debug info preservation."));
60 cl::opt<std::string>
61 VerifyDIPreserveExport("verify-di-preserve-export",
62 cl::desc("Export debug info preservation failures into "
63 "specified (JSON) file (should be abs path as we use"
64 " append mode to insert new JSON objects)"),
65 cl::value_desc("filename"), cl::init(""));
67 } // namespace llvm
69 enum class DebugLogging { None, Normal, Verbose, Quiet };
71 static cl::opt<DebugLogging> DebugPM(
72 "debug-pass-manager", cl::Hidden, cl::ValueOptional,
73 cl::desc("Print pass management debugging information"),
74 cl::init(DebugLogging::None),
75 cl::values(
76 clEnumValN(DebugLogging::Normal, "", ""),
77 clEnumValN(DebugLogging::Quiet, "quiet",
78 "Skip printing info about analyses"),
79 clEnumValN(
80 DebugLogging::Verbose, "verbose",
81 "Print extra information about adaptors and pass managers")));
83 // This flag specifies a textual description of the alias analysis pipeline to
84 // use when querying for aliasing information. It only works in concert with
85 // the "passes" flag above.
86 static cl::opt<std::string>
87 AAPipeline("aa-pipeline",
88 cl::desc("A textual description of the alias analysis "
89 "pipeline for handling managed aliasing queries"),
90 cl::Hidden, cl::init("default"));
92 /// {{@ These options accept textual pipeline descriptions which will be
93 /// inserted into default pipelines at the respective extension points
94 static cl::opt<std::string> PeepholeEPPipeline(
95 "passes-ep-peephole",
96 cl::desc("A textual description of the function pass pipeline inserted at "
97 "the Peephole extension points into default pipelines"),
98 cl::Hidden);
99 static cl::opt<std::string> LateLoopOptimizationsEPPipeline(
100 "passes-ep-late-loop-optimizations",
101 cl::desc(
102 "A textual description of the loop pass pipeline inserted at "
103 "the LateLoopOptimizations extension point into default pipelines"),
104 cl::Hidden);
105 static cl::opt<std::string> LoopOptimizerEndEPPipeline(
106 "passes-ep-loop-optimizer-end",
107 cl::desc("A textual description of the loop pass pipeline inserted at "
108 "the LoopOptimizerEnd extension point into default pipelines"),
109 cl::Hidden);
110 static cl::opt<std::string> ScalarOptimizerLateEPPipeline(
111 "passes-ep-scalar-optimizer-late",
112 cl::desc("A textual description of the function pass pipeline inserted at "
113 "the ScalarOptimizerLate extension point into default pipelines"),
114 cl::Hidden);
115 static cl::opt<std::string> CGSCCOptimizerLateEPPipeline(
116 "passes-ep-cgscc-optimizer-late",
117 cl::desc("A textual description of the cgscc pass pipeline inserted at "
118 "the CGSCCOptimizerLate extension point into default pipelines"),
119 cl::Hidden);
120 static cl::opt<std::string> VectorizerStartEPPipeline(
121 "passes-ep-vectorizer-start",
122 cl::desc("A textual description of the function pass pipeline inserted at "
123 "the VectorizerStart extension point into default pipelines"),
124 cl::Hidden);
125 static cl::opt<std::string> VectorizerEndEPPipeline(
126 "passes-ep-vectorizer-end",
127 cl::desc("A textual description of the function pass pipeline inserted at "
128 "the VectorizerEnd extension point into default pipelines"),
129 cl::Hidden);
130 static cl::opt<std::string> PipelineStartEPPipeline(
131 "passes-ep-pipeline-start",
132 cl::desc("A textual description of the module pass pipeline inserted at "
133 "the PipelineStart extension point into default pipelines"),
134 cl::Hidden);
135 static cl::opt<std::string> PipelineEarlySimplificationEPPipeline(
136 "passes-ep-pipeline-early-simplification",
137 cl::desc("A textual description of the module pass pipeline inserted at "
138 "the EarlySimplification extension point into default pipelines"),
139 cl::Hidden);
140 static cl::opt<std::string> OptimizerEarlyEPPipeline(
141 "passes-ep-optimizer-early",
142 cl::desc("A textual description of the module pass pipeline inserted at "
143 "the OptimizerEarly extension point into default pipelines"),
144 cl::Hidden);
145 static cl::opt<std::string> OptimizerLastEPPipeline(
146 "passes-ep-optimizer-last",
147 cl::desc("A textual description of the module pass pipeline inserted at "
148 "the OptimizerLast extension point into default pipelines"),
149 cl::Hidden);
150 static cl::opt<std::string> FullLinkTimeOptimizationEarlyEPPipeline(
151 "passes-ep-full-link-time-optimization-early",
152 cl::desc("A textual description of the module pass pipeline inserted at "
153 "the FullLinkTimeOptimizationEarly extension point into default "
154 "pipelines"),
155 cl::Hidden);
156 static cl::opt<std::string> FullLinkTimeOptimizationLastEPPipeline(
157 "passes-ep-full-link-time-optimization-last",
158 cl::desc("A textual description of the module pass pipeline inserted at "
159 "the FullLinkTimeOptimizationLast extension point into default "
160 "pipelines"),
161 cl::Hidden);
162 /// @}}
164 static cl::opt<bool> DisablePipelineVerification(
165 "disable-pipeline-verification",
166 cl::desc("Only has an effect when specified with -print-pipeline-passes. "
167 "Disables verifying that the textual pipeline generated by "
168 "-print-pipeline-passes can be used to create a pipeline."),
169 cl::Hidden);
172 static cl::opt<PGOKind>
173 PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
174 cl::desc("The kind of profile guided optimization"),
175 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
176 clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
177 "Instrument the IR to generate profile."),
178 clEnumValN(InstrUse, "pgo-instr-use-pipeline",
179 "Use instrumented profile to guide PGO."),
180 clEnumValN(SampleUse, "pgo-sample-use-pipeline",
181 "Use sampled profile to guide PGO.")));
182 static cl::opt<std::string> ProfileFile("profile-file",
183 cl::desc("Path to the profile."), cl::Hidden);
184 static cl::opt<std::string>
185 MemoryProfileFile("memory-profile-file",
186 cl::desc("Path to the memory profile."), cl::Hidden);
188 static cl::opt<CSPGOKind> CSPGOKindFlag(
189 "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
190 cl::desc("The kind of context sensitive profile guided optimization"),
191 cl::values(
192 clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
193 clEnumValN(
194 CSInstrGen, "cspgo-instr-gen-pipeline",
195 "Instrument (context sensitive) the IR to generate profile."),
196 clEnumValN(
197 CSInstrUse, "cspgo-instr-use-pipeline",
198 "Use instrumented (context sensitive) profile to guide PGO.")));
200 static cl::opt<std::string> CSProfileGenFile(
201 "cs-profilegen-file",
202 cl::desc("Path to the instrumented context sensitive profile."),
203 cl::Hidden);
205 static cl::opt<std::string>
206 ProfileRemappingFile("profile-remapping-file",
207 cl::desc("Path to the profile remapping file."),
208 cl::Hidden);
210 static cl::opt<PGOOptions::ColdFuncOpt> PGOColdFuncAttr(
211 "pgo-cold-func-opt", cl::init(PGOOptions::ColdFuncOpt::Default), cl::Hidden,
212 cl::desc(
213 "Function attribute to apply to cold functions as determined by PGO"),
214 cl::values(clEnumValN(PGOOptions::ColdFuncOpt::Default, "default",
215 "Default (no attribute)"),
216 clEnumValN(PGOOptions::ColdFuncOpt::OptSize, "optsize",
217 "Mark cold functions with optsize."),
218 clEnumValN(PGOOptions::ColdFuncOpt::MinSize, "minsize",
219 "Mark cold functions with minsize."),
220 clEnumValN(PGOOptions::ColdFuncOpt::OptNone, "optnone",
221 "Mark cold functions with optnone.")));
223 static cl::opt<bool> DebugInfoForProfiling(
224 "debug-info-for-profiling", cl::init(false), cl::Hidden,
225 cl::desc("Emit special debug info to enable PGO profile generation."));
227 static cl::opt<bool> PseudoProbeForProfiling(
228 "pseudo-probe-for-profiling", cl::init(false), cl::Hidden,
229 cl::desc("Emit pseudo probes to enable PGO profile generation."));
231 static cl::opt<bool> DisableLoopUnrolling(
232 "disable-loop-unrolling",
233 cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false));
235 template <typename PassManagerT>
236 bool tryParsePipelineText(PassBuilder &PB,
237 const cl::opt<std::string> &PipelineOpt) {
238 if (PipelineOpt.empty())
239 return false;
241 // Verify the pipeline is parseable:
242 PassManagerT PM;
243 if (auto Err = PB.parsePassPipeline(PM, PipelineOpt)) {
244 errs() << "Could not parse -" << PipelineOpt.ArgStr
245 << " pipeline: " << toString(std::move(Err))
246 << "... I'm going to ignore it.\n";
247 return false;
249 return true;
252 /// If one of the EPPipeline command line options was given, register callbacks
253 /// for parsing and inserting the given pipeline
254 static void registerEPCallbacks(PassBuilder &PB) {
255 if (tryParsePipelineText<FunctionPassManager>(PB, PeepholeEPPipeline))
256 PB.registerPeepholeEPCallback(
257 [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
258 ExitOnError Err("Unable to parse PeepholeEP pipeline: ");
259 Err(PB.parsePassPipeline(PM, PeepholeEPPipeline));
261 if (tryParsePipelineText<LoopPassManager>(PB,
262 LateLoopOptimizationsEPPipeline))
263 PB.registerLateLoopOptimizationsEPCallback(
264 [&PB](LoopPassManager &PM, OptimizationLevel Level) {
265 ExitOnError Err("Unable to parse LateLoopOptimizationsEP pipeline: ");
266 Err(PB.parsePassPipeline(PM, LateLoopOptimizationsEPPipeline));
268 if (tryParsePipelineText<LoopPassManager>(PB, LoopOptimizerEndEPPipeline))
269 PB.registerLoopOptimizerEndEPCallback(
270 [&PB](LoopPassManager &PM, OptimizationLevel Level) {
271 ExitOnError Err("Unable to parse LoopOptimizerEndEP pipeline: ");
272 Err(PB.parsePassPipeline(PM, LoopOptimizerEndEPPipeline));
274 if (tryParsePipelineText<FunctionPassManager>(PB,
275 ScalarOptimizerLateEPPipeline))
276 PB.registerScalarOptimizerLateEPCallback(
277 [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
278 ExitOnError Err("Unable to parse ScalarOptimizerLateEP pipeline: ");
279 Err(PB.parsePassPipeline(PM, ScalarOptimizerLateEPPipeline));
281 if (tryParsePipelineText<CGSCCPassManager>(PB, CGSCCOptimizerLateEPPipeline))
282 PB.registerCGSCCOptimizerLateEPCallback(
283 [&PB](CGSCCPassManager &PM, OptimizationLevel Level) {
284 ExitOnError Err("Unable to parse CGSCCOptimizerLateEP pipeline: ");
285 Err(PB.parsePassPipeline(PM, CGSCCOptimizerLateEPPipeline));
287 if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerStartEPPipeline))
288 PB.registerVectorizerStartEPCallback(
289 [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
290 ExitOnError Err("Unable to parse VectorizerStartEP pipeline: ");
291 Err(PB.parsePassPipeline(PM, VectorizerStartEPPipeline));
293 if (tryParsePipelineText<FunctionPassManager>(PB, VectorizerEndEPPipeline))
294 PB.registerVectorizerEndEPCallback(
295 [&PB](FunctionPassManager &PM, OptimizationLevel Level) {
296 ExitOnError Err("Unable to parse VectorizerEndEP pipeline: ");
297 Err(PB.parsePassPipeline(PM, VectorizerEndEPPipeline));
299 if (tryParsePipelineText<ModulePassManager>(PB, PipelineStartEPPipeline))
300 PB.registerPipelineStartEPCallback(
301 [&PB](ModulePassManager &PM, OptimizationLevel) {
302 ExitOnError Err("Unable to parse PipelineStartEP pipeline: ");
303 Err(PB.parsePassPipeline(PM, PipelineStartEPPipeline));
305 if (tryParsePipelineText<ModulePassManager>(
306 PB, PipelineEarlySimplificationEPPipeline))
307 PB.registerPipelineEarlySimplificationEPCallback(
308 [&PB](ModulePassManager &PM, OptimizationLevel, ThinOrFullLTOPhase) {
309 ExitOnError Err("Unable to parse EarlySimplification pipeline: ");
310 Err(PB.parsePassPipeline(PM, PipelineEarlySimplificationEPPipeline));
312 if (tryParsePipelineText<ModulePassManager>(PB, OptimizerEarlyEPPipeline))
313 PB.registerOptimizerEarlyEPCallback(
314 [&PB](ModulePassManager &PM, OptimizationLevel, ThinOrFullLTOPhase) {
315 ExitOnError Err("Unable to parse OptimizerEarlyEP pipeline: ");
316 Err(PB.parsePassPipeline(PM, OptimizerEarlyEPPipeline));
318 if (tryParsePipelineText<ModulePassManager>(PB, OptimizerLastEPPipeline))
319 PB.registerOptimizerLastEPCallback(
320 [&PB](ModulePassManager &PM, OptimizationLevel, ThinOrFullLTOPhase) {
321 ExitOnError Err("Unable to parse OptimizerLastEP pipeline: ");
322 Err(PB.parsePassPipeline(PM, OptimizerLastEPPipeline));
324 if (tryParsePipelineText<ModulePassManager>(
325 PB, FullLinkTimeOptimizationEarlyEPPipeline))
326 PB.registerFullLinkTimeOptimizationEarlyEPCallback(
327 [&PB](ModulePassManager &PM, OptimizationLevel) {
328 ExitOnError Err(
329 "Unable to parse FullLinkTimeOptimizationEarlyEP pipeline: ");
330 Err(PB.parsePassPipeline(PM,
331 FullLinkTimeOptimizationEarlyEPPipeline));
333 if (tryParsePipelineText<ModulePassManager>(
334 PB, FullLinkTimeOptimizationLastEPPipeline))
335 PB.registerFullLinkTimeOptimizationLastEPCallback(
336 [&PB](ModulePassManager &PM, OptimizationLevel) {
337 ExitOnError Err(
338 "Unable to parse FullLinkTimeOptimizationLastEP pipeline: ");
339 Err(PB.parsePassPipeline(PM, FullLinkTimeOptimizationLastEPPipeline));
343 #define HANDLE_EXTENSION(Ext) \
344 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
345 #include "llvm/Support/Extension.def"
347 bool llvm::runPassPipeline(
348 StringRef Arg0, Module &M, TargetMachine *TM, TargetLibraryInfoImpl *TLII,
349 ToolOutputFile *Out, ToolOutputFile *ThinLTOLinkOut,
350 ToolOutputFile *OptRemarkFile, StringRef PassPipeline,
351 ArrayRef<PassPlugin> PassPlugins,
352 ArrayRef<std::function<void(llvm::PassBuilder &)>> PassBuilderCallbacks,
353 OutputKind OK, VerifierKind VK, bool ShouldPreserveAssemblyUseListOrder,
354 bool ShouldPreserveBitcodeUseListOrder, bool EmitSummaryIndex,
355 bool EmitModuleHash, bool EnableDebugify, bool VerifyDIPreserve,
356 bool UnifiedLTO) {
357 auto FS = vfs::getRealFileSystem();
358 std::optional<PGOOptions> P;
359 switch (PGOKindFlag) {
360 case InstrGen:
361 P = PGOOptions(ProfileFile, "", "", MemoryProfileFile, FS,
362 PGOOptions::IRInstr, PGOOptions::NoCSAction,
363 PGOColdFuncAttr);
364 break;
365 case InstrUse:
366 P = PGOOptions(ProfileFile, "", ProfileRemappingFile, MemoryProfileFile, FS,
367 PGOOptions::IRUse, PGOOptions::NoCSAction, PGOColdFuncAttr);
368 break;
369 case SampleUse:
370 P = PGOOptions(ProfileFile, "", ProfileRemappingFile, MemoryProfileFile, FS,
371 PGOOptions::SampleUse, PGOOptions::NoCSAction,
372 PGOColdFuncAttr);
373 break;
374 case NoPGO:
375 if (DebugInfoForProfiling || PseudoProbeForProfiling ||
376 !MemoryProfileFile.empty())
377 P = PGOOptions("", "", "", MemoryProfileFile, FS, PGOOptions::NoAction,
378 PGOOptions::NoCSAction, PGOColdFuncAttr,
379 DebugInfoForProfiling, PseudoProbeForProfiling);
380 else
381 P = std::nullopt;
383 if (CSPGOKindFlag != NoCSPGO) {
384 if (P && (P->Action == PGOOptions::IRInstr ||
385 P->Action == PGOOptions::SampleUse)) {
386 errs() << "CSPGOKind cannot be used with IRInstr or SampleUse";
387 return false;
389 if (CSPGOKindFlag == CSInstrGen) {
390 if (CSProfileGenFile.empty()) {
391 errs() << "CSInstrGen needs to specify CSProfileGenFile";
392 return false;
394 if (P) {
395 P->CSAction = PGOOptions::CSIRInstr;
396 P->CSProfileGenFile = CSProfileGenFile;
397 } else
398 P = PGOOptions("", CSProfileGenFile, ProfileRemappingFile,
399 /*MemoryProfile=*/"", FS, PGOOptions::NoAction,
400 PGOOptions::CSIRInstr);
401 } else /* CSPGOKindFlag == CSInstrUse */ {
402 if (!P) {
403 errs() << "CSInstrUse needs to be together with InstrUse";
404 return false;
406 P->CSAction = PGOOptions::CSIRUse;
409 if (TM)
410 TM->setPGOOption(P);
412 LoopAnalysisManager LAM;
413 FunctionAnalysisManager FAM;
414 CGSCCAnalysisManager CGAM;
415 ModuleAnalysisManager MAM;
417 PassInstrumentationCallbacks PIC;
418 PrintPassOptions PrintPassOpts;
419 PrintPassOpts.Verbose = DebugPM == DebugLogging::Verbose;
420 PrintPassOpts.SkipAnalyses = DebugPM == DebugLogging::Quiet;
421 StandardInstrumentations SI(M.getContext(), DebugPM != DebugLogging::None,
422 VK == VerifierKind::EachPass, PrintPassOpts);
423 SI.registerCallbacks(PIC, &MAM);
424 DebugifyEachInstrumentation Debugify;
425 DebugifyStatsMap DIStatsMap;
426 DebugInfoPerPass DebugInfoBeforePass;
427 if (DebugifyEach) {
428 Debugify.setDIStatsMap(DIStatsMap);
429 Debugify.setDebugifyMode(DebugifyMode::SyntheticDebugInfo);
430 Debugify.registerCallbacks(PIC, MAM);
431 } else if (VerifyEachDebugInfoPreserve) {
432 Debugify.setDebugInfoBeforePass(DebugInfoBeforePass);
433 Debugify.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
434 Debugify.setOrigDIVerifyBugsReportFilePath(
435 VerifyDIPreserveExport);
436 Debugify.registerCallbacks(PIC, MAM);
439 PipelineTuningOptions PTO;
440 // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized
441 // to false above so we shouldn't necessarily need to check whether or not the
442 // option has been enabled.
443 PTO.LoopUnrolling = !DisableLoopUnrolling;
444 PTO.UnifiedLTO = UnifiedLTO;
445 PassBuilder PB(TM, PTO, P, &PIC);
446 registerEPCallbacks(PB);
448 // For any loaded plugins, let them register pass builder callbacks.
449 for (auto &PassPlugin : PassPlugins)
450 PassPlugin.registerPassBuilderCallbacks(PB);
452 // Load any explicitly specified plugins.
453 for (auto &PassCallback : PassBuilderCallbacks)
454 PassCallback(PB);
456 #define HANDLE_EXTENSION(Ext) \
457 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
458 #include "llvm/Support/Extension.def"
460 // Specially handle the alias analysis manager so that we can register
461 // a custom pipeline of AA passes with it.
462 AAManager AA;
463 if (auto Err = PB.parseAAPipeline(AA, AAPipeline)) {
464 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
465 return false;
468 // Register the AA manager first so that our version is the one used.
469 FAM.registerPass([&] { return std::move(AA); });
470 // Register our TargetLibraryInfoImpl.
471 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
473 // Register all the basic analyses with the managers.
474 PB.registerModuleAnalyses(MAM);
475 PB.registerCGSCCAnalyses(CGAM);
476 PB.registerFunctionAnalyses(FAM);
477 PB.registerLoopAnalyses(LAM);
478 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
480 ModulePassManager MPM;
481 if (EnableDebugify)
482 MPM.addPass(NewPMDebugifyPass());
483 if (VerifyDIPreserve)
484 MPM.addPass(NewPMDebugifyPass(DebugifyMode::OriginalDebugInfo, "",
485 &DebugInfoBeforePass));
487 // Add passes according to the -passes options.
488 if (!PassPipeline.empty()) {
489 if (auto Err = PB.parsePassPipeline(MPM, PassPipeline)) {
490 errs() << Arg0 << ": " << toString(std::move(Err)) << "\n";
491 return false;
495 if (VK != VerifierKind::None)
496 MPM.addPass(VerifierPass());
497 if (EnableDebugify)
498 MPM.addPass(NewPMCheckDebugifyPass(false, "", &DIStatsMap));
499 if (VerifyDIPreserve)
500 MPM.addPass(NewPMCheckDebugifyPass(
501 false, "", nullptr, DebugifyMode::OriginalDebugInfo,
502 &DebugInfoBeforePass, VerifyDIPreserveExport));
504 // Add any relevant output pass at the end of the pipeline.
505 switch (OK) {
506 case OK_NoOutput:
507 break; // No output pass needed.
508 case OK_OutputAssembly:
509 MPM.addPass(PrintModulePass(
510 Out->os(), "", ShouldPreserveAssemblyUseListOrder, EmitSummaryIndex));
511 break;
512 case OK_OutputBitcode:
513 MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
514 EmitSummaryIndex, EmitModuleHash));
515 break;
516 case OK_OutputThinLTOBitcode:
517 MPM.addPass(ThinLTOBitcodeWriterPass(
518 Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr));
519 break;
522 // Before executing passes, print the final values of the LLVM options.
523 cl::PrintOptionValues();
525 // Print a textual, '-passes=' compatible, representation of pipeline if
526 // requested.
527 if (PrintPipelinePasses) {
528 std::string Pipeline;
529 raw_string_ostream SOS(Pipeline);
530 MPM.printPipeline(SOS, [&PIC](StringRef ClassName) {
531 auto PassName = PIC.getPassNameForClassName(ClassName);
532 return PassName.empty() ? ClassName : PassName;
534 outs() << Pipeline;
535 outs() << "\n";
537 if (!DisablePipelineVerification) {
538 // Check that we can parse the returned pipeline string as an actual
539 // pipeline.
540 ModulePassManager TempPM;
541 if (auto Err = PB.parsePassPipeline(TempPM, Pipeline)) {
542 errs() << "Could not parse dumped pass pipeline: "
543 << toString(std::move(Err)) << "\n";
544 return false;
548 return true;
551 // Now that we have all of the passes ready, run them.
552 MPM.run(M, MAM);
554 // Declare success.
555 if (OK != OK_NoOutput) {
556 Out->keep();
557 if (OK == OK_OutputThinLTOBitcode && ThinLTOLinkOut)
558 ThinLTOLinkOut->keep();
561 if (OptRemarkFile)
562 OptRemarkFile->keep();
564 if (DebugifyEach && !DebugifyExport.empty())
565 exportDebugifyStats(DebugifyExport, Debugify.getDebugifyStatsMap());
567 return true;
570 void llvm::printPasses(raw_ostream &OS) {
571 PassBuilder PB;
572 PB.printPassNames(OS);