PassManagerBuilder.cpp 31 KB

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