PassManagerBuilder.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===//
  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. // This file defines the PassManagerBuilder class, which is used to set up a
  11. // "standard" optimization sequence suitable for languages like C and C++.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/Transforms/IPO/PassManagerBuilder.h"
  15. #include "llvm-c/Transforms/PassManagerBuilder.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Analysis/Passes.h"
  18. #include "llvm/IR/DataLayout.h"
  19. #include "llvm/IR/Verifier.h"
  20. #include "llvm/IR/LegacyPassManager.h"
  21. #include "llvm/Support/CommandLine.h"
  22. #include "llvm/Support/ManagedStatic.h"
  23. #include "llvm/Analysis/TargetLibraryInfo.h"
  24. #include "llvm/Target/TargetMachine.h"
  25. #include "llvm/Transforms/IPO.h"
  26. #include "llvm/Transforms/Scalar.h"
  27. #include "llvm/Transforms/Vectorize.h"
  28. #include "dxc/HLSL/DxilGenerationPass.h" // HLSL Change
  29. #include "dxc/HLSL/HLMatrixLowerPass.h" // HLSL Change
  30. #include "dxc/HLSL/ComputeViewIdState.h" // HLSL Change
  31. using namespace llvm;
  32. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  33. static cl::opt<bool>
  34. RunLoopVectorization("vectorize-loops", cl::Hidden,
  35. cl::desc("Run the Loop vectorization passes"));
  36. static cl::opt<bool>
  37. RunSLPVectorization("vectorize-slp", cl::Hidden,
  38. cl::desc("Run the SLP vectorization passes"));
  39. static cl::opt<bool>
  40. RunBBVectorization("vectorize-slp-aggressive", cl::Hidden,
  41. cl::desc("Run the BB vectorization passes"));
  42. static cl::opt<bool>
  43. UseGVNAfterVectorization("use-gvn-after-vectorization",
  44. cl::init(false), cl::Hidden,
  45. cl::desc("Run GVN instead of Early CSE after vectorization passes"));
  46. static cl::opt<bool> ExtraVectorizerPasses(
  47. "extra-vectorizer-passes", cl::init(false), cl::Hidden,
  48. cl::desc("Run cleanup optimization passes after vectorization."));
  49. #else
  50. // Don't declare the 'false' counterparts - simply avoid altogether.
  51. #endif // HLSL Change - don't build vectorization passes
  52. static cl::opt<bool> UseNewSROA("use-new-sroa",
  53. cl::init(true), cl::Hidden,
  54. cl::desc("Enable the new, experimental SROA pass"));
  55. static cl::opt<bool>
  56. RunLoopRerolling("reroll-loops", cl::Hidden,
  57. cl::desc("Run the loop rerolling pass"));
  58. static cl::opt<bool>
  59. RunFloat2Int("float-to-int", cl::Hidden, cl::init(true),
  60. cl::desc("Run the float2int (float demotion) pass"));
  61. static cl::opt<bool> RunLoadCombine("combine-loads", cl::init(false),
  62. cl::Hidden,
  63. cl::desc("Run the load combining pass"));
  64. static cl::opt<bool>
  65. RunSLPAfterLoopVectorization("run-slp-after-loop-vectorization",
  66. cl::init(true), cl::Hidden,
  67. cl::desc("Run the SLP vectorizer (and BB vectorizer) after the Loop "
  68. "vectorizer instead of before"));
  69. static cl::opt<bool> UseCFLAA("use-cfl-aa",
  70. cl::init(false), cl::Hidden,
  71. cl::desc("Enable the new, experimental CFL alias analysis"));
  72. static cl::opt<bool>
  73. EnableMLSM("mlsm", cl::init(true), cl::Hidden,
  74. cl::desc("Enable motion of merged load and store"));
  75. static cl::opt<bool> EnableLoopInterchange(
  76. "enable-loopinterchange", cl::init(false), cl::Hidden,
  77. cl::desc("Enable the new, experimental LoopInterchange Pass"));
  78. static cl::opt<bool> EnableLoopDistribute(
  79. "enable-loop-distribute", cl::init(false), cl::Hidden,
  80. cl::desc("Enable the new, experimental LoopDistribution Pass"));
  81. PassManagerBuilder::PassManagerBuilder() {
  82. OptLevel = 2;
  83. SizeLevel = 0;
  84. LibraryInfo = nullptr;
  85. Inliner = nullptr;
  86. DisableUnitAtATime = false;
  87. DisableUnrollLoops = false;
  88. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  89. BBVectorize = RunBBVectorization;
  90. SLPVectorize = RunSLPVectorization;
  91. LoopVectorize = RunLoopVectorization;
  92. #else
  93. BBVectorize = SLPVectorize = LoopVectorize = false;
  94. #endif
  95. RerollLoops = RunLoopRerolling;
  96. LoadCombine = RunLoadCombine;
  97. DisableGVNLoadPRE = false;
  98. VerifyInput = false;
  99. VerifyOutput = false;
  100. MergeFunctions = false;
  101. PrepareForLTO = false;
  102. }
  103. PassManagerBuilder::~PassManagerBuilder() {
  104. delete LibraryInfo;
  105. delete Inliner;
  106. }
  107. /// Set of global extensions, automatically added as part of the standard set.
  108. static ManagedStatic<SmallVector<std::pair<PassManagerBuilder::ExtensionPointTy,
  109. PassManagerBuilder::ExtensionFn>, 8> > GlobalExtensions;
  110. void PassManagerBuilder::addGlobalExtension(
  111. PassManagerBuilder::ExtensionPointTy Ty,
  112. PassManagerBuilder::ExtensionFn Fn) {
  113. GlobalExtensions->push_back(std::make_pair(Ty, Fn));
  114. }
  115. void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {
  116. Extensions.push_back(std::make_pair(Ty, Fn));
  117. }
  118. void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,
  119. legacy::PassManagerBase &PM) const {
  120. for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)
  121. if ((*GlobalExtensions)[i].first == ETy)
  122. (*GlobalExtensions)[i].second(*this, PM);
  123. for (unsigned i = 0, e = Extensions.size(); i != e; ++i)
  124. if (Extensions[i].first == ETy)
  125. Extensions[i].second(*this, PM);
  126. }
  127. void PassManagerBuilder::addInitialAliasAnalysisPasses(
  128. legacy::PassManagerBase &PM) const {
  129. // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
  130. // BasicAliasAnalysis wins if they disagree. This is intended to help
  131. // support "obvious" type-punning idioms.
  132. if (UseCFLAA)
  133. PM.add(createCFLAliasAnalysisPass());
  134. PM.add(createTypeBasedAliasAnalysisPass());
  135. PM.add(createScopedNoAliasAAPass());
  136. PM.add(createBasicAliasAnalysisPass());
  137. }
  138. void PassManagerBuilder::populateFunctionPassManager(
  139. legacy::FunctionPassManager &FPM) {
  140. addExtensionsToPM(EP_EarlyAsPossible, FPM);
  141. // Add LibraryInfo if we have some.
  142. if (LibraryInfo)
  143. FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  144. if (OptLevel == 0) return;
  145. addInitialAliasAnalysisPasses(FPM);
  146. FPM.add(createCFGSimplificationPass());
  147. // HLSL Change - don't run SROA.
  148. // HLSL uses special SROA added in addHLSLPasses.
  149. if (HLSLHighLevel) // HLSL Change
  150. if (UseNewSROA)
  151. FPM.add(createSROAPass());
  152. else
  153. FPM.add(createScalarReplAggregatesPass());
  154. // HLSL Change. FPM.add(createEarlyCSEPass());
  155. FPM.add(createLowerExpectIntrinsicPass());
  156. }
  157. // HLSL Change Starts
  158. static void addHLSLPasses(bool HLSLHighLevel, bool NoOpt, hlsl::HLSLExtensionsCodegenHelper *ExtHelper, legacy::PassManagerBase &MPM) {
  159. // Don't do any lowering if we're targeting high-level.
  160. if (HLSLHighLevel) {
  161. MPM.add(createHLEmitMetadataPass());
  162. return;
  163. }
  164. // Split struct and array of parameter.
  165. MPM.add(createSROA_Parameter_HLSL());
  166. // Split struct.
  167. MPM.add(createScalarReplAggregatesHLSLPass(/*UseDomTree*/ true,
  168. /*Promote*/ !NoOpt));
  169. MPM.add(createHLMatrixLowerPass());
  170. MPM.add(createResourceToHandlePass());
  171. // DCE should after SROA to remove unused element.
  172. MPM.add(createDeadCodeEliminationPass());
  173. MPM.add(createGlobalDCEPass());
  174. if (NoOpt) {
  175. // If not run mem2reg, try to promote allocas used by EvalOperations.
  176. // Do this before change vector to array.
  177. MPM.add(createDxilLegalizeEvalOperationsPass());
  178. }
  179. // Change dynamic indexing vector to array.
  180. MPM.add(createDynamicIndexingVectorToArrayPass(NoOpt));
  181. if (!NoOpt) {
  182. MPM.add(createLowerStaticGlobalIntoAlloca());
  183. // mem2reg
  184. MPM.add(createPromoteMemoryToRegisterPass());
  185. }
  186. MPM.add(createSimplifyInstPass());
  187. MPM.add(createCFGSimplificationPass());
  188. MPM.add(createDxilLegalizeResourceUsePass());
  189. MPM.add(createDxilLegalizeStaticResourceUsePass());
  190. MPM.add(createDxilGenerationPass(NoOpt, ExtHelper));
  191. MPM.add(createDxilLoadMetadataPass()); // Ensure DxilModule is loaded for optimizations.
  192. MPM.add(createSimplifyInstPass());
  193. // Propagate precise attribute.
  194. MPM.add(createDxilPrecisePropagatePass());
  195. // scalarize vector to scalar
  196. MPM.add(createScalarizerPass());
  197. MPM.add(createSimplifyInstPass());
  198. MPM.add(createCFGSimplificationPass());
  199. MPM.add(createDeadCodeEliminationPass());
  200. }
  201. // HLSL Change Ends
  202. void PassManagerBuilder::populateModulePassManager(
  203. legacy::PassManagerBase &MPM) {
  204. // If all optimizations are disabled, just run the always-inline pass and,
  205. // if enabled, the function merging pass.
  206. if (OptLevel == 0) {
  207. if (!HLSLHighLevel) {
  208. MPM.add(createHLEnsureMetadataPass()); // HLSL Change - rehydrate metadata from high-level codegen
  209. }
  210. if (Inliner) {
  211. MPM.add(Inliner);
  212. Inliner = nullptr;
  213. }
  214. // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly
  215. // creates a CGSCC pass manager, but we don't want to add extensions into
  216. // that pass manager. To prevent this we insert a no-op module pass to reset
  217. // the pass manager to get the same behavior as EP_OptimizerLast in non-O0
  218. // builds. The function merging pass is
  219. if (MergeFunctions)
  220. MPM.add(createMergeFunctionsPass());
  221. else if (!GlobalExtensions->empty() || !Extensions.empty())
  222. MPM.add(createBarrierNoopPass());
  223. addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);
  224. // HLSL Change Begins.
  225. addHLSLPasses(HLSLHighLevel, true/*NoOpt*/, HLSLExtensionsCodeGen, MPM); // HLSL Change
  226. if (!HLSLHighLevel) {
  227. MPM.add(createMultiDimArrayToOneDimArrayPass());// HLSL Change
  228. MPM.add(createDxilCondenseResourcesPass()); // HLSL Change
  229. MPM.add(createDxilLegalizeSampleOffsetPass()); // HLSL Change
  230. MPM.add(createDxilFinalizeModulePass()); // HLSL Change
  231. MPM.add(createComputeViewIdStatePass()); // HLSL Change
  232. MPM.add(createDxilEmitMetadataPass()); // HLSL Change
  233. }
  234. // HLSL Change Ends.
  235. return;
  236. }
  237. if (!HLSLHighLevel) {
  238. MPM.add(createHLEnsureMetadataPass()); // HLSL Change - rehydrate metadata from high-level codegen
  239. }
  240. // HLSL Change Begins
  241. MPM.add(createAlwaysInlinerPass(/*InsertLifeTime*/false));
  242. if (Inliner) {
  243. delete Inliner;
  244. Inliner = nullptr;
  245. }
  246. addHLSLPasses(HLSLHighLevel, false/*NoOpt*/, HLSLExtensionsCodeGen, MPM); // HLSL Change
  247. // HLSL Change Ends
  248. // Add LibraryInfo if we have some.
  249. if (LibraryInfo)
  250. MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  251. addInitialAliasAnalysisPasses(MPM);
  252. if (!DisableUnitAtATime) {
  253. addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);
  254. MPM.add(createIPSCCPPass()); // IP SCCP
  255. MPM.add(createGlobalOptimizerPass()); // Optimize out global vars
  256. MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
  257. MPM.add(createInstructionCombiningPass());// Clean up after IPCP & DAE
  258. addExtensionsToPM(EP_Peephole, MPM);
  259. MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
  260. }
  261. // Start of CallGraph SCC passes.
  262. if (!DisableUnitAtATime)
  263. MPM.add(createPruneEHPass()); // Remove dead EH info
  264. if (Inliner) {
  265. MPM.add(Inliner);
  266. Inliner = nullptr;
  267. }
  268. if (!DisableUnitAtATime)
  269. MPM.add(createFunctionAttrsPass()); // Set readonly/readnone attrs
  270. if (OptLevel > 2)
  271. MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
  272. // Start of function pass.
  273. // Break up aggregate allocas, using SSAUpdater.
  274. // HLSL Change - don't run SROA.
  275. // HLSL uses special SROA added in addHLSLPasses.
  276. if (HLSLHighLevel) // HLSL Change
  277. if (UseNewSROA)
  278. MPM.add(createSROAPass(/*RequiresDomTree*/ false));
  279. else
  280. MPM.add(createScalarReplAggregatesPass(-1, false));
  281. // HLSL Change. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  282. // HLSL Change. MPM.add(createJumpThreadingPass()); // Thread jumps.
  283. MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals
  284. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  285. MPM.add(createInstructionCombiningPass()); // Combine silly seq's
  286. addExtensionsToPM(EP_Peephole, MPM);
  287. // HLSL Change Begins.
  288. // HLSL does not allow recursize functions.
  289. //MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
  290. // HLSL Change Ends.
  291. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  292. MPM.add(createReassociatePass()); // Reassociate expressions
  293. // Rotate Loop - disable header duplication at -Oz
  294. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
  295. MPM.add(createLICMPass()); // Hoist loop invariants
  296. //MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3)); // HLSL Change - may move barrier inside divergent if.
  297. MPM.add(createInstructionCombiningPass());
  298. MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
  299. MPM.add(createLoopIdiomPass()); // Recognize idioms like memset.
  300. MPM.add(createLoopDeletionPass()); // Delete dead loops
  301. if (EnableLoopInterchange) {
  302. MPM.add(createLoopInterchangePass()); // Interchange loops
  303. MPM.add(createCFGSimplificationPass());
  304. }
  305. if (!DisableUnrollLoops)
  306. MPM.add(createSimpleLoopUnrollPass()); // Unroll small loops
  307. addExtensionsToPM(EP_LoopOptimizerEnd, MPM);
  308. if (OptLevel > 1) {
  309. if (EnableMLSM)
  310. MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds
  311. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  312. }
  313. // HLSL Change Begins.
  314. // HLSL don't allow memcpy and memset.
  315. //MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
  316. // HLSL Change Ends.
  317. MPM.add(createSCCPPass()); // Constant prop with SCCP
  318. // Delete dead bit computations (instcombine runs after to fold away the dead
  319. // computations, and then ADCE will run later to exploit any new DCE
  320. // opportunities that creates).
  321. MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations
  322. // Run instcombine after redundancy elimination to exploit opportunities
  323. // opened up by them.
  324. MPM.add(createInstructionCombiningPass());
  325. addExtensionsToPM(EP_Peephole, MPM);
  326. // HLSL Change. MPM.add(createJumpThreadingPass()); // Thread jumps
  327. MPM.add(createCorrelatedValuePropagationPass());
  328. MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
  329. MPM.add(createLICMPass());
  330. addExtensionsToPM(EP_ScalarOptimizerLate, MPM);
  331. if (RerollLoops)
  332. MPM.add(createLoopRerollPass());
  333. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  334. if (!RunSLPAfterLoopVectorization) {
  335. if (SLPVectorize)
  336. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  337. if (BBVectorize) {
  338. MPM.add(createBBVectorizePass());
  339. MPM.add(createInstructionCombiningPass());
  340. addExtensionsToPM(EP_Peephole, MPM);
  341. if (OptLevel > 1 && UseGVNAfterVectorization)
  342. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  343. else
  344. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  345. // BBVectorize may have significantly shortened a loop body; unroll again.
  346. if (!DisableUnrollLoops)
  347. MPM.add(createLoopUnrollPass());
  348. }
  349. }
  350. #endif
  351. if (LoadCombine)
  352. MPM.add(createLoadCombinePass());
  353. MPM.add(createHoistConstantArrayPass()); // HLSL change
  354. MPM.add(createAggressiveDCEPass()); // Delete dead instructions
  355. MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
  356. MPM.add(createInstructionCombiningPass()); // Clean up after everything.
  357. addExtensionsToPM(EP_Peephole, MPM);
  358. // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC
  359. // pass manager that we are specifically trying to avoid. To prevent this
  360. // we must insert a no-op module pass to reset the pass manager.
  361. MPM.add(createBarrierNoopPass());
  362. if (RunFloat2Int)
  363. MPM.add(createFloat2IntPass());
  364. // Re-rotate loops in all our loop nests. These may have fallout out of
  365. // rotated form due to GVN or other transformations, and the vectorizer relies
  366. // on the rotated form. Disable header duplication at -Oz.
  367. MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1));
  368. // Distribute loops to allow partial vectorization. I.e. isolate dependences
  369. // into separate loop that would otherwise inhibit vectorization.
  370. if (EnableLoopDistribute)
  371. MPM.add(createLoopDistributePass());
  372. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  373. MPM.add(createLoopVectorizePass(DisableUnrollLoops, LoopVectorize));
  374. #endif
  375. // FIXME: Because of #pragma vectorize enable, the passes below are always
  376. // inserted in the pipeline, even when the vectorizer doesn't run (ex. when
  377. // on -O1 and no #pragma is found). Would be good to have these two passes
  378. // as function calls, so that we can only pass them when the vectorizer
  379. // changed the code.
  380. MPM.add(createInstructionCombiningPass());
  381. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  382. if (OptLevel > 1 && ExtraVectorizerPasses) {
  383. // At higher optimization levels, try to clean up any runtime overlap and
  384. // alignment checks inserted by the vectorizer. We want to track correllated
  385. // runtime checks for two inner loops in the same outer loop, fold any
  386. // common computations, hoist loop-invariant aspects out of any outer loop,
  387. // and unswitch the runtime checks if possible. Once hoisted, we may have
  388. // dead (or speculatable) control flows or more combining opportunities.
  389. MPM.add(createEarlyCSEPass());
  390. MPM.add(createCorrelatedValuePropagationPass());
  391. MPM.add(createInstructionCombiningPass());
  392. MPM.add(createLICMPass());
  393. MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));
  394. MPM.add(createCFGSimplificationPass());
  395. MPM.add(createInstructionCombiningPass());
  396. }
  397. if (RunSLPAfterLoopVectorization) {
  398. if (SLPVectorize) {
  399. MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  400. if (OptLevel > 1 && ExtraVectorizerPasses) {
  401. MPM.add(createEarlyCSEPass());
  402. }
  403. }
  404. if (BBVectorize) {
  405. MPM.add(createBBVectorizePass());
  406. MPM.add(createInstructionCombiningPass());
  407. addExtensionsToPM(EP_Peephole, MPM);
  408. if (OptLevel > 1 && UseGVNAfterVectorization)
  409. MPM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies
  410. else
  411. MPM.add(createEarlyCSEPass()); // Catch trivial redundancies
  412. // BBVectorize may have significantly shortened a loop body; unroll again.
  413. if (!DisableUnrollLoops)
  414. MPM.add(createLoopUnrollPass());
  415. }
  416. }
  417. #endif // HLSL Change - don't build vectorization passes
  418. addExtensionsToPM(EP_Peephole, MPM);
  419. MPM.add(createCFGSimplificationPass());
  420. MPM.add(createInstructionCombiningPass());
  421. if (!DisableUnrollLoops) {
  422. MPM.add(createLoopUnrollPass()); // Unroll small loops
  423. // LoopUnroll may generate some redundency to cleanup.
  424. MPM.add(createInstructionCombiningPass());
  425. // Runtime unrolling will introduce runtime check in loop prologue. If the
  426. // unrolled loop is a inner loop, then the prologue will be inside the
  427. // outer loop. LICM pass can help to promote the runtime check out if the
  428. // checked value is loop invariant.
  429. MPM.add(createLICMPass());
  430. }
  431. // After vectorization and unrolling, assume intrinsics may tell us more
  432. // about pointer alignments.
  433. MPM.add(createAlignmentFromAssumptionsPass());
  434. if (!DisableUnitAtATime) {
  435. // FIXME: We shouldn't bother with this anymore.
  436. MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
  437. // GlobalOpt already deletes dead functions and globals, at -O2 try a
  438. // late pass of GlobalDCE. It is capable of deleting dead cycles.
  439. if (OptLevel > 1) {
  440. if (!PrepareForLTO) {
  441. // Remove avail extern fns and globals definitions if we aren't
  442. // compiling an object file for later LTO. For LTO we want to preserve
  443. // these so they are eligible for inlining at link-time. Note if they
  444. // are unreferenced they will be removed by GlobalDCE below, so
  445. // this only impacts referenced available externally globals.
  446. // Eventually they will be suppressed during codegen, but eliminating
  447. // here enables more opportunity for GlobalDCE as it may make
  448. // globals referenced by available external functions dead.
  449. MPM.add(createEliminateAvailableExternallyPass());
  450. }
  451. MPM.add(createGlobalDCEPass()); // Remove dead fns and globals.
  452. MPM.add(createConstantMergePass()); // Merge dup global constants
  453. }
  454. }
  455. if (MergeFunctions)
  456. MPM.add(createMergeFunctionsPass());
  457. // HLSL Change Begins.
  458. if (!HLSLHighLevel) {
  459. MPM.add(createMultiDimArrayToOneDimArrayPass());// HLSL Change
  460. MPM.add(createDxilCondenseResourcesPass());
  461. if (DisableUnrollLoops)
  462. MPM.add(createDxilLegalizeSampleOffsetPass()); // HLSL Change
  463. MPM.add(createDxilFinalizeModulePass());
  464. MPM.add(createComputeViewIdStatePass()); // HLSL Change
  465. MPM.add(createDxilEmitMetadataPass());
  466. }
  467. // HLSL Change Ends.
  468. addExtensionsToPM(EP_OptimizerLast, MPM);
  469. }
  470. void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) {
  471. // Provide AliasAnalysis services for optimizations.
  472. addInitialAliasAnalysisPasses(PM);
  473. // Propagate constants at call sites into the functions they call. This
  474. // opens opportunities for globalopt (and inlining) by substituting function
  475. // pointers passed as arguments to direct uses of functions.
  476. PM.add(createIPSCCPPass());
  477. // Now that we internalized some globals, see if we can hack on them!
  478. PM.add(createGlobalOptimizerPass());
  479. // Linking modules together can lead to duplicated global constants, only
  480. // keep one copy of each constant.
  481. PM.add(createConstantMergePass());
  482. // Remove unused arguments from functions.
  483. PM.add(createDeadArgEliminationPass());
  484. // Reduce the code after globalopt and ipsccp. Both can open up significant
  485. // simplification opportunities, and both can propagate functions through
  486. // function pointers. When this happens, we often have to resolve varargs
  487. // calls, etc, so let instcombine do this.
  488. PM.add(createInstructionCombiningPass());
  489. addExtensionsToPM(EP_Peephole, PM);
  490. // Inline small functions
  491. bool RunInliner = Inliner;
  492. if (RunInliner) {
  493. PM.add(Inliner);
  494. Inliner = nullptr;
  495. }
  496. PM.add(createPruneEHPass()); // Remove dead EH info.
  497. // Optimize globals again if we ran the inliner.
  498. if (RunInliner)
  499. PM.add(createGlobalOptimizerPass());
  500. PM.add(createGlobalDCEPass()); // Remove dead functions.
  501. // If we didn't decide to inline a function, check to see if we can
  502. // transform it to pass arguments by value instead of by reference.
  503. PM.add(createArgumentPromotionPass());
  504. // The IPO passes may leave cruft around. Clean up after them.
  505. PM.add(createInstructionCombiningPass());
  506. addExtensionsToPM(EP_Peephole, PM);
  507. // HLSL Change. PM.add(createJumpThreadingPass());
  508. // Break up allocas
  509. if (UseNewSROA)
  510. PM.add(createSROAPass());
  511. else
  512. PM.add(createScalarReplAggregatesPass());
  513. // Run a few AA driven optimizations here and now, to cleanup the code.
  514. PM.add(createFunctionAttrsPass()); // Add nocapture.
  515. PM.add(createGlobalsModRefPass()); // IP alias analysis.
  516. PM.add(createLICMPass()); // Hoist loop invariants.
  517. if (EnableMLSM)
  518. PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds.
  519. PM.add(createGVNPass(DisableGVNLoadPRE)); // Remove redundancies.
  520. PM.add(createMemCpyOptPass()); // Remove dead memcpys.
  521. // Nuke dead stores.
  522. PM.add(createDeadStoreEliminationPass());
  523. // More loops are countable; try to optimize them.
  524. PM.add(createIndVarSimplifyPass());
  525. PM.add(createLoopDeletionPass());
  526. if (EnableLoopInterchange)
  527. PM.add(createLoopInterchangePass());
  528. #if HLSL_VECTORIZATION_ENABLED // HLSL Change - don't build vectorization passes
  529. PM.add(createLoopVectorizePass(true, LoopVectorize));
  530. // More scalar chains could be vectorized due to more alias information
  531. if (RunSLPAfterLoopVectorization)
  532. if (SLPVectorize)
  533. PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains.
  534. // After vectorization, assume intrinsics may tell us more about pointer
  535. // alignments.
  536. PM.add(createAlignmentFromAssumptionsPass());
  537. #endif
  538. if (LoadCombine)
  539. PM.add(createLoadCombinePass());
  540. // Cleanup and simplify the code after the scalar optimizations.
  541. PM.add(createInstructionCombiningPass());
  542. addExtensionsToPM(EP_Peephole, PM);
  543. // HLSL Change. PM.add(createJumpThreadingPass());
  544. }
  545. void PassManagerBuilder::addLateLTOOptimizationPasses(
  546. legacy::PassManagerBase &PM) {
  547. // Delete basic blocks, which optimization passes may have killed.
  548. PM.add(createCFGSimplificationPass());
  549. // Now that we have optimized the program, discard unreachable functions.
  550. PM.add(createGlobalDCEPass());
  551. // FIXME: this is profitable (for compiler time) to do at -O0 too, but
  552. // currently it damages debug info.
  553. if (MergeFunctions)
  554. PM.add(createMergeFunctionsPass());
  555. }
  556. void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) {
  557. if (LibraryInfo)
  558. PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo));
  559. if (VerifyInput)
  560. PM.add(createVerifierPass());
  561. if (OptLevel > 1)
  562. addLTOOptimizationPasses(PM);
  563. // Lower bit sets to globals. This pass supports Clang's control flow
  564. // integrity mechanisms (-fsanitize=cfi*) and needs to run at link time if CFI
  565. // is enabled. The pass does nothing if CFI is disabled.
  566. PM.add(createLowerBitSetsPass());
  567. if (OptLevel != 0)
  568. addLateLTOOptimizationPasses(PM);
  569. if (VerifyOutput)
  570. PM.add(createVerifierPass());
  571. }
  572. inline PassManagerBuilder *unwrap(LLVMPassManagerBuilderRef P) {
  573. return reinterpret_cast<PassManagerBuilder*>(P);
  574. }
  575. inline LLVMPassManagerBuilderRef wrap(PassManagerBuilder *P) {
  576. return reinterpret_cast<LLVMPassManagerBuilderRef>(P);
  577. }
  578. LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() {
  579. PassManagerBuilder *PMB = new PassManagerBuilder();
  580. return wrap(PMB);
  581. }
  582. void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {
  583. PassManagerBuilder *Builder = unwrap(PMB);
  584. delete Builder;
  585. }
  586. void
  587. LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,
  588. unsigned OptLevel) {
  589. PassManagerBuilder *Builder = unwrap(PMB);
  590. Builder->OptLevel = OptLevel;
  591. }
  592. void
  593. LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,
  594. unsigned SizeLevel) {
  595. PassManagerBuilder *Builder = unwrap(PMB);
  596. Builder->SizeLevel = SizeLevel;
  597. }
  598. void
  599. LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,
  600. LLVMBool Value) {
  601. PassManagerBuilder *Builder = unwrap(PMB);
  602. Builder->DisableUnitAtATime = Value;
  603. }
  604. void
  605. LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,
  606. LLVMBool Value) {
  607. PassManagerBuilder *Builder = unwrap(PMB);
  608. Builder->DisableUnrollLoops = Value;
  609. }
  610. void
  611. LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,
  612. LLVMBool Value) {
  613. // NOTE: The simplify-libcalls pass has been removed.
  614. }
  615. void
  616. LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,
  617. unsigned Threshold) {
  618. PassManagerBuilder *Builder = unwrap(PMB);
  619. Builder->Inliner = createFunctionInliningPass(Threshold);
  620. }
  621. void
  622. LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,
  623. LLVMPassManagerRef PM) {
  624. PassManagerBuilder *Builder = unwrap(PMB);
  625. legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM);
  626. Builder->populateFunctionPassManager(*FPM);
  627. }
  628. void
  629. LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,
  630. LLVMPassManagerRef PM) {
  631. PassManagerBuilder *Builder = unwrap(PMB);
  632. legacy::PassManagerBase *MPM = unwrap(PM);
  633. Builder->populateModulePassManager(*MPM);
  634. }
  635. void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,
  636. LLVMPassManagerRef PM,
  637. LLVMBool Internalize,
  638. LLVMBool RunInliner) {
  639. PassManagerBuilder *Builder = unwrap(PMB);
  640. legacy::PassManagerBase *LPM = unwrap(PM);
  641. // A small backwards compatibility hack. populateLTOPassManager used to take
  642. // an RunInliner option.
  643. if (RunInliner && !Builder->Inliner)
  644. Builder->Inliner = createFunctionInliningPass();
  645. Builder->populateLTOPassManager(*LPM);
  646. }