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