PassManagerBuilder.cpp 31 KB

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