xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 3a92ecc8)
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/CommandFlags.inc"
27 #include "llvm/CodeGen/TargetPassConfig.h"
28 #include "llvm/Config/llvm-config.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/IRPrintingPasses.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/LegacyPassManager.h"
34 #include "llvm/IR/LegacyPassNameParser.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Verifier.h"
37 #include "llvm/IRReader/IRReader.h"
38 #include "llvm/InitializePasses.h"
39 #include "llvm/LinkAllIR.h"
40 #include "llvm/LinkAllPasses.h"
41 #include "llvm/MC/SubtargetFeature.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/InitLLVM.h"
46 #include "llvm/Support/PluginLoader.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/YAMLTraits.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/IPO/AlwaysInliner.h"
56 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
57 #include "llvm/Transforms/Utils/Cloning.h"
58 #include <algorithm>
59 #include <memory>
60 using namespace llvm;
61 using namespace opt_tool;
62 
63 // The OptimizationList is automatically populated with registered Passes by the
64 // PassNameParser.
65 //
66 static cl::list<const PassInfo*, bool, PassNameParser>
67 PassList(cl::desc("Optimizations available:"));
68 
69 // This flag specifies a textual description of the optimization pass pipeline
70 // to run over the module. This flag switches opt to use the new pass manager
71 // infrastructure, completely disabling all of the flags specific to the old
72 // pass management.
73 static cl::opt<std::string> PassPipeline(
74     "passes",
75     cl::desc("A textual description of the pass pipeline for optimizing"),
76     cl::Hidden);
77 
78 // Other command line options...
79 //
80 static cl::opt<std::string>
81 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
82     cl::init("-"), cl::value_desc("filename"));
83 
84 static cl::opt<std::string>
85 OutputFilename("o", cl::desc("Override output filename"),
86                cl::value_desc("filename"));
87 
88 static cl::opt<bool>
89 Force("f", cl::desc("Enable binary output on terminals"));
90 
91 static cl::opt<bool>
92 PrintEachXForm("p", cl::desc("Print module after each transformation"));
93 
94 static cl::opt<bool>
95 NoOutput("disable-output",
96          cl::desc("Do not write result bitcode file"), cl::Hidden);
97 
98 static cl::opt<bool>
99 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
100 
101 static cl::opt<bool>
102     OutputThinLTOBC("thinlto-bc",
103                     cl::desc("Write output as ThinLTO-ready bitcode"));
104 
105 static cl::opt<std::string> ThinLinkBitcodeFile(
106     "thin-link-bitcode-file", cl::value_desc("filename"),
107     cl::desc(
108         "A file in which to write minimized bitcode for the thin link only"));
109 
110 static cl::opt<bool>
111 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
112 
113 static cl::opt<bool>
114 VerifyEach("verify-each", cl::desc("Verify after each transform"));
115 
116 static cl::opt<bool>
117     DisableDITypeMap("disable-debug-info-type-map",
118                      cl::desc("Don't use a uniquing type map for debug info"));
119 
120 static cl::opt<bool>
121 StripDebug("strip-debug",
122            cl::desc("Strip debugger symbol info from translation unit"));
123 
124 static cl::opt<bool>
125 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
126 
127 static cl::opt<bool>
128 DisableOptimizations("disable-opt",
129                      cl::desc("Do not run any optimization passes"));
130 
131 static cl::opt<bool>
132 StandardLinkOpts("std-link-opts",
133                  cl::desc("Include the standard link time optimizations"));
134 
135 static cl::opt<bool>
136 OptLevelO0("O0",
137   cl::desc("Optimization level 0. Similar to clang -O0"));
138 
139 static cl::opt<bool>
140 OptLevelO1("O1",
141            cl::desc("Optimization level 1. Similar to clang -O1"));
142 
143 static cl::opt<bool>
144 OptLevelO2("O2",
145            cl::desc("Optimization level 2. Similar to clang -O2"));
146 
147 static cl::opt<bool>
148 OptLevelOs("Os",
149            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
150 
151 static cl::opt<bool>
152 OptLevelOz("Oz",
153            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
154 
155 static cl::opt<bool>
156 OptLevelO3("O3",
157            cl::desc("Optimization level 3. Similar to clang -O3"));
158 
159 static cl::opt<unsigned>
160 CodeGenOptLevel("codegen-opt-level",
161                 cl::desc("Override optimization level for codegen hooks"));
162 
163 static cl::opt<std::string>
164 TargetTriple("mtriple", cl::desc("Override target triple for module"));
165 
166 static cl::opt<bool>
167 UnitAtATime("funit-at-a-time",
168             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
169             cl::init(true));
170 
171 static cl::opt<bool>
172 DisableLoopUnrolling("disable-loop-unrolling",
173                      cl::desc("Disable loop unrolling in all relevant passes"),
174                      cl::init(false));
175 static cl::opt<bool>
176 DisableLoopVectorization("disable-loop-vectorization",
177                      cl::desc("Disable the loop vectorization pass"),
178                      cl::init(false));
179 
180 static cl::opt<bool>
181 DisableSLPVectorization("disable-slp-vectorization",
182                         cl::desc("Disable the slp vectorization pass"),
183                         cl::init(false));
184 
185 static cl::opt<bool> EmitSummaryIndex("module-summary",
186                                       cl::desc("Emit module summary index"),
187                                       cl::init(false));
188 
189 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
190                                     cl::init(false));
191 
192 static cl::opt<bool>
193 DisableSimplifyLibCalls("disable-simplify-libcalls",
194                         cl::desc("Disable simplify-libcalls"));
195 
196 static cl::opt<bool>
197 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
198 
199 static cl::alias
200 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
201 
202 static cl::opt<bool>
203 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
204 
205 static cl::opt<bool> EnableDebugify(
206     "enable-debugify",
207     cl::desc(
208         "Start the pipeline with debugify and end it with check-debugify"));
209 
210 static cl::opt<bool> DebugifyEach(
211     "debugify-each",
212     cl::desc(
213         "Start each pass with debugify and end it with check-debugify"));
214 
215 static cl::opt<bool>
216 PrintBreakpoints("print-breakpoints-for-testing",
217                  cl::desc("Print select breakpoints location for testing"));
218 
219 static cl::opt<std::string> ClDataLayout("data-layout",
220                                          cl::desc("data layout string to use"),
221                                          cl::value_desc("layout-string"),
222                                          cl::init(""));
223 
224 static cl::opt<bool> PreserveBitcodeUseListOrder(
225     "preserve-bc-uselistorder",
226     cl::desc("Preserve use-list order when writing LLVM bitcode."),
227     cl::init(true), cl::Hidden);
228 
229 static cl::opt<bool> PreserveAssemblyUseListOrder(
230     "preserve-ll-uselistorder",
231     cl::desc("Preserve use-list order when writing LLVM assembly."),
232     cl::init(false), cl::Hidden);
233 
234 static cl::opt<bool>
235     RunTwice("run-twice",
236              cl::desc("Run all passes twice, re-using the same pass manager."),
237              cl::init(false), cl::Hidden);
238 
239 static cl::opt<bool> DiscardValueNames(
240     "discard-value-names",
241     cl::desc("Discard names from Value (other than GlobalValue)."),
242     cl::init(false), cl::Hidden);
243 
244 static cl::opt<bool> Coroutines(
245   "enable-coroutines",
246   cl::desc("Enable coroutine passes."),
247   cl::init(false), cl::Hidden);
248 
249 static cl::opt<bool> PassRemarksWithHotness(
250     "pass-remarks-with-hotness",
251     cl::desc("With PGO, include profile count in optimization remarks"),
252     cl::Hidden);
253 
254 static cl::opt<unsigned> PassRemarksHotnessThreshold(
255     "pass-remarks-hotness-threshold",
256     cl::desc("Minimum profile count required for an optimization remark to be output"),
257     cl::Hidden);
258 
259 static cl::opt<std::string>
260     RemarksFilename("pass-remarks-output",
261                     cl::desc("YAML output filename for pass remarks"),
262                     cl::value_desc("filename"));
263 
264 class OptCustomPassManager : public legacy::PassManager {
265 public:
266   using super = legacy::PassManager;
267 
268   void add(Pass *P) override {
269     bool WrapWithDebugify =
270         DebugifyEach && !P->getAsImmutablePass() && !isIRPrintingPass(P);
271     if (!WrapWithDebugify) {
272       super::add(P);
273       return;
274     }
275     PassKind Kind = P->getPassKind();
276     // TODO: Implement Debugify for BasicBlockPass, LoopPass.
277     switch (Kind) {
278       case PT_Function:
279         super::add(createDebugifyFunctionPass());
280         super::add(P);
281         super::add(createCheckDebugifyFunctionPass(true, P->getPassName()));
282         break;
283       case PT_Module:
284         super::add(createDebugifyModulePass());
285         super::add(P);
286         super::add(createCheckDebugifyModulePass(true, P->getPassName()));
287         break;
288       default:
289         super::add(P);
290         break;
291     }
292   }
293 };
294 
295 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
296   // Add the pass to the pass manager...
297   PM.add(P);
298 
299   // If we are verifying all of the intermediate steps, add the verifier...
300   if (VerifyEach)
301     PM.add(createVerifierPass());
302 }
303 
304 /// This routine adds optimization passes based on selected optimization level,
305 /// OptLevel.
306 ///
307 /// OptLevel - Optimization Level
308 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
309                                   legacy::FunctionPassManager &FPM,
310                                   TargetMachine *TM, unsigned OptLevel,
311                                   unsigned SizeLevel) {
312   if (!NoVerify || VerifyEach)
313     FPM.add(createVerifierPass()); // Verify that input is correct
314 
315   PassManagerBuilder Builder;
316   Builder.OptLevel = OptLevel;
317   Builder.SizeLevel = SizeLevel;
318 
319   if (DisableInline) {
320     // No inlining pass
321   } else if (OptLevel > 1) {
322     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
323   } else {
324     Builder.Inliner = createAlwaysInlinerLegacyPass();
325   }
326   Builder.DisableUnitAtATime = !UnitAtATime;
327   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
328                                DisableLoopUnrolling : OptLevel == 0;
329 
330   // This is final, unless there is a #pragma vectorize enable
331   if (DisableLoopVectorization)
332     Builder.LoopVectorize = false;
333   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
334   else if (!Builder.LoopVectorize)
335     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
336 
337   // When #pragma vectorize is on for SLP, do the same as above
338   Builder.SLPVectorize =
339       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
340 
341   if (TM)
342     TM->adjustPassManager(Builder);
343 
344   if (Coroutines)
345     addCoroutinePassesToExtensionPoints(Builder);
346 
347   Builder.populateFunctionPassManager(FPM);
348   Builder.populateModulePassManager(MPM);
349 }
350 
351 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
352   PassManagerBuilder Builder;
353   Builder.VerifyInput = true;
354   if (DisableOptimizations)
355     Builder.OptLevel = 0;
356 
357   if (!DisableInline)
358     Builder.Inliner = createFunctionInliningPass();
359   Builder.populateLTOPassManager(PM);
360 }
361 
362 //===----------------------------------------------------------------------===//
363 // CodeGen-related helper functions.
364 //
365 
366 static CodeGenOpt::Level GetCodeGenOptLevel() {
367   if (CodeGenOptLevel.getNumOccurrences())
368     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
369   if (OptLevelO1)
370     return CodeGenOpt::Less;
371   if (OptLevelO2)
372     return CodeGenOpt::Default;
373   if (OptLevelO3)
374     return CodeGenOpt::Aggressive;
375   return CodeGenOpt::None;
376 }
377 
378 // Returns the TargetMachine instance or zero if no triple is provided.
379 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
380                                        StringRef FeaturesStr,
381                                        const TargetOptions &Options) {
382   std::string Error;
383   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
384                                                          Error);
385   // Some modules don't specify a triple, and this is okay.
386   if (!TheTarget) {
387     return nullptr;
388   }
389 
390   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
391                                         FeaturesStr, Options, getRelocModel(),
392                                         getCodeModel(), GetCodeGenOptLevel());
393 }
394 
395 #ifdef LINK_POLLY_INTO_TOOLS
396 namespace polly {
397 void initializePollyPasses(llvm::PassRegistry &Registry);
398 }
399 #endif
400 
401 //===----------------------------------------------------------------------===//
402 // main for opt
403 //
404 int main(int argc, char **argv) {
405   InitLLVM X(argc, argv);
406 
407   // Enable debug stream buffering.
408   EnableDebugBuffering = true;
409 
410   LLVMContext Context;
411 
412   InitializeAllTargets();
413   InitializeAllTargetMCs();
414   InitializeAllAsmPrinters();
415   InitializeAllAsmParsers();
416 
417   // Initialize passes
418   PassRegistry &Registry = *PassRegistry::getPassRegistry();
419   initializeCore(Registry);
420   initializeCoroutines(Registry);
421   initializeScalarOpts(Registry);
422   initializeObjCARCOpts(Registry);
423   initializeVectorization(Registry);
424   initializeIPO(Registry);
425   initializeAnalysis(Registry);
426   initializeTransformUtils(Registry);
427   initializeInstCombine(Registry);
428   initializeAggressiveInstCombine(Registry);
429   initializeInstrumentation(Registry);
430   initializeTarget(Registry);
431   // For codegen passes, only passes that do IR to IR transformation are
432   // supported.
433   initializeExpandMemCmpPassPass(Registry);
434   initializeScalarizeMaskedMemIntrinPass(Registry);
435   initializeCodeGenPreparePass(Registry);
436   initializeAtomicExpandPass(Registry);
437   initializeRewriteSymbolsLegacyPassPass(Registry);
438   initializeWinEHPreparePass(Registry);
439   initializeDwarfEHPreparePass(Registry);
440   initializeSafeStackLegacyPassPass(Registry);
441   initializeSjLjEHPreparePass(Registry);
442   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
443   initializeGlobalMergePass(Registry);
444   initializeIndirectBrExpandPassPass(Registry);
445   initializeInterleavedAccessPass(Registry);
446   initializeEntryExitInstrumenterPass(Registry);
447   initializePostInlineEntryExitInstrumenterPass(Registry);
448   initializeUnreachableBlockElimLegacyPassPass(Registry);
449   initializeExpandReductionsPass(Registry);
450   initializeWriteBitcodePassPass(Registry);
451 
452 #ifdef LINK_POLLY_INTO_TOOLS
453   polly::initializePollyPasses(Registry);
454 #endif
455 
456   cl::ParseCommandLineOptions(argc, argv,
457     "llvm .bc -> .bc modular optimizer and analysis printer\n");
458 
459   if (AnalyzeOnly && NoOutput) {
460     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
461     return 1;
462   }
463 
464   SMDiagnostic Err;
465 
466   Context.setDiscardValueNames(DiscardValueNames);
467   if (!DisableDITypeMap)
468     Context.enableDebugTypeODRUniquing();
469 
470   if (PassRemarksWithHotness)
471     Context.setDiagnosticsHotnessRequested(true);
472 
473   if (PassRemarksHotnessThreshold)
474     Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
475 
476   std::unique_ptr<ToolOutputFile> OptRemarkFile;
477   if (RemarksFilename != "") {
478     std::error_code EC;
479     OptRemarkFile =
480         llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
481     if (EC) {
482       errs() << EC.message() << '\n';
483       return 1;
484     }
485     Context.setDiagnosticsOutputFile(
486         llvm::make_unique<yaml::Output>(OptRemarkFile->os()));
487   }
488 
489   // Load the input module...
490   std::unique_ptr<Module> M =
491       parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout);
492 
493   if (!M) {
494     Err.print(argv[0], errs());
495     return 1;
496   }
497 
498   // Strip debug info before running the verifier.
499   if (StripDebug)
500     StripDebugInfo(*M);
501 
502   // If we are supposed to override the target triple or data layout, do so now.
503   if (!TargetTriple.empty())
504     M->setTargetTriple(Triple::normalize(TargetTriple));
505 
506   // Immediately run the verifier to catch any problems before starting up the
507   // pass pipelines.  Otherwise we can crash on broken code during
508   // doInitialization().
509   if (!NoVerify && verifyModule(*M, &errs())) {
510     errs() << argv[0] << ": " << InputFilename
511            << ": error: input module is broken!\n";
512     return 1;
513   }
514 
515   // Figure out what stream we are supposed to write to...
516   std::unique_ptr<ToolOutputFile> Out;
517   std::unique_ptr<ToolOutputFile> ThinLinkOut;
518   if (NoOutput) {
519     if (!OutputFilename.empty())
520       errs() << "WARNING: The -o (output filename) option is ignored when\n"
521                 "the --disable-output option is used.\n";
522   } else {
523     // Default to standard output.
524     if (OutputFilename.empty())
525       OutputFilename = "-";
526 
527     std::error_code EC;
528     Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
529     if (EC) {
530       errs() << EC.message() << '\n';
531       return 1;
532     }
533 
534     if (!ThinLinkBitcodeFile.empty()) {
535       ThinLinkOut.reset(
536           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::F_None));
537       if (EC) {
538         errs() << EC.message() << '\n';
539         return 1;
540       }
541     }
542   }
543 
544   Triple ModuleTriple(M->getTargetTriple());
545   std::string CPUStr, FeaturesStr;
546   TargetMachine *Machine = nullptr;
547   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
548 
549   if (ModuleTriple.getArch()) {
550     CPUStr = getCPUStr();
551     FeaturesStr = getFeaturesStr();
552     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
553   }
554 
555   std::unique_ptr<TargetMachine> TM(Machine);
556 
557   // Override function attributes based on CPUStr, FeaturesStr, and command line
558   // flags.
559   setFunctionAttributes(CPUStr, FeaturesStr, *M);
560 
561   // If the output is set to be emitted to standard out, and standard out is a
562   // console, print out a warning message and refuse to do it.  We don't
563   // impress anyone by spewing tons of binary goo to a terminal.
564   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
565     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
566       NoOutput = true;
567 
568   if (PassPipeline.getNumOccurrences() > 0) {
569     OutputKind OK = OK_NoOutput;
570     if (!NoOutput)
571       OK = OutputAssembly
572                ? OK_OutputAssembly
573                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
574 
575     VerifierKind VK = VK_VerifyInAndOut;
576     if (NoVerify)
577       VK = VK_NoVerifier;
578     else if (VerifyEach)
579       VK = VK_VerifyEachPass;
580 
581     // The user has asked to use the new pass manager and provided a pipeline
582     // string. Hand off the rest of the functionality to the new code for that
583     // layer.
584     return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
585                            OptRemarkFile.get(), PassPipeline, OK, VK,
586                            PreserveAssemblyUseListOrder,
587                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
588                            EmitModuleHash, EnableDebugify)
589                ? 0
590                : 1;
591   }
592 
593   // Create a PassManager to hold and optimize the collection of passes we are
594   // about to build.
595   OptCustomPassManager Passes;
596   bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach;
597 
598   // Add an appropriate TargetLibraryInfo pass for the module's triple.
599   TargetLibraryInfoImpl TLII(ModuleTriple);
600 
601   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
602   if (DisableSimplifyLibCalls)
603     TLII.disableAllFunctions();
604   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
605 
606   // Add internal analysis passes from the target machine.
607   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
608                                                      : TargetIRAnalysis()));
609 
610   if (AddOneTimeDebugifyPasses)
611     Passes.add(createDebugifyModulePass());
612 
613   std::unique_ptr<legacy::FunctionPassManager> FPasses;
614   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
615       OptLevelO3) {
616     FPasses.reset(new legacy::FunctionPassManager(M.get()));
617     FPasses->add(createTargetTransformInfoWrapperPass(
618         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
619   }
620 
621   if (PrintBreakpoints) {
622     // Default to standard output.
623     if (!Out) {
624       if (OutputFilename.empty())
625         OutputFilename = "-";
626 
627       std::error_code EC;
628       Out = llvm::make_unique<ToolOutputFile>(OutputFilename, EC,
629                                               sys::fs::F_None);
630       if (EC) {
631         errs() << EC.message() << '\n';
632         return 1;
633       }
634     }
635     Passes.add(createBreakpointPrinter(Out->os()));
636     NoOutput = true;
637   }
638 
639   if (TM) {
640     // FIXME: We should dyn_cast this when supported.
641     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
642     Pass *TPC = LTM.createPassConfig(Passes);
643     Passes.add(TPC);
644   }
645 
646   // Create a new optimization pass for each one specified on the command line
647   for (unsigned i = 0; i < PassList.size(); ++i) {
648     if (StandardLinkOpts &&
649         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
650       AddStandardLinkPasses(Passes);
651       StandardLinkOpts = false;
652     }
653 
654     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
655       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
656       OptLevelO0 = false;
657     }
658 
659     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
660       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
661       OptLevelO1 = false;
662     }
663 
664     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
665       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
666       OptLevelO2 = false;
667     }
668 
669     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
670       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
671       OptLevelOs = false;
672     }
673 
674     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
675       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
676       OptLevelOz = false;
677     }
678 
679     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
680       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
681       OptLevelO3 = false;
682     }
683 
684     const PassInfo *PassInf = PassList[i];
685     Pass *P = nullptr;
686     if (PassInf->getNormalCtor())
687       P = PassInf->getNormalCtor()();
688     else
689       errs() << argv[0] << ": cannot create pass: "
690              << PassInf->getPassName() << "\n";
691     if (P) {
692       PassKind Kind = P->getPassKind();
693       addPass(Passes, P);
694 
695       if (AnalyzeOnly) {
696         switch (Kind) {
697         case PT_BasicBlock:
698           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
699           break;
700         case PT_Region:
701           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
702           break;
703         case PT_Loop:
704           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
705           break;
706         case PT_Function:
707           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
708           break;
709         case PT_CallGraphSCC:
710           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
711           break;
712         default:
713           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
714           break;
715         }
716       }
717     }
718 
719     if (PrintEachXForm)
720       Passes.add(
721           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
722   }
723 
724   if (StandardLinkOpts) {
725     AddStandardLinkPasses(Passes);
726     StandardLinkOpts = false;
727   }
728 
729   if (OptLevelO0)
730     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
731 
732   if (OptLevelO1)
733     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
734 
735   if (OptLevelO2)
736     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
737 
738   if (OptLevelOs)
739     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
740 
741   if (OptLevelOz)
742     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
743 
744   if (OptLevelO3)
745     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
746 
747   if (FPasses) {
748     FPasses->doInitialization();
749     for (Function &F : *M)
750       FPasses->run(F);
751     FPasses->doFinalization();
752   }
753 
754   // Check that the module is well formed on completion of optimization
755   if (!NoVerify && !VerifyEach)
756     Passes.add(createVerifierPass());
757 
758   if (AddOneTimeDebugifyPasses)
759     Passes.add(createCheckDebugifyModulePass(false));
760 
761   // In run twice mode, we want to make sure the output is bit-by-bit
762   // equivalent if we run the pass manager again, so setup two buffers and
763   // a stream to write to them. Note that llc does something similar and it
764   // may be worth to abstract this out in the future.
765   SmallVector<char, 0> Buffer;
766   SmallVector<char, 0> FirstRunBuffer;
767   std::unique_ptr<raw_svector_ostream> BOS;
768   raw_ostream *OS = nullptr;
769 
770   // Write bitcode or assembly to the output as the last step...
771   if (!NoOutput && !AnalyzeOnly) {
772     assert(Out);
773     OS = &Out->os();
774     if (RunTwice) {
775       BOS = make_unique<raw_svector_ostream>(Buffer);
776       OS = BOS.get();
777     }
778     if (OutputAssembly) {
779       if (EmitSummaryIndex)
780         report_fatal_error("Text output is incompatible with -module-summary");
781       if (EmitModuleHash)
782         report_fatal_error("Text output is incompatible with -module-hash");
783       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
784     } else if (OutputThinLTOBC)
785       Passes.add(createWriteThinLTOBitcodePass(
786           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
787     else
788       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
789                                          EmitSummaryIndex, EmitModuleHash));
790   }
791 
792   // Before executing passes, print the final values of the LLVM options.
793   cl::PrintOptionValues();
794 
795   if (!RunTwice) {
796     // Now that we have all of the passes ready, run them.
797     Passes.run(*M);
798   } else {
799     // If requested, run all passes twice with the same pass manager to catch
800     // bugs caused by persistent state in the passes.
801     std::unique_ptr<Module> M2(CloneModule(*M));
802     // Run all passes on the original module first, so the second run processes
803     // the clone to catch CloneModule bugs.
804     Passes.run(*M);
805     FirstRunBuffer = Buffer;
806     Buffer.clear();
807 
808     Passes.run(*M2);
809 
810     // Compare the two outputs and make sure they're the same
811     assert(Out);
812     if (Buffer.size() != FirstRunBuffer.size() ||
813         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
814       errs()
815           << "Running the pass manager twice changed the output.\n"
816              "Writing the result of the second run to the specified output.\n"
817              "To generate the one-run comparison binary, just run without\n"
818              "the compile-twice option\n";
819       Out->os() << BOS->str();
820       Out->keep();
821       if (OptRemarkFile)
822         OptRemarkFile->keep();
823       return 1;
824     }
825     Out->os() << BOS->str();
826   }
827 
828   // Declare success.
829   if (!NoOutput || PrintBreakpoints)
830     Out->keep();
831 
832   if (OptRemarkFile)
833     OptRemarkFile->keep();
834 
835   if (ThinLinkOut)
836     ThinLinkOut->keep();
837 
838   return 0;
839 }
840