opt.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. #include "BreakpointPrinter.h"
  15. #include "NewPMDriver.h"
  16. #include "llvm/PassPrinters/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.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DebugInfo.h"
  28. #include "llvm/IR/IRPrintingPasses.h"
  29. #include "llvm/IR/LLVMContext.h"
  30. #include "llvm/IR/LegacyPassNameParser.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Verifier.h"
  33. #include "llvm/IRReader/IRReader.h"
  34. #include "llvm/InitializePasses.h"
  35. #include "llvm/LinkAllIR.h"
  36. #include "llvm/LinkAllPasses.h"
  37. #include "llvm/MC/SubtargetFeature.h"
  38. #include "llvm/IR/LegacyPassManager.h"
  39. #include "llvm/Support/Debug.h"
  40. #include "llvm/Support/FileSystem.h"
  41. #include "llvm/Support/Host.h"
  42. #include "llvm/Support/ManagedStatic.h"
  43. #include "llvm/Support/PluginLoader.h"
  44. #include "llvm/Support/PrettyStackTrace.h"
  45. #include "llvm/Support/Signals.h"
  46. #include "llvm/Support/SourceMgr.h"
  47. #include "llvm/Support/SystemUtils.h"
  48. #include "llvm/Support/TargetRegistry.h"
  49. #include "llvm/Support/TargetSelect.h"
  50. #include "llvm/Support/ToolOutputFile.h"
  51. #include "llvm/Target/TargetMachine.h"
  52. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  53. // HLSL Change Starts
  54. #include "dxc/Support/Global.h"
  55. #include "llvm/Analysis/ReducibilityAnalysis.h"
  56. #include "dxc/Support/WinIncludes.h"
  57. #include "llvm/Support/MSFileSystem.h"
  58. // HLSL Change Ends
  59. #include <algorithm>
  60. #include <memory>
  61. using namespace llvm;
  62. using namespace opt_tool;
  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. // This flag specifies a textual description of the optimization pass pipeline
  69. // to run over the module. This flag switches opt to use the new pass manager
  70. // infrastructure, completely disabling all of the flags specific to the old
  71. // pass management.
  72. static cl::opt<std::string> PassPipeline(
  73. "passes",
  74. cl::desc("A textual description of the pass pipeline for optimizing"),
  75. cl::Hidden);
  76. // Other command line options...
  77. //
  78. static cl::opt<std::string>
  79. InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
  80. cl::init("-"), cl::value_desc("filename"));
  81. static cl::opt<std::string>
  82. OutputFilename("o", cl::desc("Override output filename"),
  83. cl::value_desc("filename"));
  84. static cl::opt<bool>
  85. Force("f", cl::desc("Enable binary output on terminals"));
  86. static cl::opt<bool>
  87. PrintEachXForm("p", cl::desc("Print module after each transformation"));
  88. static cl::opt<bool>
  89. NoOutput("disable-output",
  90. cl::desc("Do not write result bitcode file"), cl::Hidden);
  91. static cl::opt<bool>
  92. OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
  93. static cl::opt<bool>
  94. NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
  95. static cl::opt<bool>
  96. VerifyEach("verify-each", cl::desc("Verify after each transform"));
  97. static cl::opt<bool>
  98. StripDebug("strip-debug",
  99. cl::desc("Strip debugger symbol info from translation unit"));
  100. static cl::opt<bool>
  101. DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
  102. static cl::opt<bool>
  103. DisableOptimizations("disable-opt",
  104. cl::desc("Do not run any optimization passes"));
  105. static cl::opt<bool>
  106. StandardLinkOpts("std-link-opts",
  107. cl::desc("Include the standard link time optimizations"));
  108. static cl::opt<bool>
  109. OptLevelO1("O1",
  110. cl::desc("Optimization level 1. Similar to clang -O1"));
  111. static cl::opt<bool>
  112. OptLevelO2("O2",
  113. cl::desc("Optimization level 2. Similar to clang -O2"));
  114. static cl::opt<bool>
  115. OptLevelOs("Os",
  116. cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
  117. static cl::opt<bool>
  118. OptLevelOz("Oz",
  119. cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
  120. static cl::opt<bool>
  121. OptLevelO3("O3",
  122. cl::desc("Optimization level 3. Similar to clang -O3"));
  123. static cl::opt<std::string>
  124. TargetTriple("mtriple", cl::desc("Override target triple for module"));
  125. static cl::opt<bool>
  126. UnitAtATime("funit-at-a-time",
  127. cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
  128. cl::init(true));
  129. static cl::opt<bool>
  130. DisableLoopUnrolling("disable-loop-unrolling",
  131. cl::desc("Disable loop unrolling in all relevant passes"),
  132. cl::init(false));
  133. static cl::opt<bool>
  134. DisableLoopVectorization("disable-loop-vectorization",
  135. cl::desc("Disable the loop vectorization pass"),
  136. cl::init(false));
  137. static cl::opt<bool>
  138. DisableSLPVectorization("disable-slp-vectorization",
  139. cl::desc("Disable the slp vectorization pass"),
  140. cl::init(false));
  141. static cl::opt<bool>
  142. DisableSimplifyLibCalls("disable-simplify-libcalls",
  143. cl::desc("Disable simplify-libcalls"));
  144. static cl::opt<bool>
  145. Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
  146. static cl::alias
  147. QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
  148. static cl::opt<bool>
  149. AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
  150. static cl::opt<bool>
  151. PrintBreakpoints("print-breakpoints-for-testing",
  152. cl::desc("Print select breakpoints location for testing"));
  153. static cl::opt<std::string>
  154. DefaultDataLayout("default-data-layout",
  155. cl::desc("data layout string to use if not specified by module"),
  156. cl::value_desc("layout-string"), cl::init(""));
  157. static cl::opt<bool> PreserveBitcodeUseListOrder(
  158. "preserve-bc-uselistorder",
  159. cl::desc("Preserve use-list order when writing LLVM bitcode."),
  160. cl::init(true), cl::Hidden);
  161. static cl::opt<bool> PreserveAssemblyUseListOrder(
  162. "preserve-ll-uselistorder",
  163. cl::desc("Preserve use-list order when writing LLVM assembly."),
  164. cl::init(false), cl::Hidden);
  165. static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
  166. // Add the pass to the pass manager...
  167. PM.add(P);
  168. // If we are verifying all of the intermediate steps, add the verifier...
  169. if (VerifyEach)
  170. PM.add(createVerifierPass());
  171. }
  172. /// This routine adds optimization passes based on selected optimization level,
  173. /// OptLevel.
  174. ///
  175. /// OptLevel - Optimization Level
  176. static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
  177. legacy::FunctionPassManager &FPM,
  178. unsigned OptLevel, unsigned SizeLevel) {
  179. FPM.add(createVerifierPass()); // Verify that input is correct
  180. PassManagerBuilder Builder;
  181. Builder.OptLevel = OptLevel;
  182. Builder.SizeLevel = SizeLevel;
  183. if (DisableInline) {
  184. // No inlining pass
  185. } else if (OptLevel > 1) {
  186. Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
  187. } else {
  188. Builder.Inliner = createAlwaysInlinerPass();
  189. }
  190. Builder.DisableUnitAtATime = !UnitAtATime;
  191. Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
  192. DisableLoopUnrolling : OptLevel == 0;
  193. // This is final, unless there is a #pragma vectorize enable
  194. if (DisableLoopVectorization)
  195. Builder.LoopVectorize = false;
  196. // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
  197. else if (!Builder.LoopVectorize)
  198. Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
  199. // When #pragma vectorize is on for SLP, do the same as above
  200. Builder.SLPVectorize =
  201. DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
  202. Builder.populateFunctionPassManager(FPM);
  203. Builder.populateModulePassManager(MPM);
  204. }
  205. static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
  206. PassManagerBuilder Builder;
  207. Builder.VerifyInput = true;
  208. if (DisableOptimizations)
  209. Builder.OptLevel = 0;
  210. if (!DisableInline)
  211. Builder.Inliner = createFunctionInliningPass();
  212. Builder.populateLTOPassManager(PM);
  213. }
  214. //===----------------------------------------------------------------------===//
  215. // CodeGen-related helper functions.
  216. //
  217. static CodeGenOpt::Level GetCodeGenOptLevel() {
  218. if (OptLevelO1)
  219. return CodeGenOpt::Less;
  220. if (OptLevelO2)
  221. return CodeGenOpt::Default;
  222. if (OptLevelO3)
  223. return CodeGenOpt::Aggressive;
  224. return CodeGenOpt::None;
  225. }
  226. // Returns the TargetMachine instance or zero if no triple is provided.
  227. static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
  228. StringRef FeaturesStr,
  229. const TargetOptions &Options) {
  230. std::string Error;
  231. const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
  232. Error);
  233. // Some modules don't specify a triple, and this is okay.
  234. if (!TheTarget) {
  235. return nullptr;
  236. }
  237. return TheTarget->createTargetMachine(TheTriple.getTriple(),
  238. CPUStr, FeaturesStr, Options,
  239. RelocModel, CMModel,
  240. GetCodeGenOptLevel());
  241. }
  242. #ifdef LINK_POLLY_INTO_TOOLS
  243. namespace polly {
  244. void initializePollyPasses(llvm::PassRegistry &Registry);
  245. }
  246. #endif
  247. // HLSL Change Start
  248. void __cdecl initializeDxilConvPasses(llvm::PassRegistry &);
  249. // HLSL Change End
  250. //===----------------------------------------------------------------------===//
  251. // main for opt
  252. //
  253. // HLSL Change: changed calling convention to __cdecl
  254. int __cdecl main(int argc, char **argv) {
  255. // HLSL Change Starts
  256. if (llvm::sys::fs::SetupPerThreadFileSystem())
  257. return 1;
  258. llvm::sys::fs::AutoCleanupPerThreadFileSystem auto_cleanup_fs;
  259. if (FAILED(DxcInitThreadMalloc())) return 1;
  260. DxcSetThreadMallocToDefault();
  261. llvm::sys::fs::MSFileSystem* msfPtr;
  262. if (FAILED(CreateMSFileSystemForDisk(&msfPtr))) return 1;
  263. std::unique_ptr<llvm::sys::fs::MSFileSystem> msf(msfPtr);
  264. llvm::sys::fs::AutoPerThreadSystem pts(msf.get());
  265. //llvm::STDStreamCloser stdStreamCloser;
  266. // HLSL Change Ends
  267. //sys::PrintStackTraceOnErrorSignal(); // HLSL Change
  268. //llvm::PrettyStackTraceProgram X(argc, argv); // HLSL Change
  269. // Enable debug stream buffering.
  270. EnableDebugBuffering = true;
  271. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  272. LLVMContext &Context = getGlobalContext();
  273. InitializeAllTargets();
  274. // InitializeAllTargetMCs(); // HLSL Change: remove MC targets
  275. InitializeAllAsmPrinters();
  276. // Initialize passes
  277. PassRegistry &Registry = *PassRegistry::getPassRegistry();
  278. initializeCore(Registry);
  279. initializeScalarOpts(Registry);
  280. initializeReducibilityAnalysisPass(Registry); // HLSL Change: add ReducibilityAnalysis pass
  281. // initializeObjCARCOpts(Registry); // HLSL Change: remove ObjC ARC passes
  282. // initializeVectorization(Registry); // HLSL Change: remove vectorization passes
  283. initializeIPO(Registry);
  284. initializeAnalysis(Registry);
  285. initializeIPA(Registry);
  286. initializeTransformUtils(Registry);
  287. initializeInstCombine(Registry);
  288. // initializeInstrumentation(Registry); // HLSL Change: remove instrumentation
  289. initializeTarget(Registry);
  290. // For codegen passes, only passes that do IR to IR transformation are
  291. // supported.
  292. // initializeCodeGenPreparePass(Registry); // HLSL Change: remove EH passes
  293. //initializeAtomicExpandPass(Registry); // HLSL Change: remove EH passes
  294. initializeRewriteSymbolsPass(Registry);
  295. //initializeWinEHPreparePass(Registry); // HLSL Change: remove EH passes
  296. //initializeDwarfEHPreparePass(Registry); // HLSL Change: remove EH passes
  297. //initializeSjLjEHPreparePass(Registry); // HLSL Change: remove EH passes
  298. // HLSL Change Starts
  299. initializeReducibilityAnalysisPass(Registry);
  300. #ifdef _WIN32
  301. initializeDxilConvPasses(Registry);
  302. #endif
  303. // HLSL Change Ends
  304. #ifdef LINK_POLLY_INTO_TOOLS
  305. polly::initializePollyPasses(Registry);
  306. #endif
  307. cl::ParseCommandLineOptions(argc, argv,
  308. "llvm .bc -> .bc modular optimizer and analysis printer\n");
  309. if (AnalyzeOnly && NoOutput) {
  310. errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
  311. return 1;
  312. }
  313. SMDiagnostic Err;
  314. // Load the input module...
  315. std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
  316. if (!M) {
  317. Err.print(argv[0], errs());
  318. return 1;
  319. }
  320. // Strip debug info before running the verifier.
  321. if (StripDebug)
  322. StripDebugInfo(*M);
  323. // Immediately run the verifier to catch any problems before starting up the
  324. // pass pipelines. Otherwise we can crash on broken code during
  325. // doInitialization().
  326. if (!NoVerify && verifyModule(*M, &errs())) {
  327. errs() << argv[0] << ": " << InputFilename
  328. << ": error: input module is broken!\n";
  329. return 1;
  330. }
  331. // If we are supposed to override the target triple, do so now.
  332. if (!TargetTriple.empty())
  333. M->setTargetTriple(Triple::normalize(TargetTriple));
  334. // Figure out what stream we are supposed to write to...
  335. std::unique_ptr<tool_output_file> Out;
  336. if (NoOutput) {
  337. if (!OutputFilename.empty())
  338. errs() << "WARNING: The -o (output filename) option is ignored when\n"
  339. "the --disable-output option is used.\n";
  340. } else {
  341. // Default to standard output.
  342. if (OutputFilename.empty())
  343. OutputFilename = "-";
  344. std::error_code EC;
  345. Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
  346. if (EC) {
  347. errs() << EC.message() << '\n';
  348. return 1;
  349. }
  350. }
  351. Triple ModuleTriple(M->getTargetTriple());
  352. std::string CPUStr, FeaturesStr;
  353. TargetMachine *Machine = nullptr;
  354. const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
  355. if (ModuleTriple.getArch()) {
  356. CPUStr = getCPUStr();
  357. FeaturesStr = getFeaturesStr();
  358. Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
  359. }
  360. std::unique_ptr<TargetMachine> TM(Machine);
  361. // Override function attributes based on CPUStr, FeaturesStr, and command line
  362. // flags.
  363. setFunctionAttributes(CPUStr, FeaturesStr, *M);
  364. // If the output is set to be emitted to standard out, and standard out is a
  365. // console, print out a warning message and refuse to do it. We don't
  366. // impress anyone by spewing tons of binary goo to a terminal.
  367. if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
  368. if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
  369. NoOutput = true;
  370. if (PassPipeline.getNumOccurrences() > 0) {
  371. OutputKind OK = OK_NoOutput;
  372. if (!NoOutput)
  373. OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
  374. VerifierKind VK = VK_VerifyInAndOut;
  375. if (NoVerify)
  376. VK = VK_NoVerifier;
  377. else if (VerifyEach)
  378. VK = VK_VerifyEachPass;
  379. // The user has asked to use the new pass manager and provided a pipeline
  380. // string. Hand off the rest of the functionality to the new code for that
  381. // layer.
  382. return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
  383. PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
  384. PreserveBitcodeUseListOrder)
  385. ? 0
  386. : 1;
  387. }
  388. // Create a PassManager to hold and optimize the collection of passes we are
  389. // about to build.
  390. //
  391. legacy::PassManager Passes;
  392. // Add an appropriate TargetLibraryInfo pass for the module's triple.
  393. TargetLibraryInfoImpl TLII(ModuleTriple);
  394. // The -disable-simplify-libcalls flag actually disables all builtin optzns.
  395. if (DisableSimplifyLibCalls)
  396. TLII.disableAllFunctions();
  397. Passes.add(new TargetLibraryInfoWrapperPass(TLII));
  398. // Add an appropriate DataLayout instance for this module.
  399. const DataLayout &DL = M->getDataLayout();
  400. if (DL.isDefault() && !DefaultDataLayout.empty()) {
  401. M->setDataLayout(DefaultDataLayout);
  402. }
  403. // Add internal analysis passes from the target machine.
  404. Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
  405. : TargetIRAnalysis()));
  406. std::unique_ptr<legacy::FunctionPassManager> FPasses;
  407. if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
  408. FPasses.reset(new legacy::FunctionPassManager(M.get()));
  409. FPasses->add(createTargetTransformInfoWrapperPass(
  410. TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
  411. }
  412. if (PrintBreakpoints) {
  413. // Default to standard output.
  414. if (!Out) {
  415. if (OutputFilename.empty())
  416. OutputFilename = "-";
  417. std::error_code EC;
  418. Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
  419. sys::fs::F_None);
  420. if (EC) {
  421. errs() << EC.message() << '\n';
  422. return 1;
  423. }
  424. }
  425. Passes.add(createBreakpointPrinter(Out->os()));
  426. NoOutput = true;
  427. }
  428. // Create a new optimization pass for each one specified on the command line
  429. for (unsigned i = 0; i < PassList.size(); ++i) {
  430. if (StandardLinkOpts &&
  431. StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
  432. AddStandardLinkPasses(Passes);
  433. StandardLinkOpts = false;
  434. }
  435. if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
  436. AddOptimizationPasses(Passes, *FPasses, 1, 0);
  437. OptLevelO1 = false;
  438. }
  439. if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
  440. AddOptimizationPasses(Passes, *FPasses, 2, 0);
  441. OptLevelO2 = false;
  442. }
  443. if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
  444. AddOptimizationPasses(Passes, *FPasses, 2, 1);
  445. OptLevelOs = false;
  446. }
  447. if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
  448. AddOptimizationPasses(Passes, *FPasses, 2, 2);
  449. OptLevelOz = false;
  450. }
  451. if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
  452. AddOptimizationPasses(Passes, *FPasses, 3, 0);
  453. OptLevelO3 = false;
  454. }
  455. const PassInfo *PassInf = PassList[i];
  456. Pass *P = nullptr;
  457. if (PassInf->getTargetMachineCtor())
  458. P = PassInf->getTargetMachineCtor()(TM.get());
  459. else if (PassInf->getNormalCtor())
  460. P = PassInf->getNormalCtor()();
  461. else
  462. errs() << argv[0] << ": cannot create pass: "
  463. << PassInf->getPassName() << "\n";
  464. if (P) {
  465. PassKind Kind = P->getPassKind();
  466. addPass(Passes, P);
  467. if (AnalyzeOnly) {
  468. switch (Kind) {
  469. case PT_BasicBlock:
  470. Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
  471. break;
  472. case PT_Region:
  473. Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
  474. break;
  475. case PT_Loop:
  476. Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
  477. break;
  478. case PT_Function:
  479. Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
  480. break;
  481. case PT_CallGraphSCC:
  482. Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
  483. break;
  484. default:
  485. Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
  486. break;
  487. }
  488. }
  489. }
  490. if (PrintEachXForm)
  491. Passes.add(
  492. createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
  493. }
  494. if (StandardLinkOpts) {
  495. AddStandardLinkPasses(Passes);
  496. StandardLinkOpts = false;
  497. }
  498. if (OptLevelO1)
  499. AddOptimizationPasses(Passes, *FPasses, 1, 0);
  500. if (OptLevelO2)
  501. AddOptimizationPasses(Passes, *FPasses, 2, 0);
  502. if (OptLevelOs)
  503. AddOptimizationPasses(Passes, *FPasses, 2, 1);
  504. if (OptLevelOz)
  505. AddOptimizationPasses(Passes, *FPasses, 2, 2);
  506. if (OptLevelO3)
  507. AddOptimizationPasses(Passes, *FPasses, 3, 0);
  508. if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
  509. FPasses->doInitialization();
  510. for (Function &F : *M)
  511. FPasses->run(F);
  512. FPasses->doFinalization();
  513. }
  514. // Check that the module is well formed on completion of optimization
  515. if (!NoVerify && !VerifyEach)
  516. Passes.add(createVerifierPass());
  517. // Write bitcode or assembly to the output as the last step...
  518. if (!NoOutput && !AnalyzeOnly) {
  519. if (OutputAssembly)
  520. Passes.add(
  521. createPrintModulePass(Out->os(), "", PreserveAssemblyUseListOrder));
  522. else
  523. Passes.add(
  524. createBitcodeWriterPass(Out->os(), PreserveBitcodeUseListOrder));
  525. }
  526. // Before executing passes, print the final values of the LLVM options.
  527. cl::PrintOptionValues();
  528. // Now that we have all of the passes ready, run them.
  529. // HLSL Change Starts - wrap in try-catch
  530. try {
  531. Passes.run(*M);
  532. }
  533. catch(...) {
  534. exit(1);
  535. }
  536. // HLSL Change Ends
  537. // Declare success.
  538. if (!NoOutput || PrintBreakpoints)
  539. Out->keep();
  540. return 0;
  541. }