xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 0928368f)
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
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 //
9 // Optimizations may be specified an arbitrary number of times on the command
10 // line, They are run in the order specified.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "BreakpointPrinter.h"
15 #include "NewPMDriver.h"
16 #include "PassPrinters.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/CallGraph.h"
19 #include "llvm/Analysis/CallGraphSCCPass.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/RegionPass.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Bitcode/BitcodeWriterPass.h"
25 #include "llvm/CodeGen/CommandFlags.inc"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/LLVMRemarkStreamer.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/IPO/WholeProgramDevirt.h"
58 #include "llvm/Transforms/Utils/Cloning.h"
59 #include "llvm/Transforms/Utils/Debugify.h"
60 #include <algorithm>
61 #include <memory>
62 using namespace llvm;
63 using namespace opt_tool;
64 
65 // The OptimizationList is automatically populated with registered Passes by the
66 // PassNameParser.
67 //
68 static cl::list<const PassInfo*, bool, PassNameParser>
69 PassList(cl::desc("Optimizations available:"));
70 
71 // This flag specifies a textual description of the optimization pass pipeline
72 // to run over the module. This flag switches opt to use the new pass manager
73 // infrastructure, completely disabling all of the flags specific to the old
74 // pass management.
75 static cl::opt<std::string> PassPipeline(
76     "passes",
77     cl::desc("A textual description of the pass pipeline for optimizing"),
78     cl::Hidden);
79 
80 // Other command line options...
81 //
82 static cl::opt<std::string>
83 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
84     cl::init("-"), cl::value_desc("filename"));
85 
86 static cl::opt<std::string>
87 OutputFilename("o", cl::desc("Override output filename"),
88                cl::value_desc("filename"));
89 
90 static cl::opt<bool>
91 Force("f", cl::desc("Enable binary output on terminals"));
92 
93 static cl::opt<bool>
94 PrintEachXForm("p", cl::desc("Print module after each transformation"));
95 
96 static cl::opt<bool>
97 NoOutput("disable-output",
98          cl::desc("Do not write result bitcode file"), cl::Hidden);
99 
100 static cl::opt<bool>
101 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
102 
103 static cl::opt<bool>
104     OutputThinLTOBC("thinlto-bc",
105                     cl::desc("Write output as ThinLTO-ready bitcode"));
106 
107 static cl::opt<bool>
108     SplitLTOUnit("thinlto-split-lto-unit",
109                  cl::desc("Enable splitting of a ThinLTO LTOUnit"));
110 
111 static cl::opt<std::string> ThinLinkBitcodeFile(
112     "thin-link-bitcode-file", cl::value_desc("filename"),
113     cl::desc(
114         "A file in which to write minimized bitcode for the thin link only"));
115 
116 static cl::opt<bool>
117 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
118 
119 static cl::opt<bool>
120 VerifyEach("verify-each", cl::desc("Verify after each transform"));
121 
122 static cl::opt<bool>
123     DisableDITypeMap("disable-debug-info-type-map",
124                      cl::desc("Don't use a uniquing type map for debug info"));
125 
126 static cl::opt<bool>
127 StripDebug("strip-debug",
128            cl::desc("Strip debugger symbol info from translation unit"));
129 
130 static cl::opt<bool>
131     StripNamedMetadata("strip-named-metadata",
132                        cl::desc("Strip module-level named metadata"));
133 
134 static cl::opt<bool> DisableInline("disable-inlining",
135                                    cl::desc("Do not run the inliner pass"));
136 
137 static cl::opt<bool>
138 DisableOptimizations("disable-opt",
139                      cl::desc("Do not run any optimization passes"));
140 
141 static cl::opt<bool>
142 StandardLinkOpts("std-link-opts",
143                  cl::desc("Include the standard link time optimizations"));
144 
145 static cl::opt<bool>
146 OptLevelO0("O0",
147   cl::desc("Optimization level 0. Similar to clang -O0"));
148 
149 static cl::opt<bool>
150 OptLevelO1("O1",
151            cl::desc("Optimization level 1. Similar to clang -O1"));
152 
153 static cl::opt<bool>
154 OptLevelO2("O2",
155            cl::desc("Optimization level 2. Similar to clang -O2"));
156 
157 static cl::opt<bool>
158 OptLevelOs("Os",
159            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
160 
161 static cl::opt<bool>
162 OptLevelOz("Oz",
163            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
164 
165 static cl::opt<bool>
166 OptLevelO3("O3",
167            cl::desc("Optimization level 3. Similar to clang -O3"));
168 
169 static cl::opt<unsigned>
170 CodeGenOptLevel("codegen-opt-level",
171                 cl::desc("Override optimization level for codegen hooks"));
172 
173 static cl::opt<std::string>
174 TargetTriple("mtriple", cl::desc("Override target triple for module"));
175 
176 static cl::opt<bool>
177 DisableLoopUnrolling("disable-loop-unrolling",
178                      cl::desc("Disable loop unrolling in all relevant passes"),
179                      cl::init(false));
180 
181 static cl::opt<bool>
182 DisableSLPVectorization("disable-slp-vectorization",
183                         cl::desc("Disable the slp vectorization pass"),
184                         cl::init(false));
185 
186 static cl::opt<bool> EmitSummaryIndex("module-summary",
187                                       cl::desc("Emit module summary index"),
188                                       cl::init(false));
189 
190 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
191                                     cl::init(false));
192 
193 static cl::opt<bool>
194 DisableSimplifyLibCalls("disable-simplify-libcalls",
195                         cl::desc("Disable simplify-libcalls"));
196 
197 static cl::list<std::string>
198 DisableBuiltins("disable-builtin",
199                 cl::desc("Disable specific target library builtin function"),
200                 cl::ZeroOrMore);
201 
202 
203 static cl::opt<bool>
204 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
205 
206 static cl::alias
207 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
208 
209 static cl::opt<bool>
210 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
211 
212 static cl::opt<bool> EnableDebugify(
213     "enable-debugify",
214     cl::desc(
215         "Start the pipeline with debugify and end it with check-debugify"));
216 
217 static cl::opt<bool> DebugifyEach(
218     "debugify-each",
219     cl::desc(
220         "Start each pass with debugify and end it with check-debugify"));
221 
222 static cl::opt<std::string>
223     DebugifyExport("debugify-export",
224                    cl::desc("Export per-pass debugify statistics to this file"),
225                    cl::value_desc("filename"), cl::init(""));
226 
227 static cl::opt<bool>
228 PrintBreakpoints("print-breakpoints-for-testing",
229                  cl::desc("Print select breakpoints location for testing"));
230 
231 static cl::opt<std::string> ClDataLayout("data-layout",
232                                          cl::desc("data layout string to use"),
233                                          cl::value_desc("layout-string"),
234                                          cl::init(""));
235 
236 static cl::opt<bool> PreserveBitcodeUseListOrder(
237     "preserve-bc-uselistorder",
238     cl::desc("Preserve use-list order when writing LLVM bitcode."),
239     cl::init(true), cl::Hidden);
240 
241 static cl::opt<bool> PreserveAssemblyUseListOrder(
242     "preserve-ll-uselistorder",
243     cl::desc("Preserve use-list order when writing LLVM assembly."),
244     cl::init(false), cl::Hidden);
245 
246 static cl::opt<bool>
247     RunTwice("run-twice",
248              cl::desc("Run all passes twice, re-using the same pass manager."),
249              cl::init(false), cl::Hidden);
250 
251 static cl::opt<bool> DiscardValueNames(
252     "discard-value-names",
253     cl::desc("Discard names from Value (other than GlobalValue)."),
254     cl::init(false), cl::Hidden);
255 
256 static cl::opt<bool> Coroutines(
257   "enable-coroutines",
258   cl::desc("Enable coroutine passes."),
259   cl::init(false), cl::Hidden);
260 
261 static cl::opt<bool> TimeTrace(
262     "time-trace",
263     cl::desc("Record time trace"));
264 
265 static cl::opt<unsigned> TimeTraceGranularity(
266     "time-trace-granularity",
267     cl::desc("Minimum time granularity (in microseconds) traced by time profiler"),
268     cl::init(500), cl::Hidden);
269 
270 static cl::opt<std::string>
271     TimeTraceFile("time-trace-file",
272                     cl::desc("Specify time trace file destination"),
273                     cl::value_desc("filename"));
274 
275 static cl::opt<bool> RemarksWithHotness(
276     "pass-remarks-with-hotness",
277     cl::desc("With PGO, include profile count in optimization remarks"),
278     cl::Hidden);
279 
280 static cl::opt<unsigned>
281     RemarksHotnessThreshold("pass-remarks-hotness-threshold",
282                             cl::desc("Minimum profile count required for "
283                                      "an optimization remark to be output"),
284                             cl::Hidden);
285 
286 static cl::opt<std::string>
287     RemarksFilename("pass-remarks-output",
288                     cl::desc("Output filename for pass remarks"),
289                     cl::value_desc("filename"));
290 
291 static cl::opt<std::string>
292     RemarksPasses("pass-remarks-filter",
293                   cl::desc("Only record optimization remarks from passes whose "
294                            "names match the given regular expression"),
295                   cl::value_desc("regex"));
296 
297 static cl::opt<std::string> RemarksFormat(
298     "pass-remarks-format",
299     cl::desc("The format used for serializing remarks (default: YAML)"),
300     cl::value_desc("format"), cl::init("yaml"));
301 
302 cl::opt<PGOKind>
303     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
304                 cl::desc("The kind of profile guided optimization"),
305                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
306                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
307                                       "Instrument the IR to generate profile."),
308                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
309                                       "Use instrumented profile to guide PGO."),
310                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
311                                       "Use sampled profile to guide PGO.")));
312 cl::opt<std::string> ProfileFile("profile-file",
313                                  cl::desc("Path to the profile."), cl::Hidden);
314 
315 cl::opt<CSPGOKind> CSPGOKindFlag(
316     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
317     cl::desc("The kind of context sensitive profile guided optimization"),
318     cl::values(
319         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
320         clEnumValN(
321             CSInstrGen, "cspgo-instr-gen-pipeline",
322             "Instrument (context sensitive) the IR to generate profile."),
323         clEnumValN(
324             CSInstrUse, "cspgo-instr-use-pipeline",
325             "Use instrumented (context sensitive) profile to guide PGO.")));
326 cl::opt<std::string> CSProfileGenFile(
327     "cs-profilegen-file",
328     cl::desc("Path to the instrumented context sensitive profile."),
329     cl::Hidden);
330 
331 class OptCustomPassManager : public legacy::PassManager {
332   DebugifyStatsMap DIStatsMap;
333 
334 public:
335   using super = legacy::PassManager;
336 
337   void add(Pass *P) override {
338     // Wrap each pass with (-check)-debugify passes if requested, making
339     // exceptions for passes which shouldn't see -debugify instrumentation.
340     bool WrapWithDebugify = DebugifyEach && !P->getAsImmutablePass() &&
341                             !isIRPrintingPass(P) && !isBitcodeWriterPass(P);
342     if (!WrapWithDebugify) {
343       super::add(P);
344       return;
345     }
346 
347     // Apply -debugify/-check-debugify before/after each pass and collect
348     // debug info loss statistics.
349     PassKind Kind = P->getPassKind();
350     StringRef Name = P->getPassName();
351 
352     // TODO: Implement Debugify for LoopPass.
353     switch (Kind) {
354       case PT_Function:
355         super::add(createDebugifyFunctionPass());
356         super::add(P);
357         super::add(createCheckDebugifyFunctionPass(true, Name, &DIStatsMap));
358         break;
359       case PT_Module:
360         super::add(createDebugifyModulePass());
361         super::add(P);
362         super::add(createCheckDebugifyModulePass(true, Name, &DIStatsMap));
363         break;
364       default:
365         super::add(P);
366         break;
367     }
368   }
369 
370   const DebugifyStatsMap &getDebugifyStatsMap() const { return DIStatsMap; }
371 };
372 
373 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
374   // Add the pass to the pass manager...
375   PM.add(P);
376 
377   // If we are verifying all of the intermediate steps, add the verifier...
378   if (VerifyEach)
379     PM.add(createVerifierPass());
380 }
381 
382 /// This routine adds optimization passes based on selected optimization level,
383 /// OptLevel.
384 ///
385 /// OptLevel - Optimization Level
386 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
387                                   legacy::FunctionPassManager &FPM,
388                                   TargetMachine *TM, unsigned OptLevel,
389                                   unsigned SizeLevel) {
390   if (!NoVerify || VerifyEach)
391     FPM.add(createVerifierPass()); // Verify that input is correct
392 
393   PassManagerBuilder Builder;
394   Builder.OptLevel = OptLevel;
395   Builder.SizeLevel = SizeLevel;
396 
397   if (DisableInline) {
398     // No inlining pass
399   } else if (OptLevel > 1) {
400     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
401   } else {
402     Builder.Inliner = createAlwaysInlinerLegacyPass();
403   }
404   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
405                                DisableLoopUnrolling : OptLevel == 0;
406 
407   // Check if vectorization is explicitly disabled via -vectorize-loops=false.
408   // The flag enables vectorization in the LoopVectorize pass, it is on by
409   // default, and if it was disabled, leave it disabled here.
410   // Another flag that exists: -loop-vectorize, controls adding the pass to the
411   // pass manager. If set, the pass is added, and there is no additional check
412   // here for it.
413   if (Builder.LoopVectorize)
414     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
415 
416   // When #pragma vectorize is on for SLP, do the same as above
417   Builder.SLPVectorize =
418       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
419 
420   if (TM)
421     TM->adjustPassManager(Builder);
422 
423   if (Coroutines)
424     addCoroutinePassesToExtensionPoints(Builder);
425 
426   switch (PGOKindFlag) {
427   case InstrGen:
428     Builder.EnablePGOInstrGen = true;
429     Builder.PGOInstrGen = ProfileFile;
430     break;
431   case InstrUse:
432     Builder.PGOInstrUse = ProfileFile;
433     break;
434   case SampleUse:
435     Builder.PGOSampleUse = ProfileFile;
436     break;
437   default:
438     break;
439   }
440 
441   switch (CSPGOKindFlag) {
442   case CSInstrGen:
443     Builder.EnablePGOCSInstrGen = true;
444     break;
445   case CSInstrUse:
446     Builder.EnablePGOCSInstrUse = true;
447     break;
448   default:
449     break;
450   }
451 
452   Builder.populateFunctionPassManager(FPM);
453   Builder.populateModulePassManager(MPM);
454 }
455 
456 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
457   PassManagerBuilder Builder;
458   Builder.VerifyInput = true;
459   if (DisableOptimizations)
460     Builder.OptLevel = 0;
461 
462   if (!DisableInline)
463     Builder.Inliner = createFunctionInliningPass();
464   Builder.populateLTOPassManager(PM);
465 }
466 
467 //===----------------------------------------------------------------------===//
468 // CodeGen-related helper functions.
469 //
470 
471 static CodeGenOpt::Level GetCodeGenOptLevel() {
472   if (CodeGenOptLevel.getNumOccurrences())
473     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
474   if (OptLevelO1)
475     return CodeGenOpt::Less;
476   if (OptLevelO2)
477     return CodeGenOpt::Default;
478   if (OptLevelO3)
479     return CodeGenOpt::Aggressive;
480   return CodeGenOpt::None;
481 }
482 
483 // Returns the TargetMachine instance or zero if no triple is provided.
484 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
485                                        StringRef FeaturesStr,
486                                        const TargetOptions &Options) {
487   std::string Error;
488   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
489                                                          Error);
490   // Some modules don't specify a triple, and this is okay.
491   if (!TheTarget) {
492     return nullptr;
493   }
494 
495   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
496                                         FeaturesStr, Options, getRelocModel(),
497                                         getCodeModel(), GetCodeGenOptLevel());
498 }
499 
500 #ifdef BUILD_EXAMPLES
501 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
502 #endif
503 
504 
505 void exportDebugifyStats(llvm::StringRef Path, const DebugifyStatsMap &Map) {
506   std::error_code EC;
507   raw_fd_ostream OS{Path, EC};
508   if (EC) {
509     errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
510     return;
511   }
512 
513   OS << "Pass Name" << ',' << "# of missing debug values" << ','
514      << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
515      << "Missing/Expected location ratio" << '\n';
516   for (const auto &Entry : Map) {
517     StringRef Pass = Entry.first;
518     DebugifyStatistics Stats = Entry.second;
519 
520     OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
521        << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
522        << Stats.getEmptyLocationRatio() << '\n';
523   }
524 }
525 
526 struct TimeTracerRAII {
527   TimeTracerRAII(StringRef ProgramName) {
528     if (TimeTrace)
529       timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName);
530   }
531   ~TimeTracerRAII() {
532     if (TimeTrace) {
533       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
534         handleAllErrors(std::move(E), [&](const StringError &SE) {
535           errs() << SE.getMessage() << "\n";
536         });
537         return;
538       }
539       timeTraceProfilerCleanup();
540     }
541   }
542 };
543 
544 //===----------------------------------------------------------------------===//
545 // main for opt
546 //
547 int main(int argc, char **argv) {
548   InitLLVM X(argc, argv);
549 
550   // Enable debug stream buffering.
551   EnableDebugBuffering = true;
552 
553   LLVMContext Context;
554 
555   InitializeAllTargets();
556   InitializeAllTargetMCs();
557   InitializeAllAsmPrinters();
558   InitializeAllAsmParsers();
559 
560   // Initialize passes
561   PassRegistry &Registry = *PassRegistry::getPassRegistry();
562   initializeCore(Registry);
563   initializeCoroutines(Registry);
564   initializeScalarOpts(Registry);
565   initializeObjCARCOpts(Registry);
566   initializeVectorization(Registry);
567   initializeIPO(Registry);
568   initializeAnalysis(Registry);
569   initializeTransformUtils(Registry);
570   initializeInstCombine(Registry);
571   initializeAggressiveInstCombine(Registry);
572   initializeInstrumentation(Registry);
573   initializeTarget(Registry);
574   // For codegen passes, only passes that do IR to IR transformation are
575   // supported.
576   initializeExpandMemCmpPassPass(Registry);
577   initializeScalarizeMaskedMemIntrinPass(Registry);
578   initializeCodeGenPreparePass(Registry);
579   initializeAtomicExpandPass(Registry);
580   initializeRewriteSymbolsLegacyPassPass(Registry);
581   initializeWinEHPreparePass(Registry);
582   initializeDwarfEHPreparePass(Registry);
583   initializeSafeStackLegacyPassPass(Registry);
584   initializeSjLjEHPreparePass(Registry);
585   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
586   initializeGlobalMergePass(Registry);
587   initializeIndirectBrExpandPassPass(Registry);
588   initializeInterleavedLoadCombinePass(Registry);
589   initializeInterleavedAccessPass(Registry);
590   initializeEntryExitInstrumenterPass(Registry);
591   initializePostInlineEntryExitInstrumenterPass(Registry);
592   initializeUnreachableBlockElimLegacyPassPass(Registry);
593   initializeExpandReductionsPass(Registry);
594   initializeWasmEHPreparePass(Registry);
595   initializeWriteBitcodePassPass(Registry);
596   initializeHardwareLoopsPass(Registry);
597   initializeTypePromotionPass(Registry);
598 
599 #ifdef BUILD_EXAMPLES
600   initializeExampleIRTransforms(Registry);
601 #endif
602 
603   cl::ParseCommandLineOptions(argc, argv,
604     "llvm .bc -> .bc modular optimizer and analysis printer\n");
605 
606   if (AnalyzeOnly && NoOutput) {
607     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
608     return 1;
609   }
610 
611   TimeTracerRAII TimeTracer(argv[0]);
612 
613   SMDiagnostic Err;
614 
615   Context.setDiscardValueNames(DiscardValueNames);
616   if (!DisableDITypeMap)
617     Context.enableDebugTypeODRUniquing();
618 
619   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
620       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
621                                    RemarksFormat, RemarksWithHotness,
622                                    RemarksHotnessThreshold);
623   if (Error E = RemarksFileOrErr.takeError()) {
624     errs() << toString(std::move(E)) << '\n';
625     return 1;
626   }
627   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
628 
629   // Load the input module...
630   std::unique_ptr<Module> M =
631       parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout);
632 
633   if (!M) {
634     Err.print(argv[0], errs());
635     return 1;
636   }
637 
638   // Strip debug info before running the verifier.
639   if (StripDebug)
640     StripDebugInfo(*M);
641 
642   // Erase module-level named metadata, if requested.
643   if (StripNamedMetadata) {
644     while (!M->named_metadata_empty()) {
645       NamedMDNode *NMD = &*M->named_metadata_begin();
646       M->eraseNamedMetadata(NMD);
647     }
648   }
649 
650   // If we are supposed to override the target triple or data layout, do so now.
651   if (!TargetTriple.empty())
652     M->setTargetTriple(Triple::normalize(TargetTriple));
653 
654   // Immediately run the verifier to catch any problems before starting up the
655   // pass pipelines.  Otherwise we can crash on broken code during
656   // doInitialization().
657   if (!NoVerify && verifyModule(*M, &errs())) {
658     errs() << argv[0] << ": " << InputFilename
659            << ": error: input module is broken!\n";
660     return 1;
661   }
662 
663   // Enable testing of whole program devirtualization on this module by invoking
664   // the facility for updating public visibility to linkage unit visibility when
665   // specified by an internal option. This is normally done during LTO which is
666   // not performed via opt.
667   updateVCallVisibilityInModule(*M,
668                                 /* WholeProgramVisibilityEnabledInLTO */ false);
669 
670   // Figure out what stream we are supposed to write to...
671   std::unique_ptr<ToolOutputFile> Out;
672   std::unique_ptr<ToolOutputFile> ThinLinkOut;
673   if (NoOutput) {
674     if (!OutputFilename.empty())
675       errs() << "WARNING: The -o (output filename) option is ignored when\n"
676                 "the --disable-output option is used.\n";
677   } else {
678     // Default to standard output.
679     if (OutputFilename.empty())
680       OutputFilename = "-";
681 
682     std::error_code EC;
683     sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text
684                                               : sys::fs::OF_None;
685     Out.reset(new ToolOutputFile(OutputFilename, EC, Flags));
686     if (EC) {
687       errs() << EC.message() << '\n';
688       return 1;
689     }
690 
691     if (!ThinLinkBitcodeFile.empty()) {
692       ThinLinkOut.reset(
693           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None));
694       if (EC) {
695         errs() << EC.message() << '\n';
696         return 1;
697       }
698     }
699   }
700 
701   Triple ModuleTriple(M->getTargetTriple());
702   std::string CPUStr, FeaturesStr;
703   TargetMachine *Machine = nullptr;
704   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
705 
706   if (ModuleTriple.getArch()) {
707     CPUStr = getCPUStr();
708     FeaturesStr = getFeaturesStr();
709     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
710   } else if (ModuleTriple.getArchName() != "unknown" &&
711              ModuleTriple.getArchName() != "") {
712     errs() << argv[0] << ": unrecognized architecture '"
713            << ModuleTriple.getArchName() << "' provided.\n";
714     return 1;
715   }
716 
717   std::unique_ptr<TargetMachine> TM(Machine);
718 
719   // Override function attributes based on CPUStr, FeaturesStr, and command line
720   // flags.
721   setFunctionAttributes(CPUStr, FeaturesStr, *M);
722 
723   // If the output is set to be emitted to standard out, and standard out is a
724   // console, print out a warning message and refuse to do it.  We don't
725   // impress anyone by spewing tons of binary goo to a terminal.
726   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
727     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
728       NoOutput = true;
729 
730   if (OutputThinLTOBC)
731     M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
732 
733   if (PassPipeline.getNumOccurrences() > 0) {
734     OutputKind OK = OK_NoOutput;
735     if (!NoOutput)
736       OK = OutputAssembly
737                ? OK_OutputAssembly
738                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
739 
740     VerifierKind VK = VK_VerifyInAndOut;
741     if (NoVerify)
742       VK = VK_NoVerifier;
743     else if (VerifyEach)
744       VK = VK_VerifyEachPass;
745 
746     // The user has asked to use the new pass manager and provided a pipeline
747     // string. Hand off the rest of the functionality to the new code for that
748     // layer.
749     return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
750                            RemarksFile.get(), PassPipeline, OK, VK,
751                            PreserveAssemblyUseListOrder,
752                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
753                            EmitModuleHash, EnableDebugify, Coroutines)
754                ? 0
755                : 1;
756   }
757 
758   // Create a PassManager to hold and optimize the collection of passes we are
759   // about to build.
760   OptCustomPassManager Passes;
761   bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach;
762 
763   // Add an appropriate TargetLibraryInfo pass for the module's triple.
764   TargetLibraryInfoImpl TLII(ModuleTriple);
765 
766   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
767   if (DisableSimplifyLibCalls)
768     TLII.disableAllFunctions();
769   else {
770     // Disable individual builtin functions in TargetLibraryInfo.
771     LibFunc F;
772     for (auto &FuncName : DisableBuiltins)
773       if (TLII.getLibFunc(FuncName, F))
774         TLII.setUnavailable(F);
775       else {
776         errs() << argv[0] << ": cannot disable nonexistent builtin function "
777                << FuncName << '\n';
778         return 1;
779       }
780   }
781 
782   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
783 
784   // Add internal analysis passes from the target machine.
785   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
786                                                      : TargetIRAnalysis()));
787 
788   if (AddOneTimeDebugifyPasses)
789     Passes.add(createDebugifyModulePass());
790 
791   std::unique_ptr<legacy::FunctionPassManager> FPasses;
792   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
793       OptLevelO3) {
794     FPasses.reset(new legacy::FunctionPassManager(M.get()));
795     FPasses->add(createTargetTransformInfoWrapperPass(
796         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
797   }
798 
799   if (PrintBreakpoints) {
800     // Default to standard output.
801     if (!Out) {
802       if (OutputFilename.empty())
803         OutputFilename = "-";
804 
805       std::error_code EC;
806       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
807                                               sys::fs::OF_None);
808       if (EC) {
809         errs() << EC.message() << '\n';
810         return 1;
811       }
812     }
813     Passes.add(createBreakpointPrinter(Out->os()));
814     NoOutput = true;
815   }
816 
817   if (TM) {
818     // FIXME: We should dyn_cast this when supported.
819     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
820     Pass *TPC = LTM.createPassConfig(Passes);
821     Passes.add(TPC);
822   }
823 
824   // Create a new optimization pass for each one specified on the command line
825   for (unsigned i = 0; i < PassList.size(); ++i) {
826     if (StandardLinkOpts &&
827         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
828       AddStandardLinkPasses(Passes);
829       StandardLinkOpts = false;
830     }
831 
832     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
833       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
834       OptLevelO0 = false;
835     }
836 
837     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
838       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
839       OptLevelO1 = false;
840     }
841 
842     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
843       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
844       OptLevelO2 = false;
845     }
846 
847     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
848       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
849       OptLevelOs = false;
850     }
851 
852     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
853       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
854       OptLevelOz = false;
855     }
856 
857     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
858       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
859       OptLevelO3 = false;
860     }
861 
862     const PassInfo *PassInf = PassList[i];
863     Pass *P = nullptr;
864     if (PassInf->getNormalCtor())
865       P = PassInf->getNormalCtor()();
866     else
867       errs() << argv[0] << ": cannot create pass: "
868              << PassInf->getPassName() << "\n";
869     if (P) {
870       PassKind Kind = P->getPassKind();
871       addPass(Passes, P);
872 
873       if (AnalyzeOnly) {
874         switch (Kind) {
875         case PT_Region:
876           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
877           break;
878         case PT_Loop:
879           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
880           break;
881         case PT_Function:
882           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
883           break;
884         case PT_CallGraphSCC:
885           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
886           break;
887         default:
888           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
889           break;
890         }
891       }
892     }
893 
894     if (PrintEachXForm)
895       Passes.add(
896           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
897   }
898 
899   if (StandardLinkOpts) {
900     AddStandardLinkPasses(Passes);
901     StandardLinkOpts = false;
902   }
903 
904   if (OptLevelO0)
905     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
906 
907   if (OptLevelO1)
908     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
909 
910   if (OptLevelO2)
911     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
912 
913   if (OptLevelOs)
914     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
915 
916   if (OptLevelOz)
917     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
918 
919   if (OptLevelO3)
920     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
921 
922   if (FPasses) {
923     FPasses->doInitialization();
924     for (Function &F : *M)
925       FPasses->run(F);
926     FPasses->doFinalization();
927   }
928 
929   // Check that the module is well formed on completion of optimization
930   if (!NoVerify && !VerifyEach)
931     Passes.add(createVerifierPass());
932 
933   if (AddOneTimeDebugifyPasses)
934     Passes.add(createCheckDebugifyModulePass(false));
935 
936   // In run twice mode, we want to make sure the output is bit-by-bit
937   // equivalent if we run the pass manager again, so setup two buffers and
938   // a stream to write to them. Note that llc does something similar and it
939   // may be worth to abstract this out in the future.
940   SmallVector<char, 0> Buffer;
941   SmallVector<char, 0> FirstRunBuffer;
942   std::unique_ptr<raw_svector_ostream> BOS;
943   raw_ostream *OS = nullptr;
944 
945   const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly;
946 
947   // Write bitcode or assembly to the output as the last step...
948   if (ShouldEmitOutput || RunTwice) {
949     assert(Out);
950     OS = &Out->os();
951     if (RunTwice) {
952       BOS = std::make_unique<raw_svector_ostream>(Buffer);
953       OS = BOS.get();
954     }
955     if (OutputAssembly) {
956       if (EmitSummaryIndex)
957         report_fatal_error("Text output is incompatible with -module-summary");
958       if (EmitModuleHash)
959         report_fatal_error("Text output is incompatible with -module-hash");
960       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
961     } else if (OutputThinLTOBC)
962       Passes.add(createWriteThinLTOBitcodePass(
963           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
964     else
965       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
966                                          EmitSummaryIndex, EmitModuleHash));
967   }
968 
969   // Before executing passes, print the final values of the LLVM options.
970   cl::PrintOptionValues();
971 
972   if (!RunTwice) {
973     // Now that we have all of the passes ready, run them.
974     Passes.run(*M);
975   } else {
976     // If requested, run all passes twice with the same pass manager to catch
977     // bugs caused by persistent state in the passes.
978     std::unique_ptr<Module> M2(CloneModule(*M));
979     // Run all passes on the original module first, so the second run processes
980     // the clone to catch CloneModule bugs.
981     Passes.run(*M);
982     FirstRunBuffer = Buffer;
983     Buffer.clear();
984 
985     Passes.run(*M2);
986 
987     // Compare the two outputs and make sure they're the same
988     assert(Out);
989     if (Buffer.size() != FirstRunBuffer.size() ||
990         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
991       errs()
992           << "Running the pass manager twice changed the output.\n"
993              "Writing the result of the second run to the specified output.\n"
994              "To generate the one-run comparison binary, just run without\n"
995              "the compile-twice option\n";
996       if (ShouldEmitOutput) {
997         Out->os() << BOS->str();
998         Out->keep();
999       }
1000       if (RemarksFile)
1001         RemarksFile->keep();
1002       return 1;
1003     }
1004     if (ShouldEmitOutput)
1005       Out->os() << BOS->str();
1006   }
1007 
1008   if (DebugifyEach && !DebugifyExport.empty())
1009     exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
1010 
1011   // Declare success.
1012   if (!NoOutput || PrintBreakpoints)
1013     Out->keep();
1014 
1015   if (RemarksFile)
1016     RemarksFile->keep();
1017 
1018   if (ThinLinkOut)
1019     ThinLinkOut->keep();
1020 
1021   return 0;
1022 }
1023