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