X86CmovConversion.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. //====- X86CmovConversion.cpp - Convert Cmov to Branch --------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file
  10. /// This file implements a pass that converts X86 cmov instructions into
  11. /// branches when profitable. This pass is conservative. It transforms if and
  12. /// only if it can guarantee a gain with high confidence.
  13. ///
  14. /// Thus, the optimization applies under the following conditions:
  15. /// 1. Consider as candidates only CMOVs in innermost loops (assume that
  16. /// most hotspots are represented by these loops).
  17. /// 2. Given a group of CMOV instructions that are using the same EFLAGS def
  18. /// instruction:
  19. /// a. Consider them as candidates only if all have the same code condition
  20. /// or the opposite one to prevent generating more than one conditional
  21. /// jump per EFLAGS def instruction.
  22. /// b. Consider them as candidates only if all are profitable to be
  23. /// converted (assume that one bad conversion may cause a degradation).
  24. /// 3. Apply conversion only for loops that are found profitable and only for
  25. /// CMOV candidates that were found profitable.
  26. /// a. A loop is considered profitable only if conversion will reduce its
  27. /// depth cost by some threshold.
  28. /// b. CMOV is considered profitable if the cost of its condition is higher
  29. /// than the average cost of its true-value and false-value by 25% of
  30. /// branch-misprediction-penalty. This assures no degradation even with
  31. /// 25% branch misprediction.
  32. ///
  33. /// Note: This pass is assumed to run on SSA machine code.
  34. //
  35. //===----------------------------------------------------------------------===//
  36. //
  37. // External interfaces:
  38. // FunctionPass *llvm::createX86CmovConverterPass();
  39. // bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF);
  40. //
  41. //===----------------------------------------------------------------------===//
  42. #include "X86.h"
  43. #include "X86InstrInfo.h"
  44. #include "llvm/ADT/ArrayRef.h"
  45. #include "llvm/ADT/DenseMap.h"
  46. #include "llvm/ADT/STLExtras.h"
  47. #include "llvm/ADT/SmallPtrSet.h"
  48. #include "llvm/ADT/SmallVector.h"
  49. #include "llvm/ADT/Statistic.h"
  50. #include "llvm/CodeGen/MachineBasicBlock.h"
  51. #include "llvm/CodeGen/MachineFunction.h"
  52. #include "llvm/CodeGen/MachineFunctionPass.h"
  53. #include "llvm/CodeGen/MachineInstr.h"
  54. #include "llvm/CodeGen/MachineInstrBuilder.h"
  55. #include "llvm/CodeGen/MachineLoopInfo.h"
  56. #include "llvm/CodeGen/MachineOperand.h"
  57. #include "llvm/CodeGen/MachineRegisterInfo.h"
  58. #include "llvm/CodeGen/TargetInstrInfo.h"
  59. #include "llvm/CodeGen/TargetRegisterInfo.h"
  60. #include "llvm/CodeGen/TargetSchedule.h"
  61. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  62. #include "llvm/IR/DebugLoc.h"
  63. #include "llvm/InitializePasses.h"
  64. #include "llvm/MC/MCSchedule.h"
  65. #include "llvm/Pass.h"
  66. #include "llvm/Support/CommandLine.h"
  67. #include "llvm/Support/Debug.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. #include "llvm/Target/CGPassBuilderOption.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <iterator>
  73. #include <utility>
  74. using namespace llvm;
  75. #define DEBUG_TYPE "x86-cmov-conversion"
  76. STATISTIC(NumOfSkippedCmovGroups, "Number of unsupported CMOV-groups");
  77. STATISTIC(NumOfCmovGroupCandidate, "Number of CMOV-group candidates");
  78. STATISTIC(NumOfLoopCandidate, "Number of CMOV-conversion profitable loops");
  79. STATISTIC(NumOfOptimizedCmovGroups, "Number of optimized CMOV-groups");
  80. // This internal switch can be used to turn off the cmov/branch optimization.
  81. static cl::opt<bool>
  82. EnableCmovConverter("x86-cmov-converter",
  83. cl::desc("Enable the X86 cmov-to-branch optimization."),
  84. cl::init(true), cl::Hidden);
  85. static cl::opt<unsigned>
  86. GainCycleThreshold("x86-cmov-converter-threshold",
  87. cl::desc("Minimum gain per loop (in cycles) threshold."),
  88. cl::init(4), cl::Hidden);
  89. static cl::opt<bool> ForceMemOperand(
  90. "x86-cmov-converter-force-mem-operand",
  91. cl::desc("Convert cmovs to branches whenever they have memory operands."),
  92. cl::init(true), cl::Hidden);
  93. static cl::opt<bool> ForceAll(
  94. "x86-cmov-converter-force-all",
  95. cl::desc("Convert all cmovs to branches."),
  96. cl::init(false), cl::Hidden);
  97. namespace {
  98. /// Converts X86 cmov instructions into branches when profitable.
  99. class X86CmovConverterPass : public MachineFunctionPass {
  100. public:
  101. X86CmovConverterPass() : MachineFunctionPass(ID) { }
  102. StringRef getPassName() const override { return "X86 cmov Conversion"; }
  103. bool runOnMachineFunction(MachineFunction &MF) override;
  104. void getAnalysisUsage(AnalysisUsage &AU) const override;
  105. /// Pass identification, replacement for typeid.
  106. static char ID;
  107. private:
  108. MachineRegisterInfo *MRI = nullptr;
  109. const TargetInstrInfo *TII = nullptr;
  110. const TargetRegisterInfo *TRI = nullptr;
  111. MachineLoopInfo *MLI = nullptr;
  112. TargetSchedModel TSchedModel;
  113. /// List of consecutive CMOV instructions.
  114. using CmovGroup = SmallVector<MachineInstr *, 2>;
  115. using CmovGroups = SmallVector<CmovGroup, 2>;
  116. /// Collect all CMOV-group-candidates in \p CurrLoop and update \p
  117. /// CmovInstGroups accordingly.
  118. ///
  119. /// \param Blocks List of blocks to process.
  120. /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
  121. /// \returns true iff it found any CMOV-group-candidate.
  122. bool collectCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
  123. CmovGroups &CmovInstGroups,
  124. bool IncludeLoads = false);
  125. /// Check if it is profitable to transform each CMOV-group-candidates into
  126. /// branch. Remove all groups that are not profitable from \p CmovInstGroups.
  127. ///
  128. /// \param Blocks List of blocks to process.
  129. /// \param CmovInstGroups List of consecutive CMOV instructions in CurrLoop.
  130. /// \returns true iff any CMOV-group-candidate remain.
  131. bool checkForProfitableCmovCandidates(ArrayRef<MachineBasicBlock *> Blocks,
  132. CmovGroups &CmovInstGroups);
  133. /// Convert the given list of consecutive CMOV instructions into a branch.
  134. ///
  135. /// \param Group Consecutive CMOV instructions to be converted into branch.
  136. void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group) const;
  137. };
  138. } // end anonymous namespace
  139. char X86CmovConverterPass::ID = 0;
  140. void X86CmovConverterPass::getAnalysisUsage(AnalysisUsage &AU) const {
  141. MachineFunctionPass::getAnalysisUsage(AU);
  142. AU.addRequired<MachineLoopInfo>();
  143. }
  144. bool X86CmovConverterPass::runOnMachineFunction(MachineFunction &MF) {
  145. if (skipFunction(MF.getFunction()))
  146. return false;
  147. if (!EnableCmovConverter)
  148. return false;
  149. // If the SelectOptimize pass is enabled, cmovs have already been optimized.
  150. if (!getCGPassBuilderOption().DisableSelectOptimize)
  151. return false;
  152. LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
  153. << "**********\n");
  154. bool Changed = false;
  155. MLI = &getAnalysis<MachineLoopInfo>();
  156. const TargetSubtargetInfo &STI = MF.getSubtarget();
  157. MRI = &MF.getRegInfo();
  158. TII = STI.getInstrInfo();
  159. TRI = STI.getRegisterInfo();
  160. TSchedModel.init(&STI);
  161. // Before we handle the more subtle cases of register-register CMOVs inside
  162. // of potentially hot loops, we want to quickly remove all CMOVs (ForceAll) or
  163. // the ones with a memory operand (ForceMemOperand option). The latter CMOV
  164. // will risk a stall waiting for the load to complete that speculative
  165. // execution behind a branch is better suited to handle on modern x86 chips.
  166. if (ForceMemOperand || ForceAll) {
  167. CmovGroups AllCmovGroups;
  168. SmallVector<MachineBasicBlock *, 4> Blocks;
  169. for (auto &MBB : MF)
  170. Blocks.push_back(&MBB);
  171. if (collectCmovCandidates(Blocks, AllCmovGroups, /*IncludeLoads*/ true)) {
  172. for (auto &Group : AllCmovGroups) {
  173. // Skip any group that doesn't do at least one memory operand cmov.
  174. if (ForceMemOperand && !ForceAll &&
  175. llvm::none_of(Group, [&](MachineInstr *I) { return I->mayLoad(); }))
  176. continue;
  177. // For CMOV groups which we can rewrite and which contain a memory load,
  178. // always rewrite them. On x86, a CMOV will dramatically amplify any
  179. // memory latency by blocking speculative execution.
  180. Changed = true;
  181. convertCmovInstsToBranches(Group);
  182. }
  183. }
  184. // Early return as ForceAll converts all CmovGroups.
  185. if (ForceAll)
  186. return Changed;
  187. }
  188. //===--------------------------------------------------------------------===//
  189. // Register-operand Conversion Algorithm
  190. // ---------
  191. // For each innermost loop
  192. // collectCmovCandidates() {
  193. // Find all CMOV-group-candidates.
  194. // }
  195. //
  196. // checkForProfitableCmovCandidates() {
  197. // * Calculate both loop-depth and optimized-loop-depth.
  198. // * Use these depth to check for loop transformation profitability.
  199. // * Check for CMOV-group-candidate transformation profitability.
  200. // }
  201. //
  202. // For each profitable CMOV-group-candidate
  203. // convertCmovInstsToBranches() {
  204. // * Create FalseBB, SinkBB, Conditional branch to SinkBB.
  205. // * Replace each CMOV instruction with a PHI instruction in SinkBB.
  206. // }
  207. //
  208. // Note: For more details, see each function description.
  209. //===--------------------------------------------------------------------===//
  210. // Build up the loops in pre-order.
  211. SmallVector<MachineLoop *, 4> Loops(MLI->begin(), MLI->end());
  212. // Note that we need to check size on each iteration as we accumulate child
  213. // loops.
  214. for (int i = 0; i < (int)Loops.size(); ++i)
  215. for (MachineLoop *Child : Loops[i]->getSubLoops())
  216. Loops.push_back(Child);
  217. for (MachineLoop *CurrLoop : Loops) {
  218. // Optimize only innermost loops.
  219. if (!CurrLoop->getSubLoops().empty())
  220. continue;
  221. // List of consecutive CMOV instructions to be processed.
  222. CmovGroups CmovInstGroups;
  223. if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
  224. continue;
  225. if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
  226. CmovInstGroups))
  227. continue;
  228. Changed = true;
  229. for (auto &Group : CmovInstGroups)
  230. convertCmovInstsToBranches(Group);
  231. }
  232. return Changed;
  233. }
  234. bool X86CmovConverterPass::collectCmovCandidates(
  235. ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups,
  236. bool IncludeLoads) {
  237. //===--------------------------------------------------------------------===//
  238. // Collect all CMOV-group-candidates and add them into CmovInstGroups.
  239. //
  240. // CMOV-group:
  241. // CMOV instructions, in same MBB, that uses same EFLAGS def instruction.
  242. //
  243. // CMOV-group-candidate:
  244. // CMOV-group where all the CMOV instructions are
  245. // 1. consecutive.
  246. // 2. have same condition code or opposite one.
  247. // 3. have only operand registers (X86::CMOVrr).
  248. //===--------------------------------------------------------------------===//
  249. // List of possible improvement (TODO's):
  250. // --------------------------------------
  251. // TODO: Add support for X86::CMOVrm instructions.
  252. // TODO: Add support for X86::SETcc instructions.
  253. // TODO: Add support for CMOV-groups with non consecutive CMOV instructions.
  254. //===--------------------------------------------------------------------===//
  255. // Current processed CMOV-Group.
  256. CmovGroup Group;
  257. for (auto *MBB : Blocks) {
  258. Group.clear();
  259. // Condition code of first CMOV instruction current processed range and its
  260. // opposite condition code.
  261. X86::CondCode FirstCC = X86::COND_INVALID, FirstOppCC = X86::COND_INVALID,
  262. MemOpCC = X86::COND_INVALID;
  263. // Indicator of a non CMOVrr instruction in the current processed range.
  264. bool FoundNonCMOVInst = false;
  265. // Indicator for current processed CMOV-group if it should be skipped.
  266. bool SkipGroup = false;
  267. for (auto &I : *MBB) {
  268. // Skip debug instructions.
  269. if (I.isDebugInstr())
  270. continue;
  271. X86::CondCode CC = X86::getCondFromCMov(I);
  272. // Check if we found a X86::CMOVrr instruction.
  273. if (CC != X86::COND_INVALID && (IncludeLoads || !I.mayLoad())) {
  274. if (Group.empty()) {
  275. // We found first CMOV in the range, reset flags.
  276. FirstCC = CC;
  277. FirstOppCC = X86::GetOppositeBranchCondition(CC);
  278. // Clear out the prior group's memory operand CC.
  279. MemOpCC = X86::COND_INVALID;
  280. FoundNonCMOVInst = false;
  281. SkipGroup = false;
  282. }
  283. Group.push_back(&I);
  284. // Check if it is a non-consecutive CMOV instruction or it has different
  285. // condition code than FirstCC or FirstOppCC.
  286. if (FoundNonCMOVInst || (CC != FirstCC && CC != FirstOppCC))
  287. // Mark the SKipGroup indicator to skip current processed CMOV-Group.
  288. SkipGroup = true;
  289. if (I.mayLoad()) {
  290. if (MemOpCC == X86::COND_INVALID)
  291. // The first memory operand CMOV.
  292. MemOpCC = CC;
  293. else if (CC != MemOpCC)
  294. // Can't handle mixed conditions with memory operands.
  295. SkipGroup = true;
  296. }
  297. // Check if we were relying on zero-extending behavior of the CMOV.
  298. if (!SkipGroup &&
  299. llvm::any_of(
  300. MRI->use_nodbg_instructions(I.defs().begin()->getReg()),
  301. [&](MachineInstr &UseI) {
  302. return UseI.getOpcode() == X86::SUBREG_TO_REG;
  303. }))
  304. // FIXME: We should model the cost of using an explicit MOV to handle
  305. // the zero-extension rather than just refusing to handle this.
  306. SkipGroup = true;
  307. continue;
  308. }
  309. // If Group is empty, keep looking for first CMOV in the range.
  310. if (Group.empty())
  311. continue;
  312. // We found a non X86::CMOVrr instruction.
  313. FoundNonCMOVInst = true;
  314. // Check if this instruction define EFLAGS, to determine end of processed
  315. // range, as there would be no more instructions using current EFLAGS def.
  316. if (I.definesRegister(X86::EFLAGS)) {
  317. // Check if current processed CMOV-group should not be skipped and add
  318. // it as a CMOV-group-candidate.
  319. if (!SkipGroup)
  320. CmovInstGroups.push_back(Group);
  321. else
  322. ++NumOfSkippedCmovGroups;
  323. Group.clear();
  324. }
  325. }
  326. // End of basic block is considered end of range, check if current processed
  327. // CMOV-group should not be skipped and add it as a CMOV-group-candidate.
  328. if (Group.empty())
  329. continue;
  330. if (!SkipGroup)
  331. CmovInstGroups.push_back(Group);
  332. else
  333. ++NumOfSkippedCmovGroups;
  334. }
  335. NumOfCmovGroupCandidate += CmovInstGroups.size();
  336. return !CmovInstGroups.empty();
  337. }
  338. /// \returns Depth of CMOV instruction as if it was converted into branch.
  339. /// \param TrueOpDepth depth cost of CMOV true value operand.
  340. /// \param FalseOpDepth depth cost of CMOV false value operand.
  341. static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth) {
  342. // The depth of the result after branch conversion is
  343. // TrueOpDepth * TrueOpProbability + FalseOpDepth * FalseOpProbability.
  344. // As we have no info about branch weight, we assume 75% for one and 25% for
  345. // the other, and pick the result with the largest resulting depth.
  346. return std::max(
  347. divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
  348. divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
  349. }
  350. bool X86CmovConverterPass::checkForProfitableCmovCandidates(
  351. ArrayRef<MachineBasicBlock *> Blocks, CmovGroups &CmovInstGroups) {
  352. struct DepthInfo {
  353. /// Depth of original loop.
  354. unsigned Depth;
  355. /// Depth of optimized loop.
  356. unsigned OptDepth;
  357. };
  358. /// Number of loop iterations to calculate depth for ?!
  359. static const unsigned LoopIterations = 2;
  360. DenseMap<MachineInstr *, DepthInfo> DepthMap;
  361. DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
  362. enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
  363. /// For each register type maps the register to its last def instruction.
  364. DenseMap<unsigned, MachineInstr *> RegDefMaps[RegTypeNum];
  365. /// Maps register operand to its def instruction, which can be nullptr if it
  366. /// is unknown (e.g., operand is defined outside the loop).
  367. DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
  368. // Set depth of unknown instruction (i.e., nullptr) to zero.
  369. DepthMap[nullptr] = {0, 0};
  370. SmallPtrSet<MachineInstr *, 4> CmovInstructions;
  371. for (auto &Group : CmovInstGroups)
  372. CmovInstructions.insert(Group.begin(), Group.end());
  373. //===--------------------------------------------------------------------===//
  374. // Step 1: Calculate instruction depth and loop depth.
  375. // Optimized-Loop:
  376. // loop with CMOV-group-candidates converted into branches.
  377. //
  378. // Instruction-Depth:
  379. // instruction latency + max operand depth.
  380. // * For CMOV instruction in optimized loop the depth is calculated as:
  381. // CMOV latency + getDepthOfOptCmov(True-Op-Depth, False-Op-depth)
  382. // TODO: Find a better way to estimate the latency of the branch instruction
  383. // rather than using the CMOV latency.
  384. //
  385. // Loop-Depth:
  386. // max instruction depth of all instructions in the loop.
  387. // Note: instruction with max depth represents the critical-path in the loop.
  388. //
  389. // Loop-Depth[i]:
  390. // Loop-Depth calculated for first `i` iterations.
  391. // Note: it is enough to calculate depth for up to two iterations.
  392. //
  393. // Depth-Diff[i]:
  394. // Number of cycles saved in first 'i` iterations by optimizing the loop.
  395. //===--------------------------------------------------------------------===//
  396. for (DepthInfo &MaxDepth : LoopDepth) {
  397. for (auto *MBB : Blocks) {
  398. // Clear physical registers Def map.
  399. RegDefMaps[PhyRegType].clear();
  400. for (MachineInstr &MI : *MBB) {
  401. // Skip debug instructions.
  402. if (MI.isDebugInstr())
  403. continue;
  404. unsigned MIDepth = 0;
  405. unsigned MIDepthOpt = 0;
  406. bool IsCMOV = CmovInstructions.count(&MI);
  407. for (auto &MO : MI.uses()) {
  408. // Checks for "isUse()" as "uses()" returns also implicit definitions.
  409. if (!MO.isReg() || !MO.isUse())
  410. continue;
  411. Register Reg = MO.getReg();
  412. auto &RDM = RegDefMaps[Reg.isVirtual()];
  413. if (MachineInstr *DefMI = RDM.lookup(Reg)) {
  414. OperandToDefMap[&MO] = DefMI;
  415. DepthInfo Info = DepthMap.lookup(DefMI);
  416. MIDepth = std::max(MIDepth, Info.Depth);
  417. if (!IsCMOV)
  418. MIDepthOpt = std::max(MIDepthOpt, Info.OptDepth);
  419. }
  420. }
  421. if (IsCMOV)
  422. MIDepthOpt = getDepthOfOptCmov(
  423. DepthMap[OperandToDefMap.lookup(&MI.getOperand(1))].OptDepth,
  424. DepthMap[OperandToDefMap.lookup(&MI.getOperand(2))].OptDepth);
  425. // Iterates over all operands to handle implicit definitions as well.
  426. for (auto &MO : MI.operands()) {
  427. if (!MO.isReg() || !MO.isDef())
  428. continue;
  429. Register Reg = MO.getReg();
  430. RegDefMaps[Reg.isVirtual()][Reg] = &MI;
  431. }
  432. unsigned Latency = TSchedModel.computeInstrLatency(&MI);
  433. DepthMap[&MI] = {MIDepth += Latency, MIDepthOpt += Latency};
  434. MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
  435. MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
  436. }
  437. }
  438. }
  439. unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
  440. LoopDepth[1].Depth - LoopDepth[1].OptDepth};
  441. //===--------------------------------------------------------------------===//
  442. // Step 2: Check if Loop worth to be optimized.
  443. // Worth-Optimize-Loop:
  444. // case 1: Diff[1] == Diff[0]
  445. // Critical-path is iteration independent - there is no dependency
  446. // of critical-path instructions on critical-path instructions of
  447. // previous iteration.
  448. // Thus, it is enough to check gain percent of 1st iteration -
  449. // To be conservative, the optimized loop need to have a depth of
  450. // 12.5% cycles less than original loop, per iteration.
  451. //
  452. // case 2: Diff[1] > Diff[0]
  453. // Critical-path is iteration dependent - there is dependency of
  454. // critical-path instructions on critical-path instructions of
  455. // previous iteration.
  456. // Thus, check the gain percent of the 2nd iteration (similar to the
  457. // previous case), but it is also required to check the gradient of
  458. // the gain - the change in Depth-Diff compared to the change in
  459. // Loop-Depth between 1st and 2nd iterations.
  460. // To be conservative, the gradient need to be at least 50%.
  461. //
  462. // In addition, In order not to optimize loops with very small gain, the
  463. // gain (in cycles) after 2nd iteration should not be less than a given
  464. // threshold. Thus, the check (Diff[1] >= GainCycleThreshold) must apply.
  465. //
  466. // If loop is not worth optimizing, remove all CMOV-group-candidates.
  467. //===--------------------------------------------------------------------===//
  468. if (Diff[1] < GainCycleThreshold)
  469. return false;
  470. bool WorthOptLoop = false;
  471. if (Diff[1] == Diff[0])
  472. WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
  473. else if (Diff[1] > Diff[0])
  474. WorthOptLoop =
  475. (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].Depth - LoopDepth[0].Depth) &&
  476. (Diff[1] * 8 >= LoopDepth[1].Depth);
  477. if (!WorthOptLoop)
  478. return false;
  479. ++NumOfLoopCandidate;
  480. //===--------------------------------------------------------------------===//
  481. // Step 3: Check for each CMOV-group-candidate if it worth to be optimized.
  482. // Worth-Optimize-Group:
  483. // Iff it is worth to optimize all CMOV instructions in the group.
  484. //
  485. // Worth-Optimize-CMOV:
  486. // Predicted branch is faster than CMOV by the difference between depth of
  487. // condition operand and depth of taken (predicted) value operand.
  488. // To be conservative, the gain of such CMOV transformation should cover at
  489. // at least 25% of branch-misprediction-penalty.
  490. //===--------------------------------------------------------------------===//
  491. unsigned MispredictPenalty = TSchedModel.getMCSchedModel()->MispredictPenalty;
  492. CmovGroups TempGroups;
  493. std::swap(TempGroups, CmovInstGroups);
  494. for (auto &Group : TempGroups) {
  495. bool WorthOpGroup = true;
  496. for (auto *MI : Group) {
  497. // Avoid CMOV instruction which value is used as a pointer to load from.
  498. // This is another conservative check to avoid converting CMOV instruction
  499. // used with tree-search like algorithm, where the branch is unpredicted.
  500. auto UIs = MRI->use_instructions(MI->defs().begin()->getReg());
  501. if (!UIs.empty() && ++UIs.begin() == UIs.end()) {
  502. unsigned Op = UIs.begin()->getOpcode();
  503. if (Op == X86::MOV64rm || Op == X86::MOV32rm) {
  504. WorthOpGroup = false;
  505. break;
  506. }
  507. }
  508. unsigned CondCost =
  509. DepthMap[OperandToDefMap.lookup(&MI->getOperand(4))].Depth;
  510. unsigned ValCost = getDepthOfOptCmov(
  511. DepthMap[OperandToDefMap.lookup(&MI->getOperand(1))].Depth,
  512. DepthMap[OperandToDefMap.lookup(&MI->getOperand(2))].Depth);
  513. if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
  514. WorthOpGroup = false;
  515. break;
  516. }
  517. }
  518. if (WorthOpGroup)
  519. CmovInstGroups.push_back(Group);
  520. }
  521. return !CmovInstGroups.empty();
  522. }
  523. static bool checkEFLAGSLive(MachineInstr *MI) {
  524. if (MI->killsRegister(X86::EFLAGS))
  525. return false;
  526. // The EFLAGS operand of MI might be missing a kill marker.
  527. // Figure out whether EFLAGS operand should LIVE after MI instruction.
  528. MachineBasicBlock *BB = MI->getParent();
  529. MachineBasicBlock::iterator ItrMI = MI;
  530. // Scan forward through BB for a use/def of EFLAGS.
  531. for (auto I = std::next(ItrMI), E = BB->end(); I != E; ++I) {
  532. if (I->readsRegister(X86::EFLAGS))
  533. return true;
  534. if (I->definesRegister(X86::EFLAGS))
  535. return false;
  536. }
  537. // We hit the end of the block, check whether EFLAGS is live into a successor.
  538. for (MachineBasicBlock *Succ : BB->successors())
  539. if (Succ->isLiveIn(X86::EFLAGS))
  540. return true;
  541. return false;
  542. }
  543. /// Given /p First CMOV instruction and /p Last CMOV instruction representing a
  544. /// group of CMOV instructions, which may contain debug instructions in between,
  545. /// move all debug instructions to after the last CMOV instruction, making the
  546. /// CMOV group consecutive.
  547. static void packCmovGroup(MachineInstr *First, MachineInstr *Last) {
  548. assert(X86::getCondFromCMov(*Last) != X86::COND_INVALID &&
  549. "Last instruction in a CMOV group must be a CMOV instruction");
  550. SmallVector<MachineInstr *, 2> DBGInstructions;
  551. for (auto I = First->getIterator(), E = Last->getIterator(); I != E; I++) {
  552. if (I->isDebugInstr())
  553. DBGInstructions.push_back(&*I);
  554. }
  555. // Splice the debug instruction after the cmov group.
  556. MachineBasicBlock *MBB = First->getParent();
  557. for (auto *MI : DBGInstructions)
  558. MBB->insertAfter(Last, MI->removeFromParent());
  559. }
  560. void X86CmovConverterPass::convertCmovInstsToBranches(
  561. SmallVectorImpl<MachineInstr *> &Group) const {
  562. assert(!Group.empty() && "No CMOV instructions to convert");
  563. ++NumOfOptimizedCmovGroups;
  564. // If the CMOV group is not packed, e.g., there are debug instructions between
  565. // first CMOV and last CMOV, then pack the group and make the CMOV instruction
  566. // consecutive by moving the debug instructions to after the last CMOV.
  567. packCmovGroup(Group.front(), Group.back());
  568. // To convert a CMOVcc instruction, we actually have to insert the diamond
  569. // control-flow pattern. The incoming instruction knows the destination vreg
  570. // to set, the condition code register to branch on, the true/false values to
  571. // select between, and a branch opcode to use.
  572. // Before
  573. // -----
  574. // MBB:
  575. // cond = cmp ...
  576. // v1 = CMOVge t1, f1, cond
  577. // v2 = CMOVlt t2, f2, cond
  578. // v3 = CMOVge v1, f3, cond
  579. //
  580. // After
  581. // -----
  582. // MBB:
  583. // cond = cmp ...
  584. // jge %SinkMBB
  585. //
  586. // FalseMBB:
  587. // jmp %SinkMBB
  588. //
  589. // SinkMBB:
  590. // %v1 = phi[%f1, %FalseMBB], [%t1, %MBB]
  591. // %v2 = phi[%t2, %FalseMBB], [%f2, %MBB] ; For CMOV with OppCC switch
  592. // ; true-value with false-value
  593. // %v3 = phi[%f3, %FalseMBB], [%t1, %MBB] ; Phi instruction cannot use
  594. // ; previous Phi instruction result
  595. MachineInstr &MI = *Group.front();
  596. MachineInstr *LastCMOV = Group.back();
  597. DebugLoc DL = MI.getDebugLoc();
  598. X86::CondCode CC = X86::CondCode(X86::getCondFromCMov(MI));
  599. X86::CondCode OppCC = X86::GetOppositeBranchCondition(CC);
  600. // Potentially swap the condition codes so that any memory operand to a CMOV
  601. // is in the *false* position instead of the *true* position. We can invert
  602. // any non-memory operand CMOV instructions to cope with this and we ensure
  603. // memory operand CMOVs are only included with a single condition code.
  604. if (llvm::any_of(Group, [&](MachineInstr *I) {
  605. return I->mayLoad() && X86::getCondFromCMov(*I) == CC;
  606. }))
  607. std::swap(CC, OppCC);
  608. MachineBasicBlock *MBB = MI.getParent();
  609. MachineFunction::iterator It = ++MBB->getIterator();
  610. MachineFunction *F = MBB->getParent();
  611. const BasicBlock *BB = MBB->getBasicBlock();
  612. MachineBasicBlock *FalseMBB = F->CreateMachineBasicBlock(BB);
  613. MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(BB);
  614. F->insert(It, FalseMBB);
  615. F->insert(It, SinkMBB);
  616. // If the EFLAGS register isn't dead in the terminator, then claim that it's
  617. // live into the sink and copy blocks.
  618. if (checkEFLAGSLive(LastCMOV)) {
  619. FalseMBB->addLiveIn(X86::EFLAGS);
  620. SinkMBB->addLiveIn(X86::EFLAGS);
  621. }
  622. // Transfer the remainder of BB and its successor edges to SinkMBB.
  623. SinkMBB->splice(SinkMBB->begin(), MBB,
  624. std::next(MachineBasicBlock::iterator(LastCMOV)), MBB->end());
  625. SinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
  626. // Add the false and sink blocks as its successors.
  627. MBB->addSuccessor(FalseMBB);
  628. MBB->addSuccessor(SinkMBB);
  629. // Create the conditional branch instruction.
  630. BuildMI(MBB, DL, TII->get(X86::JCC_1)).addMBB(SinkMBB).addImm(CC);
  631. // Add the sink block to the false block successors.
  632. FalseMBB->addSuccessor(SinkMBB);
  633. MachineInstrBuilder MIB;
  634. MachineBasicBlock::iterator MIItBegin = MachineBasicBlock::iterator(MI);
  635. MachineBasicBlock::iterator MIItEnd =
  636. std::next(MachineBasicBlock::iterator(LastCMOV));
  637. MachineBasicBlock::iterator FalseInsertionPoint = FalseMBB->begin();
  638. MachineBasicBlock::iterator SinkInsertionPoint = SinkMBB->begin();
  639. // First we need to insert an explicit load on the false path for any memory
  640. // operand. We also need to potentially do register rewriting here, but it is
  641. // simpler as the memory operands are always on the false path so we can
  642. // simply take that input, whatever it is.
  643. DenseMap<unsigned, unsigned> FalseBBRegRewriteTable;
  644. for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd;) {
  645. auto &MI = *MIIt++;
  646. // Skip any CMOVs in this group which don't load from memory.
  647. if (!MI.mayLoad()) {
  648. // Remember the false-side register input.
  649. Register FalseReg =
  650. MI.getOperand(X86::getCondFromCMov(MI) == CC ? 1 : 2).getReg();
  651. // Walk back through any intermediate cmovs referenced.
  652. while (true) {
  653. auto FRIt = FalseBBRegRewriteTable.find(FalseReg);
  654. if (FRIt == FalseBBRegRewriteTable.end())
  655. break;
  656. FalseReg = FRIt->second;
  657. }
  658. FalseBBRegRewriteTable[MI.getOperand(0).getReg()] = FalseReg;
  659. continue;
  660. }
  661. // The condition must be the *opposite* of the one we've decided to branch
  662. // on as the branch will go *around* the load and the load should happen
  663. // when the CMOV condition is false.
  664. assert(X86::getCondFromCMov(MI) == OppCC &&
  665. "Can only handle memory-operand cmov instructions with a condition "
  666. "opposite to the selected branch direction.");
  667. // The goal is to rewrite the cmov from:
  668. //
  669. // MBB:
  670. // %A = CMOVcc %B (tied), (mem)
  671. //
  672. // to
  673. //
  674. // MBB:
  675. // %A = CMOVcc %B (tied), %C
  676. // FalseMBB:
  677. // %C = MOV (mem)
  678. //
  679. // Which will allow the next loop to rewrite the CMOV in terms of a PHI:
  680. //
  681. // MBB:
  682. // JMP!cc SinkMBB
  683. // FalseMBB:
  684. // %C = MOV (mem)
  685. // SinkMBB:
  686. // %A = PHI [ %C, FalseMBB ], [ %B, MBB]
  687. // Get a fresh register to use as the destination of the MOV.
  688. const TargetRegisterClass *RC = MRI->getRegClass(MI.getOperand(0).getReg());
  689. Register TmpReg = MRI->createVirtualRegister(RC);
  690. SmallVector<MachineInstr *, 4> NewMIs;
  691. bool Unfolded = TII->unfoldMemoryOperand(*MBB->getParent(), MI, TmpReg,
  692. /*UnfoldLoad*/ true,
  693. /*UnfoldStore*/ false, NewMIs);
  694. (void)Unfolded;
  695. assert(Unfolded && "Should never fail to unfold a loading cmov!");
  696. // Move the new CMOV to just before the old one and reset any impacted
  697. // iterator.
  698. auto *NewCMOV = NewMIs.pop_back_val();
  699. assert(X86::getCondFromCMov(*NewCMOV) == OppCC &&
  700. "Last new instruction isn't the expected CMOV!");
  701. LLVM_DEBUG(dbgs() << "\tRewritten cmov: "; NewCMOV->dump());
  702. MBB->insert(MachineBasicBlock::iterator(MI), NewCMOV);
  703. if (&*MIItBegin == &MI)
  704. MIItBegin = MachineBasicBlock::iterator(NewCMOV);
  705. // Sink whatever instructions were needed to produce the unfolded operand
  706. // into the false block.
  707. for (auto *NewMI : NewMIs) {
  708. LLVM_DEBUG(dbgs() << "\tRewritten load instr: "; NewMI->dump());
  709. FalseMBB->insert(FalseInsertionPoint, NewMI);
  710. // Re-map any operands that are from other cmovs to the inputs for this block.
  711. for (auto &MOp : NewMI->uses()) {
  712. if (!MOp.isReg())
  713. continue;
  714. auto It = FalseBBRegRewriteTable.find(MOp.getReg());
  715. if (It == FalseBBRegRewriteTable.end())
  716. continue;
  717. MOp.setReg(It->second);
  718. // This might have been a kill when it referenced the cmov result, but
  719. // it won't necessarily be once rewritten.
  720. // FIXME: We could potentially improve this by tracking whether the
  721. // operand to the cmov was also a kill, and then skipping the PHI node
  722. // construction below.
  723. MOp.setIsKill(false);
  724. }
  725. }
  726. MBB->erase(&MI);
  727. // Add this PHI to the rewrite table.
  728. FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
  729. }
  730. // As we are creating the PHIs, we have to be careful if there is more than
  731. // one. Later CMOVs may reference the results of earlier CMOVs, but later
  732. // PHIs have to reference the individual true/false inputs from earlier PHIs.
  733. // That also means that PHI construction must work forward from earlier to
  734. // later, and that the code must maintain a mapping from earlier PHI's
  735. // destination registers, and the registers that went into the PHI.
  736. DenseMap<unsigned, std::pair<unsigned, unsigned>> RegRewriteTable;
  737. for (MachineBasicBlock::iterator MIIt = MIItBegin; MIIt != MIItEnd; ++MIIt) {
  738. Register DestReg = MIIt->getOperand(0).getReg();
  739. Register Op1Reg = MIIt->getOperand(1).getReg();
  740. Register Op2Reg = MIIt->getOperand(2).getReg();
  741. // If this CMOV we are processing is the opposite condition from the jump we
  742. // generated, then we have to swap the operands for the PHI that is going to
  743. // be generated.
  744. if (X86::getCondFromCMov(*MIIt) == OppCC)
  745. std::swap(Op1Reg, Op2Reg);
  746. auto Op1Itr = RegRewriteTable.find(Op1Reg);
  747. if (Op1Itr != RegRewriteTable.end())
  748. Op1Reg = Op1Itr->second.first;
  749. auto Op2Itr = RegRewriteTable.find(Op2Reg);
  750. if (Op2Itr != RegRewriteTable.end())
  751. Op2Reg = Op2Itr->second.second;
  752. // SinkMBB:
  753. // %Result = phi [ %FalseValue, FalseMBB ], [ %TrueValue, MBB ]
  754. // ...
  755. MIB = BuildMI(*SinkMBB, SinkInsertionPoint, DL, TII->get(X86::PHI), DestReg)
  756. .addReg(Op1Reg)
  757. .addMBB(FalseMBB)
  758. .addReg(Op2Reg)
  759. .addMBB(MBB);
  760. (void)MIB;
  761. LLVM_DEBUG(dbgs() << "\tFrom: "; MIIt->dump());
  762. LLVM_DEBUG(dbgs() << "\tTo: "; MIB->dump());
  763. // Add this PHI to the rewrite table.
  764. RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
  765. }
  766. // Now remove the CMOV(s).
  767. MBB->erase(MIItBegin, MIItEnd);
  768. // Add new basic blocks to MachineLoopInfo.
  769. if (MachineLoop *L = MLI->getLoopFor(MBB)) {
  770. L->addBasicBlockToLoop(FalseMBB, MLI->getBase());
  771. L->addBasicBlockToLoop(SinkMBB, MLI->getBase());
  772. }
  773. }
  774. INITIALIZE_PASS_BEGIN(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
  775. false, false)
  776. INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
  777. INITIALIZE_PASS_END(X86CmovConverterPass, DEBUG_TYPE, "X86 cmov Conversion",
  778. false, false)
  779. FunctionPass *llvm::createX86CmovConverterPass() {
  780. return new X86CmovConverterPass();
  781. }