1 //===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===// 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 // This pass performs peephole optimizations to clean up ugly code 10 // sequences at the MachineInstruction layer. It runs at the end of 11 // the SSA phases, following VSX swap removal. A pass of dead code 12 // elimination follows this one for quick clean-up of any dead 13 // instructions introduced here. Although we could do this as callbacks 14 // from the generic peephole pass, this would have a couple of bad 15 // effects: it might remove optimization opportunities for VSX swap 16 // removal, and it would miss cleanups made possible following VSX 17 // swap removal. 18 // 19 //===---------------------------------------------------------------------===// 20 21 #include "MCTargetDesc/PPCMCTargetDesc.h" 22 #include "MCTargetDesc/PPCPredicates.h" 23 #include "PPC.h" 24 #include "PPCInstrBuilder.h" 25 #include "PPCInstrInfo.h" 26 #include "PPCMachineFunctionInfo.h" 27 #include "PPCTargetMachine.h" 28 #include "llvm/ADT/Statistic.h" 29 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 30 #include "llvm/CodeGen/MachineDominators.h" 31 #include "llvm/CodeGen/MachineFunctionPass.h" 32 #include "llvm/CodeGen/MachineInstrBuilder.h" 33 #include "llvm/CodeGen/MachinePostDominators.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/InitializePasses.h" 36 #include "llvm/Support/Debug.h" 37 38 using namespace llvm; 39 40 #define DEBUG_TYPE "ppc-mi-peepholes" 41 42 STATISTIC(RemoveTOCSave, "Number of TOC saves removed"); 43 STATISTIC(MultiTOCSaves, 44 "Number of functions with multiple TOC saves that must be kept"); 45 STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue"); 46 STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions"); 47 STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions"); 48 STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI"); 49 STATISTIC(NumConvertedToImmediateForm, 50 "Number of instructions converted to their immediate form"); 51 STATISTIC(NumFunctionsEnteredInMIPeephole, 52 "Number of functions entered in PPC MI Peepholes"); 53 STATISTIC(NumFixedPointIterations, 54 "Number of fixed-point iterations converting reg-reg instructions " 55 "to reg-imm ones"); 56 STATISTIC(NumRotatesCollapsed, 57 "Number of pairs of rotate left, clear left/right collapsed"); 58 STATISTIC(NumEXTSWAndSLDICombined, 59 "Number of pairs of EXTSW and SLDI combined as EXTSWSLI"); 60 STATISTIC(NumX2FoundForPCRel, "Number of times the X2 TOC pointer has been " 61 "found when PC relative NOTOC is being used."); 62 63 static cl::opt<bool> 64 FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true), 65 cl::desc("Iterate to a fixed point when attempting to " 66 "convert reg-reg instructions to reg-imm")); 67 68 static cl::opt<bool> 69 ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true), 70 cl::desc("Convert eligible reg+reg instructions to reg+imm")); 71 72 static cl::opt<bool> 73 EnableSExtElimination("ppc-eliminate-signext", 74 cl::desc("enable elimination of sign-extensions"), 75 cl::init(false), cl::Hidden); 76 77 static cl::opt<bool> 78 EnableZExtElimination("ppc-eliminate-zeroext", 79 cl::desc("enable elimination of zero-extensions"), 80 cl::init(false), cl::Hidden); 81 82 namespace { 83 84 struct PPCMIPeephole : public MachineFunctionPass { 85 86 static char ID; 87 const PPCInstrInfo *TII; 88 MachineFunction *MF; 89 MachineRegisterInfo *MRI; 90 91 PPCMIPeephole() : MachineFunctionPass(ID) { 92 initializePPCMIPeepholePass(*PassRegistry::getPassRegistry()); 93 } 94 95 private: 96 MachineDominatorTree *MDT; 97 MachinePostDominatorTree *MPDT; 98 MachineBlockFrequencyInfo *MBFI; 99 uint64_t EntryFreq; 100 101 // Initialize class variables. 102 void initialize(MachineFunction &MFParm); 103 104 // Perform peepholes that cannot be skipped. 105 // Some peephole simplifications are required for correctness and will not 106 // be skipped even if skipFunction(MF.getFunction()) returns true. 107 void unskipableSimplifyCode(void); 108 109 // Perform peepholes. 110 bool simplifyCode(void); 111 112 // Perform peepholes. 113 bool eliminateRedundantCompare(void); 114 bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves); 115 bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase); 116 bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI); 117 void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves, 118 MachineInstr *MI); 119 120 public: 121 122 void getAnalysisUsage(AnalysisUsage &AU) const override { 123 AU.addRequired<MachineDominatorTree>(); 124 AU.addRequired<MachinePostDominatorTree>(); 125 AU.addRequired<MachineBlockFrequencyInfo>(); 126 AU.addPreserved<MachineDominatorTree>(); 127 AU.addPreserved<MachinePostDominatorTree>(); 128 AU.addPreserved<MachineBlockFrequencyInfo>(); 129 MachineFunctionPass::getAnalysisUsage(AU); 130 } 131 132 // Main entry point for this pass. 133 bool runOnMachineFunction(MachineFunction &MF) override { 134 initialize(MF); 135 // FIXME: This introduces another complete traversal of the instructions 136 // in the function in the common case (function is not skipped). Although 137 // this is less than ideal for compile time, this code will go away once 138 // our PC-Rel implementation is complete. 139 unskipableSimplifyCode(); 140 if (skipFunction(MF.getFunction())) 141 return false; 142 return simplifyCode(); 143 } 144 }; 145 146 // Initialize class variables. 147 void PPCMIPeephole::initialize(MachineFunction &MFParm) { 148 MF = &MFParm; 149 MRI = &MF->getRegInfo(); 150 MDT = &getAnalysis<MachineDominatorTree>(); 151 MPDT = &getAnalysis<MachinePostDominatorTree>(); 152 MBFI = &getAnalysis<MachineBlockFrequencyInfo>(); 153 EntryFreq = MBFI->getEntryFreq(); 154 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo(); 155 LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n"); 156 LLVM_DEBUG(MF->dump()); 157 } 158 159 static MachineInstr *getVRegDefOrNull(MachineOperand *Op, 160 MachineRegisterInfo *MRI) { 161 assert(Op && "Invalid Operand!"); 162 if (!Op->isReg()) 163 return nullptr; 164 165 Register Reg = Op->getReg(); 166 if (!Register::isVirtualRegister(Reg)) 167 return nullptr; 168 169 return MRI->getVRegDef(Reg); 170 } 171 172 // This function returns number of known zero bits in output of MI 173 // starting from the most significant bit. 174 static unsigned 175 getKnownLeadingZeroCount(MachineInstr *MI, const PPCInstrInfo *TII) { 176 unsigned Opcode = MI->getOpcode(); 177 if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec || 178 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec) 179 return MI->getOperand(3).getImm(); 180 181 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) && 182 MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm()) 183 return MI->getOperand(3).getImm(); 184 185 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec || 186 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec || 187 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) && 188 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm()) 189 return 32 + MI->getOperand(3).getImm(); 190 191 if (Opcode == PPC::ANDI_rec) { 192 uint16_t Imm = MI->getOperand(2).getImm(); 193 return 48 + countLeadingZeros(Imm); 194 } 195 196 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec || 197 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec || 198 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8) 199 // The result ranges from 0 to 32. 200 return 58; 201 202 if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec || 203 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec) 204 // The result ranges from 0 to 64. 205 return 57; 206 207 if (Opcode == PPC::LHZ || Opcode == PPC::LHZX || 208 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || 209 Opcode == PPC::LHZU || Opcode == PPC::LHZUX || 210 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8) 211 return 48; 212 213 if (Opcode == PPC::LBZ || Opcode == PPC::LBZX || 214 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || 215 Opcode == PPC::LBZU || Opcode == PPC::LBZUX || 216 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8) 217 return 56; 218 219 if (TII->isZeroExtended(*MI)) 220 return 32; 221 222 return 0; 223 } 224 225 // This function maintains a map for the pairs <TOC Save Instr, Keep> 226 // Each time a new TOC save is encountered, it checks if any of the existing 227 // ones are dominated by the new one. If so, it marks the existing one as 228 // redundant by setting it's entry in the map as false. It then adds the new 229 // instruction to the map with either true or false depending on if any 230 // existing instructions dominated the new one. 231 void PPCMIPeephole::UpdateTOCSaves( 232 std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) { 233 assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here"); 234 assert(MF->getSubtarget<PPCSubtarget>().isELFv2ABI() && 235 "TOC-save removal only supported on ELFv2"); 236 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>(); 237 238 MachineBasicBlock *Entry = &MF->front(); 239 uint64_t CurrBlockFreq = MBFI->getBlockFreq(MI->getParent()).getFrequency(); 240 241 // If the block in which the TOC save resides is in a block that 242 // post-dominates Entry, or a block that is hotter than entry (keep in mind 243 // that early MachineLICM has already run so the TOC save won't be hoisted) 244 // we can just do the save in the prologue. 245 if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry)) 246 FI->setMustSaveTOC(true); 247 248 // If we are saving the TOC in the prologue, all the TOC saves can be removed 249 // from the code. 250 if (FI->mustSaveTOC()) { 251 for (auto &TOCSave : TOCSaves) 252 TOCSave.second = false; 253 // Add new instruction to map. 254 TOCSaves[MI] = false; 255 return; 256 } 257 258 bool Keep = true; 259 for (auto It = TOCSaves.begin(); It != TOCSaves.end(); It++ ) { 260 MachineInstr *CurrInst = It->first; 261 // If new instruction dominates an existing one, mark existing one as 262 // redundant. 263 if (It->second && MDT->dominates(MI, CurrInst)) 264 It->second = false; 265 // Check if the new instruction is redundant. 266 if (MDT->dominates(CurrInst, MI)) { 267 Keep = false; 268 break; 269 } 270 } 271 // Add new instruction to map. 272 TOCSaves[MI] = Keep; 273 } 274 275 void PPCMIPeephole::unskipableSimplifyCode(void) { 276 // If this function has no uses of R2 there is nothing to do here. 277 if(MF->getRegInfo().use_empty(PPC::X2)) 278 return; 279 280 // This is only for PCRelative calls. 281 if (!MF->getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) { 282 return; 283 } 284 285 // This function has R2 so we need to mark an implicit def for it. 286 PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>(); 287 FuncInfo->setUsesTOCBasePtr(); 288 for (MachineBasicBlock &MBB : *MF) { 289 for (MachineInstr &MI : MBB) { 290 if (MI.getOpcode() == PPC::BL8_NOTOC) { 291 // At this point the BL8_NOTOC instruction is not really safe because it 292 // assumes that the caller does not need the TOC. It will be safe 293 // later once the full PC relative implementation is complete but it is 294 // not now. 295 // Here we are looking for X2. Since this is Pre-RA the only uses of X2 296 // would indicate the use of the TOC. We want to detect all uses of the 297 // TOC. Once the work is done we should not see any uses of the TOC. 298 // TODO: Once the implementation is complete this should be turned into 299 // an assert 300 Register Reg = MF->getSubtarget<PPCSubtarget>().getTOCPointerRegister(); 301 MachineOperand MO = MachineOperand::CreateReg(Reg, false, true); 302 MI.addOperand(*MF, MO); 303 MI.setDesc(TII->get(PPC::BL8_NOP)); 304 ++NumX2FoundForPCRel; 305 } 306 } 307 } 308 } 309 310 // Perform peephole optimizations. 311 bool PPCMIPeephole::simplifyCode(void) { 312 bool Simplified = false; 313 MachineInstr* ToErase = nullptr; 314 std::map<MachineInstr *, bool> TOCSaves; 315 const TargetRegisterInfo *TRI = &TII->getRegisterInfo(); 316 NumFunctionsEnteredInMIPeephole++; 317 if (ConvertRegReg) { 318 // Fixed-point conversion of reg/reg instructions fed by load-immediate 319 // into reg/imm instructions. FIXME: This is expensive, control it with 320 // an option. 321 bool SomethingChanged = false; 322 do { 323 NumFixedPointIterations++; 324 SomethingChanged = false; 325 for (MachineBasicBlock &MBB : *MF) { 326 for (MachineInstr &MI : MBB) { 327 if (MI.isDebugInstr()) 328 continue; 329 330 if (TII->convertToImmediateForm(MI)) { 331 // We don't erase anything in case the def has other uses. Let DCE 332 // remove it if it can be removed. 333 LLVM_DEBUG(dbgs() << "Converted instruction to imm form: "); 334 LLVM_DEBUG(MI.dump()); 335 NumConvertedToImmediateForm++; 336 SomethingChanged = true; 337 Simplified = true; 338 continue; 339 } 340 } 341 } 342 } while (SomethingChanged && FixedPointRegToImm); 343 } 344 345 for (MachineBasicBlock &MBB : *MF) { 346 for (MachineInstr &MI : MBB) { 347 348 // If the previous instruction was marked for elimination, 349 // remove it now. 350 if (ToErase) { 351 ToErase->eraseFromParent(); 352 ToErase = nullptr; 353 } 354 355 // Ignore debug instructions. 356 if (MI.isDebugInstr()) 357 continue; 358 359 // Per-opcode peepholes. 360 switch (MI.getOpcode()) { 361 362 default: 363 break; 364 365 case PPC::STD: { 366 MachineFrameInfo &MFI = MF->getFrameInfo(); 367 if (MFI.hasVarSizedObjects() || 368 !MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) 369 break; 370 // When encountering a TOC save instruction, call UpdateTOCSaves 371 // to add it to the TOCSaves map and mark any existing TOC saves 372 // it dominates as redundant. 373 if (TII->isTOCSaveMI(MI)) 374 UpdateTOCSaves(TOCSaves, &MI); 375 break; 376 } 377 case PPC::XXPERMDI: { 378 // Perform simplifications of 2x64 vector swaps and splats. 379 // A swap is identified by an immediate value of 2, and a splat 380 // is identified by an immediate value of 0 or 3. 381 int Immed = MI.getOperand(3).getImm(); 382 383 if (Immed == 1) 384 break; 385 386 // For each of these simplifications, we need the two source 387 // regs to match. Unfortunately, MachineCSE ignores COPY and 388 // SUBREG_TO_REG, so for example we can see 389 // XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed. 390 // We have to look through chains of COPY and SUBREG_TO_REG 391 // to find the real source values for comparison. 392 unsigned TrueReg1 = 393 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI); 394 unsigned TrueReg2 = 395 TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI); 396 397 if (!(TrueReg1 == TrueReg2 && Register::isVirtualRegister(TrueReg1))) 398 break; 399 400 MachineInstr *DefMI = MRI->getVRegDef(TrueReg1); 401 402 if (!DefMI) 403 break; 404 405 unsigned DefOpc = DefMI->getOpcode(); 406 407 // If this is a splat fed by a splatting load, the splat is 408 // redundant. Replace with a copy. This doesn't happen directly due 409 // to code in PPCDAGToDAGISel.cpp, but it can happen when converting 410 // a load of a double to a vector of 64-bit integers. 411 auto isConversionOfLoadAndSplat = [=]() -> bool { 412 if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS) 413 return false; 414 unsigned FeedReg1 = 415 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI); 416 if (Register::isVirtualRegister(FeedReg1)) { 417 MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1); 418 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX) 419 return true; 420 } 421 return false; 422 }; 423 if ((Immed == 0 || Immed == 3) && 424 (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) { 425 LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat " 426 "to load-and-splat/copy: "); 427 LLVM_DEBUG(MI.dump()); 428 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 429 MI.getOperand(0).getReg()) 430 .add(MI.getOperand(1)); 431 ToErase = &MI; 432 Simplified = true; 433 } 434 435 // If this is a splat or a swap fed by another splat, we 436 // can replace it with a copy. 437 if (DefOpc == PPC::XXPERMDI) { 438 unsigned DefReg1 = DefMI->getOperand(1).getReg(); 439 unsigned DefReg2 = DefMI->getOperand(2).getReg(); 440 unsigned DefImmed = DefMI->getOperand(3).getImm(); 441 442 // If the two inputs are not the same register, check to see if 443 // they originate from the same virtual register after only 444 // copy-like instructions. 445 if (DefReg1 != DefReg2) { 446 unsigned FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI); 447 unsigned FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI); 448 449 if (!(FeedReg1 == FeedReg2 && 450 Register::isVirtualRegister(FeedReg1))) 451 break; 452 } 453 454 if (DefImmed == 0 || DefImmed == 3) { 455 LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat " 456 "to splat/copy: "); 457 LLVM_DEBUG(MI.dump()); 458 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 459 MI.getOperand(0).getReg()) 460 .add(MI.getOperand(1)); 461 ToErase = &MI; 462 Simplified = true; 463 } 464 465 // If this is a splat fed by a swap, we can simplify modify 466 // the splat to splat the other value from the swap's input 467 // parameter. 468 else if ((Immed == 0 || Immed == 3) && DefImmed == 2) { 469 LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: "); 470 LLVM_DEBUG(MI.dump()); 471 MI.getOperand(1).setReg(DefReg1); 472 MI.getOperand(2).setReg(DefReg2); 473 MI.getOperand(3).setImm(3 - Immed); 474 Simplified = true; 475 } 476 477 // If this is a swap fed by a swap, we can replace it 478 // with a copy from the first swap's input. 479 else if (Immed == 2 && DefImmed == 2) { 480 LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: "); 481 LLVM_DEBUG(MI.dump()); 482 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 483 MI.getOperand(0).getReg()) 484 .add(DefMI->getOperand(1)); 485 ToErase = &MI; 486 Simplified = true; 487 } 488 } else if ((Immed == 0 || Immed == 3) && DefOpc == PPC::XXPERMDIs && 489 (DefMI->getOperand(2).getImm() == 0 || 490 DefMI->getOperand(2).getImm() == 3)) { 491 // Splat fed by another splat - switch the output of the first 492 // and remove the second. 493 DefMI->getOperand(0).setReg(MI.getOperand(0).getReg()); 494 ToErase = &MI; 495 Simplified = true; 496 LLVM_DEBUG(dbgs() << "Removing redundant splat: "); 497 LLVM_DEBUG(MI.dump()); 498 } 499 break; 500 } 501 case PPC::VSPLTB: 502 case PPC::VSPLTH: 503 case PPC::XXSPLTW: { 504 unsigned MyOpcode = MI.getOpcode(); 505 unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2; 506 unsigned TrueReg = 507 TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI); 508 if (!Register::isVirtualRegister(TrueReg)) 509 break; 510 MachineInstr *DefMI = MRI->getVRegDef(TrueReg); 511 if (!DefMI) 512 break; 513 unsigned DefOpcode = DefMI->getOpcode(); 514 auto isConvertOfSplat = [=]() -> bool { 515 if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS) 516 return false; 517 Register ConvReg = DefMI->getOperand(1).getReg(); 518 if (!Register::isVirtualRegister(ConvReg)) 519 return false; 520 MachineInstr *Splt = MRI->getVRegDef(ConvReg); 521 return Splt && (Splt->getOpcode() == PPC::LXVWSX || 522 Splt->getOpcode() == PPC::XXSPLTW); 523 }; 524 bool AlreadySplat = (MyOpcode == DefOpcode) || 525 (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) || 526 (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) || 527 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) || 528 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) || 529 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)|| 530 (MyOpcode == PPC::XXSPLTW && isConvertOfSplat()); 531 // If the instruction[s] that feed this splat have already splat 532 // the value, this splat is redundant. 533 if (AlreadySplat) { 534 LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: "); 535 LLVM_DEBUG(MI.dump()); 536 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 537 MI.getOperand(0).getReg()) 538 .add(MI.getOperand(OpNo)); 539 ToErase = &MI; 540 Simplified = true; 541 } 542 // Splat fed by a shift. Usually when we align value to splat into 543 // vector element zero. 544 if (DefOpcode == PPC::XXSLDWI) { 545 Register ShiftRes = DefMI->getOperand(0).getReg(); 546 Register ShiftOp1 = DefMI->getOperand(1).getReg(); 547 Register ShiftOp2 = DefMI->getOperand(2).getReg(); 548 unsigned ShiftImm = DefMI->getOperand(3).getImm(); 549 unsigned SplatImm = MI.getOperand(2).getImm(); 550 if (ShiftOp1 == ShiftOp2) { 551 unsigned NewElem = (SplatImm + ShiftImm) & 0x3; 552 if (MRI->hasOneNonDBGUse(ShiftRes)) { 553 LLVM_DEBUG(dbgs() << "Removing redundant shift: "); 554 LLVM_DEBUG(DefMI->dump()); 555 ToErase = DefMI; 556 } 557 Simplified = true; 558 LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm 559 << " to " << NewElem << " in instruction: "); 560 LLVM_DEBUG(MI.dump()); 561 MI.getOperand(1).setReg(ShiftOp1); 562 MI.getOperand(2).setImm(NewElem); 563 } 564 } 565 break; 566 } 567 case PPC::XVCVDPSP: { 568 // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant. 569 unsigned TrueReg = 570 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI); 571 if (!Register::isVirtualRegister(TrueReg)) 572 break; 573 MachineInstr *DefMI = MRI->getVRegDef(TrueReg); 574 575 // This can occur when building a vector of single precision or integer 576 // values. 577 if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) { 578 unsigned DefsReg1 = 579 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI); 580 unsigned DefsReg2 = 581 TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI); 582 if (!Register::isVirtualRegister(DefsReg1) || 583 !Register::isVirtualRegister(DefsReg2)) 584 break; 585 MachineInstr *P1 = MRI->getVRegDef(DefsReg1); 586 MachineInstr *P2 = MRI->getVRegDef(DefsReg2); 587 588 if (!P1 || !P2) 589 break; 590 591 // Remove the passed FRSP/XSRSP instruction if it only feeds this MI 592 // and set any uses of that FRSP/XSRSP (in this MI) to the source of 593 // the FRSP/XSRSP. 594 auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) { 595 unsigned Opc = RoundInstr->getOpcode(); 596 if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) && 597 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) { 598 Simplified = true; 599 Register ConvReg1 = RoundInstr->getOperand(1).getReg(); 600 Register FRSPDefines = RoundInstr->getOperand(0).getReg(); 601 MachineInstr &Use = *(MRI->use_instr_begin(FRSPDefines)); 602 for (int i = 0, e = Use.getNumOperands(); i < e; ++i) 603 if (Use.getOperand(i).isReg() && 604 Use.getOperand(i).getReg() == FRSPDefines) 605 Use.getOperand(i).setReg(ConvReg1); 606 LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n"); 607 LLVM_DEBUG(RoundInstr->dump()); 608 LLVM_DEBUG(dbgs() << "As it feeds instruction:\n"); 609 LLVM_DEBUG(MI.dump()); 610 LLVM_DEBUG(dbgs() << "Through instruction:\n"); 611 LLVM_DEBUG(DefMI->dump()); 612 RoundInstr->eraseFromParent(); 613 } 614 }; 615 616 // If the input to XVCVDPSP is a vector that was built (even 617 // partially) out of FRSP's, the FRSP(s) can safely be removed 618 // since this instruction performs the same operation. 619 if (P1 != P2) { 620 removeFRSPIfPossible(P1); 621 removeFRSPIfPossible(P2); 622 break; 623 } 624 removeFRSPIfPossible(P1); 625 } 626 break; 627 } 628 case PPC::EXTSH: 629 case PPC::EXTSH8: 630 case PPC::EXTSH8_32_64: { 631 if (!EnableSExtElimination) break; 632 Register NarrowReg = MI.getOperand(1).getReg(); 633 if (!Register::isVirtualRegister(NarrowReg)) 634 break; 635 636 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg); 637 // If we've used a zero-extending load that we will sign-extend, 638 // just do a sign-extending load. 639 if (SrcMI->getOpcode() == PPC::LHZ || 640 SrcMI->getOpcode() == PPC::LHZX) { 641 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg())) 642 break; 643 auto is64Bit = [] (unsigned Opcode) { 644 return Opcode == PPC::EXTSH8; 645 }; 646 auto isXForm = [] (unsigned Opcode) { 647 return Opcode == PPC::LHZX; 648 }; 649 auto getSextLoadOp = [] (bool is64Bit, bool isXForm) { 650 if (is64Bit) 651 if (isXForm) return PPC::LHAX8; 652 else return PPC::LHA8; 653 else 654 if (isXForm) return PPC::LHAX; 655 else return PPC::LHA; 656 }; 657 unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()), 658 isXForm(SrcMI->getOpcode())); 659 LLVM_DEBUG(dbgs() << "Zero-extending load\n"); 660 LLVM_DEBUG(SrcMI->dump()); 661 LLVM_DEBUG(dbgs() << "and sign-extension\n"); 662 LLVM_DEBUG(MI.dump()); 663 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n"); 664 SrcMI->setDesc(TII->get(Opc)); 665 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg()); 666 ToErase = &MI; 667 Simplified = true; 668 NumEliminatedSExt++; 669 } 670 break; 671 } 672 case PPC::EXTSW: 673 case PPC::EXTSW_32: 674 case PPC::EXTSW_32_64: { 675 if (!EnableSExtElimination) break; 676 Register NarrowReg = MI.getOperand(1).getReg(); 677 if (!Register::isVirtualRegister(NarrowReg)) 678 break; 679 680 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg); 681 // If we've used a zero-extending load that we will sign-extend, 682 // just do a sign-extending load. 683 if (SrcMI->getOpcode() == PPC::LWZ || 684 SrcMI->getOpcode() == PPC::LWZX) { 685 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg())) 686 break; 687 auto is64Bit = [] (unsigned Opcode) { 688 return Opcode == PPC::EXTSW || Opcode == PPC::EXTSW_32_64; 689 }; 690 auto isXForm = [] (unsigned Opcode) { 691 return Opcode == PPC::LWZX; 692 }; 693 auto getSextLoadOp = [] (bool is64Bit, bool isXForm) { 694 if (is64Bit) 695 if (isXForm) return PPC::LWAX; 696 else return PPC::LWA; 697 else 698 if (isXForm) return PPC::LWAX_32; 699 else return PPC::LWA_32; 700 }; 701 unsigned Opc = getSextLoadOp(is64Bit(MI.getOpcode()), 702 isXForm(SrcMI->getOpcode())); 703 LLVM_DEBUG(dbgs() << "Zero-extending load\n"); 704 LLVM_DEBUG(SrcMI->dump()); 705 LLVM_DEBUG(dbgs() << "and sign-extension\n"); 706 LLVM_DEBUG(MI.dump()); 707 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n"); 708 SrcMI->setDesc(TII->get(Opc)); 709 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg()); 710 ToErase = &MI; 711 Simplified = true; 712 NumEliminatedSExt++; 713 } else if (MI.getOpcode() == PPC::EXTSW_32_64 && 714 TII->isSignExtended(*SrcMI)) { 715 // We can eliminate EXTSW if the input is known to be already 716 // sign-extended. 717 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n"); 718 Register TmpReg = 719 MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass); 720 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF), 721 TmpReg); 722 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG), 723 MI.getOperand(0).getReg()) 724 .addReg(TmpReg) 725 .addReg(NarrowReg) 726 .addImm(PPC::sub_32); 727 ToErase = &MI; 728 Simplified = true; 729 NumEliminatedSExt++; 730 } 731 break; 732 } 733 case PPC::RLDICL: { 734 // We can eliminate RLDICL (e.g. for zero-extension) 735 // if all bits to clear are already zero in the input. 736 // This code assume following code sequence for zero-extension. 737 // %6 = COPY %5:sub_32; (optional) 738 // %8 = IMPLICIT_DEF; 739 // %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32; 740 if (!EnableZExtElimination) break; 741 742 if (MI.getOperand(2).getImm() != 0) 743 break; 744 745 Register SrcReg = MI.getOperand(1).getReg(); 746 if (!Register::isVirtualRegister(SrcReg)) 747 break; 748 749 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 750 if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG && 751 SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg())) 752 break; 753 754 MachineInstr *ImpDefMI, *SubRegMI; 755 ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg()); 756 SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg()); 757 if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break; 758 759 SrcMI = SubRegMI; 760 if (SubRegMI->getOpcode() == PPC::COPY) { 761 Register CopyReg = SubRegMI->getOperand(1).getReg(); 762 if (Register::isVirtualRegister(CopyReg)) 763 SrcMI = MRI->getVRegDef(CopyReg); 764 } 765 766 unsigned KnownZeroCount = getKnownLeadingZeroCount(SrcMI, TII); 767 if (MI.getOperand(3).getImm() <= KnownZeroCount) { 768 LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n"); 769 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 770 MI.getOperand(0).getReg()) 771 .addReg(SrcReg); 772 ToErase = &MI; 773 Simplified = true; 774 NumEliminatedZExt++; 775 } 776 break; 777 } 778 779 // TODO: Any instruction that has an immediate form fed only by a PHI 780 // whose operands are all load immediate can be folded away. We currently 781 // do this for ADD instructions, but should expand it to arithmetic and 782 // binary instructions with immediate forms in the future. 783 case PPC::ADD4: 784 case PPC::ADD8: { 785 auto isSingleUsePHI = [&](MachineOperand *PhiOp) { 786 assert(PhiOp && "Invalid Operand!"); 787 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI); 788 789 return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) && 790 MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg()); 791 }; 792 793 auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp, 794 MachineOperand *PhiOp) { 795 assert(PhiOp && "Invalid Operand!"); 796 assert(DominatorOp && "Invalid Operand!"); 797 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI); 798 MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI); 799 800 // Note: the vregs only show up at odd indices position of PHI Node, 801 // the even indices position save the BB info. 802 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) { 803 MachineInstr *LiMI = 804 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI); 805 if (!LiMI || 806 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8) 807 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) || 808 !MDT->dominates(DefDomMI, LiMI)) 809 return false; 810 } 811 812 return true; 813 }; 814 815 MachineOperand Op1 = MI.getOperand(1); 816 MachineOperand Op2 = MI.getOperand(2); 817 if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2)) 818 std::swap(Op1, Op2); 819 else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1)) 820 break; // We don't have an ADD fed by LI's that can be transformed 821 822 // Now we know that Op1 is the PHI node and Op2 is the dominator 823 Register DominatorReg = Op2.getReg(); 824 825 const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8 826 ? &PPC::G8RC_and_G8RC_NOX0RegClass 827 : &PPC::GPRC_and_GPRC_NOR0RegClass; 828 MRI->setRegClass(DominatorReg, TRC); 829 830 // replace LIs with ADDIs 831 MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI); 832 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) { 833 MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI); 834 LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: "); 835 LLVM_DEBUG(LiMI->dump()); 836 837 // There could be repeated registers in the PHI, e.g: %1 = 838 // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've 839 // already replaced the def instruction, skip. 840 if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8) 841 continue; 842 843 assert((LiMI->getOpcode() == PPC::LI || 844 LiMI->getOpcode() == PPC::LI8) && 845 "Invalid Opcode!"); 846 auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI 847 LiMI->RemoveOperand(1); // remove the imm of LI 848 LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI 849 : PPC::ADDI8)); 850 MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI) 851 .addReg(DominatorReg) 852 .addImm(LiImm); // restore the imm of LI 853 LLVM_DEBUG(LiMI->dump()); 854 } 855 856 // Replace ADD with COPY 857 LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: "); 858 LLVM_DEBUG(MI.dump()); 859 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 860 MI.getOperand(0).getReg()) 861 .add(Op1); 862 ToErase = &MI; 863 Simplified = true; 864 NumOptADDLIs++; 865 break; 866 } 867 case PPC::RLDICR: { 868 Simplified |= emitRLDICWhenLoweringJumpTables(MI) || 869 combineSEXTAndSHL(MI, ToErase); 870 break; 871 } 872 case PPC::RLWINM: 873 case PPC::RLWINM_rec: 874 case PPC::RLWINM8: 875 case PPC::RLWINM8_rec: { 876 unsigned FoldingReg = MI.getOperand(1).getReg(); 877 if (!Register::isVirtualRegister(FoldingReg)) 878 break; 879 880 MachineInstr *SrcMI = MRI->getVRegDef(FoldingReg); 881 if (SrcMI->getOpcode() != PPC::RLWINM && 882 SrcMI->getOpcode() != PPC::RLWINM_rec && 883 SrcMI->getOpcode() != PPC::RLWINM8 && 884 SrcMI->getOpcode() != PPC::RLWINM8_rec) 885 break; 886 assert((MI.getOperand(2).isImm() && MI.getOperand(3).isImm() && 887 MI.getOperand(4).isImm() && SrcMI->getOperand(2).isImm() && 888 SrcMI->getOperand(3).isImm() && SrcMI->getOperand(4).isImm()) && 889 "Invalid PPC::RLWINM Instruction!"); 890 uint64_t SHSrc = SrcMI->getOperand(2).getImm(); 891 uint64_t SHMI = MI.getOperand(2).getImm(); 892 uint64_t MBSrc = SrcMI->getOperand(3).getImm(); 893 uint64_t MBMI = MI.getOperand(3).getImm(); 894 uint64_t MESrc = SrcMI->getOperand(4).getImm(); 895 uint64_t MEMI = MI.getOperand(4).getImm(); 896 897 assert((MEMI < 32 && MESrc < 32 && MBMI < 32 && MBSrc < 32) && 898 "Invalid PPC::RLWINM Instruction!"); 899 900 // If MBMI is bigger than MEMI, we always can not get run of ones. 901 // RotatedSrcMask non-wrap: 902 // 0........31|32........63 903 // RotatedSrcMask: B---E B---E 904 // MaskMI: -----------|--E B------ 905 // Result: ----- --- (Bad candidate) 906 // 907 // RotatedSrcMask wrap: 908 // 0........31|32........63 909 // RotatedSrcMask: --E B----|--E B---- 910 // MaskMI: -----------|--E B------ 911 // Result: --- -----|--- ----- (Bad candidate) 912 // 913 // One special case is RotatedSrcMask is a full set mask. 914 // RotatedSrcMask full: 915 // 0........31|32........63 916 // RotatedSrcMask: ------EB---|-------EB--- 917 // MaskMI: -----------|--E B------ 918 // Result: -----------|--- ------- (Good candidate) 919 920 // Mark special case. 921 bool SrcMaskFull = (MBSrc - MESrc == 1) || (MBSrc == 0 && MESrc == 31); 922 923 // For other MBMI > MEMI cases, just return. 924 if ((MBMI > MEMI) && !SrcMaskFull) 925 break; 926 927 // Handle MBMI <= MEMI cases. 928 APInt MaskMI = APInt::getBitsSetWithWrap(32, 32 - MEMI - 1, 32 - MBMI); 929 // In MI, we only need low 32 bits of SrcMI, just consider about low 32 930 // bit of SrcMI mask. Note that in APInt, lowerest bit is at index 0, 931 // while in PowerPC ISA, lowerest bit is at index 63. 932 APInt MaskSrc = 933 APInt::getBitsSetWithWrap(32, 32 - MESrc - 1, 32 - MBSrc); 934 // Current APInt::getBitsSetWithWrap sets all bits to 0 if loBit is 935 // equal to highBit. 936 // If MBSrc - MESrc == 1, we expect a full set mask instead of Null. 937 if (SrcMaskFull && (MBSrc - MESrc == 1)) 938 MaskSrc.setAllBits(); 939 940 APInt RotatedSrcMask = MaskSrc.rotl(SHMI); 941 APInt FinalMask = RotatedSrcMask & MaskMI; 942 uint32_t NewMB, NewME; 943 944 // If final mask is 0, MI result should be 0 too. 945 if (FinalMask.isNullValue()) { 946 bool Is64Bit = (MI.getOpcode() == PPC::RLWINM8 || 947 MI.getOpcode() == PPC::RLWINM8_rec); 948 949 Simplified = true; 950 951 LLVM_DEBUG(dbgs() << "Replace Instr: "); 952 LLVM_DEBUG(MI.dump()); 953 954 if (MI.getOpcode() == PPC::RLWINM || MI.getOpcode() == PPC::RLWINM8) { 955 // Replace MI with "LI 0" 956 MI.RemoveOperand(4); 957 MI.RemoveOperand(3); 958 MI.RemoveOperand(2); 959 MI.getOperand(1).ChangeToImmediate(0); 960 MI.setDesc(TII->get(Is64Bit ? PPC::LI8 : PPC::LI)); 961 } else { 962 // Replace MI with "ANDI_rec reg, 0" 963 MI.RemoveOperand(4); 964 MI.RemoveOperand(3); 965 MI.getOperand(2).setImm(0); 966 MI.setDesc(TII->get(Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec)); 967 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg()); 968 if (SrcMI->getOperand(1).isKill()) { 969 MI.getOperand(1).setIsKill(true); 970 SrcMI->getOperand(1).setIsKill(false); 971 } else 972 // About to replace MI.getOperand(1), clear its kill flag. 973 MI.getOperand(1).setIsKill(false); 974 } 975 976 LLVM_DEBUG(dbgs() << "With: "); 977 LLVM_DEBUG(MI.dump()); 978 } else if ((isRunOfOnes((unsigned)(FinalMask.getZExtValue()), NewMB, 979 NewME) && NewMB <= NewME)|| SrcMaskFull) { 980 // Here we only handle MBMI <= MEMI case, so NewMB must be no bigger 981 // than NewME. Otherwise we get a 64 bit value after folding, but MI 982 // return a 32 bit value. 983 984 Simplified = true; 985 LLVM_DEBUG(dbgs() << "Converting Instr: "); 986 LLVM_DEBUG(MI.dump()); 987 988 uint16_t NewSH = (SHSrc + SHMI) % 32; 989 MI.getOperand(2).setImm(NewSH); 990 // If SrcMI mask is full, no need to update MBMI and MEMI. 991 if (!SrcMaskFull) { 992 MI.getOperand(3).setImm(NewMB); 993 MI.getOperand(4).setImm(NewME); 994 } 995 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg()); 996 if (SrcMI->getOperand(1).isKill()) { 997 MI.getOperand(1).setIsKill(true); 998 SrcMI->getOperand(1).setIsKill(false); 999 } else 1000 // About to replace MI.getOperand(1), clear its kill flag. 1001 MI.getOperand(1).setIsKill(false); 1002 1003 LLVM_DEBUG(dbgs() << "To: "); 1004 LLVM_DEBUG(MI.dump()); 1005 } 1006 if (Simplified) { 1007 // If FoldingReg has no non-debug use and it has no implicit def (it 1008 // is not RLWINMO or RLWINM8o), it's safe to delete its def SrcMI. 1009 // Otherwise keep it. 1010 ++NumRotatesCollapsed; 1011 if (MRI->use_nodbg_empty(FoldingReg) && !SrcMI->hasImplicitDef()) { 1012 ToErase = SrcMI; 1013 LLVM_DEBUG(dbgs() << "Delete dead instruction: "); 1014 LLVM_DEBUG(SrcMI->dump()); 1015 } 1016 } 1017 break; 1018 } 1019 } 1020 } 1021 1022 // If the last instruction was marked for elimination, 1023 // remove it now. 1024 if (ToErase) { 1025 ToErase->eraseFromParent(); 1026 ToErase = nullptr; 1027 } 1028 } 1029 1030 // Eliminate all the TOC save instructions which are redundant. 1031 Simplified |= eliminateRedundantTOCSaves(TOCSaves); 1032 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>(); 1033 if (FI->mustSaveTOC()) 1034 NumTOCSavesInPrologue++; 1035 1036 // We try to eliminate redundant compare instruction. 1037 Simplified |= eliminateRedundantCompare(); 1038 1039 return Simplified; 1040 } 1041 1042 // helper functions for eliminateRedundantCompare 1043 static bool isEqOrNe(MachineInstr *BI) { 1044 PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm(); 1045 unsigned PredCond = PPC::getPredicateCondition(Pred); 1046 return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE); 1047 } 1048 1049 static bool isSupportedCmpOp(unsigned opCode) { 1050 return (opCode == PPC::CMPLD || opCode == PPC::CMPD || 1051 opCode == PPC::CMPLW || opCode == PPC::CMPW || 1052 opCode == PPC::CMPLDI || opCode == PPC::CMPDI || 1053 opCode == PPC::CMPLWI || opCode == PPC::CMPWI); 1054 } 1055 1056 static bool is64bitCmpOp(unsigned opCode) { 1057 return (opCode == PPC::CMPLD || opCode == PPC::CMPD || 1058 opCode == PPC::CMPLDI || opCode == PPC::CMPDI); 1059 } 1060 1061 static bool isSignedCmpOp(unsigned opCode) { 1062 return (opCode == PPC::CMPD || opCode == PPC::CMPW || 1063 opCode == PPC::CMPDI || opCode == PPC::CMPWI); 1064 } 1065 1066 static unsigned getSignedCmpOpCode(unsigned opCode) { 1067 if (opCode == PPC::CMPLD) return PPC::CMPD; 1068 if (opCode == PPC::CMPLW) return PPC::CMPW; 1069 if (opCode == PPC::CMPLDI) return PPC::CMPDI; 1070 if (opCode == PPC::CMPLWI) return PPC::CMPWI; 1071 return opCode; 1072 } 1073 1074 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or 1075 // (LT x) to (LE x-1) 1076 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) { 1077 uint64_t Imm = CMPI->getOperand(2).getImm(); 1078 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode()); 1079 if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000)) 1080 return 0; 1081 1082 PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm(); 1083 unsigned PredCond = PPC::getPredicateCondition(Pred); 1084 unsigned PredHint = PPC::getPredicateHint(Pred); 1085 if (PredCond == PPC::PRED_GE) 1086 return PPC::getPredicate(PPC::PRED_GT, PredHint); 1087 if (PredCond == PPC::PRED_LT) 1088 return PPC::getPredicate(PPC::PRED_LE, PredHint); 1089 1090 return 0; 1091 } 1092 1093 // We can increment immediate x in (GT x) by changing it to (GE x+1) or 1094 // (LE x) to (LT x+1) 1095 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) { 1096 uint64_t Imm = CMPI->getOperand(2).getImm(); 1097 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode()); 1098 if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF)) 1099 return 0; 1100 1101 PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm(); 1102 unsigned PredCond = PPC::getPredicateCondition(Pred); 1103 unsigned PredHint = PPC::getPredicateHint(Pred); 1104 if (PredCond == PPC::PRED_GT) 1105 return PPC::getPredicate(PPC::PRED_GE, PredHint); 1106 if (PredCond == PPC::PRED_LE) 1107 return PPC::getPredicate(PPC::PRED_LT, PredHint); 1108 1109 return 0; 1110 } 1111 1112 // This takes a Phi node and returns a register value for the specified BB. 1113 static unsigned getIncomingRegForBlock(MachineInstr *Phi, 1114 MachineBasicBlock *MBB) { 1115 for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) { 1116 MachineOperand &MO = Phi->getOperand(I); 1117 if (MO.getMBB() == MBB) 1118 return Phi->getOperand(I-1).getReg(); 1119 } 1120 llvm_unreachable("invalid src basic block for this Phi node\n"); 1121 return 0; 1122 } 1123 1124 // This function tracks the source of the register through register copy. 1125 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2 1126 // assuming that the control comes from BB1 into BB2. 1127 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1, 1128 MachineBasicBlock *BB2, MachineRegisterInfo *MRI) { 1129 unsigned SrcReg = Reg; 1130 while (1) { 1131 unsigned NextReg = SrcReg; 1132 MachineInstr *Inst = MRI->getVRegDef(SrcReg); 1133 if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) { 1134 NextReg = getIncomingRegForBlock(Inst, BB1); 1135 // We track through PHI only once to avoid infinite loop. 1136 BB1 = nullptr; 1137 } 1138 else if (Inst->isFullCopy()) 1139 NextReg = Inst->getOperand(1).getReg(); 1140 if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg)) 1141 break; 1142 SrcReg = NextReg; 1143 } 1144 return SrcReg; 1145 } 1146 1147 static bool eligibleForCompareElimination(MachineBasicBlock &MBB, 1148 MachineBasicBlock *&PredMBB, 1149 MachineBasicBlock *&MBBtoMoveCmp, 1150 MachineRegisterInfo *MRI) { 1151 1152 auto isEligibleBB = [&](MachineBasicBlock &BB) { 1153 auto BII = BB.getFirstInstrTerminator(); 1154 // We optimize BBs ending with a conditional branch. 1155 // We check only for BCC here, not BCCLR, because BCCLR 1156 // will be formed only later in the pipeline. 1157 if (BB.succ_size() == 2 && 1158 BII != BB.instr_end() && 1159 (*BII).getOpcode() == PPC::BCC && 1160 (*BII).getOperand(1).isReg()) { 1161 // We optimize only if the condition code is used only by one BCC. 1162 Register CndReg = (*BII).getOperand(1).getReg(); 1163 if (!Register::isVirtualRegister(CndReg) || !MRI->hasOneNonDBGUse(CndReg)) 1164 return false; 1165 1166 MachineInstr *CMPI = MRI->getVRegDef(CndReg); 1167 // We assume compare and branch are in the same BB for ease of analysis. 1168 if (CMPI->getParent() != &BB) 1169 return false; 1170 1171 // We skip this BB if a physical register is used in comparison. 1172 for (MachineOperand &MO : CMPI->operands()) 1173 if (MO.isReg() && !Register::isVirtualRegister(MO.getReg())) 1174 return false; 1175 1176 return true; 1177 } 1178 return false; 1179 }; 1180 1181 // If this BB has more than one successor, we can create a new BB and 1182 // move the compare instruction in the new BB. 1183 // So far, we do not move compare instruction to a BB having multiple 1184 // successors to avoid potentially increasing code size. 1185 auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) { 1186 return BB.succ_size() == 1; 1187 }; 1188 1189 if (!isEligibleBB(MBB)) 1190 return false; 1191 1192 unsigned NumPredBBs = MBB.pred_size(); 1193 if (NumPredBBs == 1) { 1194 MachineBasicBlock *TmpMBB = *MBB.pred_begin(); 1195 if (isEligibleBB(*TmpMBB)) { 1196 PredMBB = TmpMBB; 1197 MBBtoMoveCmp = nullptr; 1198 return true; 1199 } 1200 } 1201 else if (NumPredBBs == 2) { 1202 // We check for partially redundant case. 1203 // So far, we support cases with only two predecessors 1204 // to avoid increasing the number of instructions. 1205 MachineBasicBlock::pred_iterator PI = MBB.pred_begin(); 1206 MachineBasicBlock *Pred1MBB = *PI; 1207 MachineBasicBlock *Pred2MBB = *(PI+1); 1208 1209 if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) { 1210 // We assume Pred1MBB is the BB containing the compare to be merged and 1211 // Pred2MBB is the BB to which we will append a compare instruction. 1212 // Hence we can proceed as is. 1213 } 1214 else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) { 1215 // We need to swap Pred1MBB and Pred2MBB to canonicalize. 1216 std::swap(Pred1MBB, Pred2MBB); 1217 } 1218 else return false; 1219 1220 // Here, Pred2MBB is the BB to which we need to append a compare inst. 1221 // We cannot move the compare instruction if operands are not available 1222 // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI). 1223 MachineInstr *BI = &*MBB.getFirstInstrTerminator(); 1224 MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg()); 1225 for (int I = 1; I <= 2; I++) 1226 if (CMPI->getOperand(I).isReg()) { 1227 MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg()); 1228 if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI) 1229 return false; 1230 } 1231 1232 PredMBB = Pred1MBB; 1233 MBBtoMoveCmp = Pred2MBB; 1234 return true; 1235 } 1236 1237 return false; 1238 } 1239 1240 // This function will iterate over the input map containing a pair of TOC save 1241 // instruction and a flag. The flag will be set to false if the TOC save is 1242 // proven redundant. This function will erase from the basic block all the TOC 1243 // saves marked as redundant. 1244 bool PPCMIPeephole::eliminateRedundantTOCSaves( 1245 std::map<MachineInstr *, bool> &TOCSaves) { 1246 bool Simplified = false; 1247 int NumKept = 0; 1248 for (auto TOCSave : TOCSaves) { 1249 if (!TOCSave.second) { 1250 TOCSave.first->eraseFromParent(); 1251 RemoveTOCSave++; 1252 Simplified = true; 1253 } else { 1254 NumKept++; 1255 } 1256 } 1257 1258 if (NumKept > 1) 1259 MultiTOCSaves++; 1260 1261 return Simplified; 1262 } 1263 1264 // If multiple conditional branches are executed based on the (essentially) 1265 // same comparison, we merge compare instructions into one and make multiple 1266 // conditional branches on this comparison. 1267 // For example, 1268 // if (a == 0) { ... } 1269 // else if (a < 0) { ... } 1270 // can be executed by one compare and two conditional branches instead of 1271 // two pairs of a compare and a conditional branch. 1272 // 1273 // This method merges two compare instructions in two MBBs and modifies the 1274 // compare and conditional branch instructions if needed. 1275 // For the above example, the input for this pass looks like: 1276 // cmplwi r3, 0 1277 // beq 0, .LBB0_3 1278 // cmpwi r3, -1 1279 // bgt 0, .LBB0_4 1280 // So, before merging two compares, we need to modify these instructions as 1281 // cmpwi r3, 0 ; cmplwi and cmpwi yield same result for beq 1282 // beq 0, .LBB0_3 1283 // cmpwi r3, 0 ; greather than -1 means greater or equal to 0 1284 // bge 0, .LBB0_4 1285 1286 bool PPCMIPeephole::eliminateRedundantCompare(void) { 1287 bool Simplified = false; 1288 1289 for (MachineBasicBlock &MBB2 : *MF) { 1290 MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr; 1291 1292 // For fully redundant case, we select two basic blocks MBB1 and MBB2 1293 // as an optimization target if 1294 // - both MBBs end with a conditional branch, 1295 // - MBB1 is the only predecessor of MBB2, and 1296 // - compare does not take a physical register as a operand in both MBBs. 1297 // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr. 1298 // 1299 // As partially redundant case, we additionally handle if MBB2 has one 1300 // additional predecessor, which has only one successor (MBB2). 1301 // In this case, we move the compare instruction originally in MBB2 into 1302 // MBBtoMoveCmp. This partially redundant case is typically appear by 1303 // compiling a while loop; here, MBBtoMoveCmp is the loop preheader. 1304 // 1305 // Overview of CFG of related basic blocks 1306 // Fully redundant case Partially redundant case 1307 // -------- ---------------- -------- 1308 // | MBB1 | (w/ 2 succ) | MBBtoMoveCmp | | MBB1 | (w/ 2 succ) 1309 // -------- ---------------- -------- 1310 // | \ (w/ 1 succ) \ | \ 1311 // | \ \ | \ 1312 // | \ | 1313 // -------- -------- 1314 // | MBB2 | (w/ 1 pred | MBB2 | (w/ 2 pred 1315 // -------- and 2 succ) -------- and 2 succ) 1316 // | \ | \ 1317 // | \ | \ 1318 // 1319 if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI)) 1320 continue; 1321 1322 MachineInstr *BI1 = &*MBB1->getFirstInstrTerminator(); 1323 MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg()); 1324 1325 MachineInstr *BI2 = &*MBB2.getFirstInstrTerminator(); 1326 MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg()); 1327 bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr); 1328 1329 // We cannot optimize an unsupported compare opcode or 1330 // a mix of 32-bit and 64-bit comaprisons 1331 if (!isSupportedCmpOp(CMPI1->getOpcode()) || 1332 !isSupportedCmpOp(CMPI2->getOpcode()) || 1333 is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode())) 1334 continue; 1335 1336 unsigned NewOpCode = 0; 1337 unsigned NewPredicate1 = 0, NewPredicate2 = 0; 1338 int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0; 1339 bool SwapOperands = false; 1340 1341 if (CMPI1->getOpcode() != CMPI2->getOpcode()) { 1342 // Typically, unsigned comparison is used for equality check, but 1343 // we replace it with a signed comparison if the comparison 1344 // to be merged is a signed comparison. 1345 // In other cases of opcode mismatch, we cannot optimize this. 1346 1347 // We cannot change opcode when comparing against an immediate 1348 // if the most significant bit of the immediate is one 1349 // due to the difference in sign extension. 1350 auto CmpAgainstImmWithSignBit = [](MachineInstr *I) { 1351 if (!I->getOperand(2).isImm()) 1352 return false; 1353 int16_t Imm = (int16_t)I->getOperand(2).getImm(); 1354 return Imm < 0; 1355 }; 1356 1357 if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) && 1358 CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode())) 1359 NewOpCode = CMPI1->getOpcode(); 1360 else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) && 1361 getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode()) 1362 NewOpCode = CMPI2->getOpcode(); 1363 else continue; 1364 } 1365 1366 if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) { 1367 // In case of comparisons between two registers, these two registers 1368 // must be same to merge two comparisons. 1369 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(), 1370 nullptr, nullptr, MRI); 1371 unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(), 1372 nullptr, nullptr, MRI); 1373 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(), 1374 MBB1, &MBB2, MRI); 1375 unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(), 1376 MBB1, &MBB2, MRI); 1377 1378 if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) { 1379 // Same pair of registers in the same order; ready to merge as is. 1380 } 1381 else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) { 1382 // Same pair of registers in different order. 1383 // We reverse the predicate to merge compare instructions. 1384 PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm(); 1385 NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred); 1386 // In case of partial redundancy, we need to swap operands 1387 // in another compare instruction. 1388 SwapOperands = true; 1389 } 1390 else continue; 1391 } 1392 else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) { 1393 // In case of comparisons between a register and an immediate, 1394 // the operand register must be same for two compare instructions. 1395 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(), 1396 nullptr, nullptr, MRI); 1397 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(), 1398 MBB1, &MBB2, MRI); 1399 if (Cmp1Operand1 != Cmp2Operand1) 1400 continue; 1401 1402 NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm(); 1403 NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm(); 1404 1405 // If immediate are not same, we try to adjust by changing predicate; 1406 // e.g. GT imm means GE (imm+1). 1407 if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) { 1408 int Diff = Imm1 - Imm2; 1409 if (Diff < -2 || Diff > 2) 1410 continue; 1411 1412 unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1); 1413 unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1); 1414 unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2); 1415 unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2); 1416 if (Diff == 2) { 1417 if (PredToInc2 && PredToDec1) { 1418 NewPredicate2 = PredToInc2; 1419 NewPredicate1 = PredToDec1; 1420 NewImm2++; 1421 NewImm1--; 1422 } 1423 } 1424 else if (Diff == 1) { 1425 if (PredToInc2) { 1426 NewImm2++; 1427 NewPredicate2 = PredToInc2; 1428 } 1429 else if (PredToDec1) { 1430 NewImm1--; 1431 NewPredicate1 = PredToDec1; 1432 } 1433 } 1434 else if (Diff == -1) { 1435 if (PredToDec2) { 1436 NewImm2--; 1437 NewPredicate2 = PredToDec2; 1438 } 1439 else if (PredToInc1) { 1440 NewImm1++; 1441 NewPredicate1 = PredToInc1; 1442 } 1443 } 1444 else if (Diff == -2) { 1445 if (PredToDec2 && PredToInc1) { 1446 NewPredicate2 = PredToDec2; 1447 NewPredicate1 = PredToInc1; 1448 NewImm2--; 1449 NewImm1++; 1450 } 1451 } 1452 } 1453 1454 // We cannot merge two compares if the immediates are not same. 1455 if (NewImm2 != NewImm1) 1456 continue; 1457 } 1458 1459 LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n"); 1460 LLVM_DEBUG(CMPI1->dump()); 1461 LLVM_DEBUG(BI1->dump()); 1462 LLVM_DEBUG(CMPI2->dump()); 1463 LLVM_DEBUG(BI2->dump()); 1464 1465 // We adjust opcode, predicates and immediate as we determined above. 1466 if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) { 1467 CMPI1->setDesc(TII->get(NewOpCode)); 1468 } 1469 if (NewPredicate1) { 1470 BI1->getOperand(0).setImm(NewPredicate1); 1471 } 1472 if (NewPredicate2) { 1473 BI2->getOperand(0).setImm(NewPredicate2); 1474 } 1475 if (NewImm1 != Imm1) { 1476 CMPI1->getOperand(2).setImm(NewImm1); 1477 } 1478 1479 if (IsPartiallyRedundant) { 1480 // We touch up the compare instruction in MBB2 and move it to 1481 // a previous BB to handle partially redundant case. 1482 if (SwapOperands) { 1483 Register Op1 = CMPI2->getOperand(1).getReg(); 1484 Register Op2 = CMPI2->getOperand(2).getReg(); 1485 CMPI2->getOperand(1).setReg(Op2); 1486 CMPI2->getOperand(2).setReg(Op1); 1487 } 1488 if (NewImm2 != Imm2) 1489 CMPI2->getOperand(2).setImm(NewImm2); 1490 1491 for (int I = 1; I <= 2; I++) { 1492 if (CMPI2->getOperand(I).isReg()) { 1493 MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg()); 1494 if (Inst->getParent() != &MBB2) 1495 continue; 1496 1497 assert(Inst->getOpcode() == PPC::PHI && 1498 "We cannot support if an operand comes from this BB."); 1499 unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp); 1500 CMPI2->getOperand(I).setReg(SrcReg); 1501 } 1502 } 1503 auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator()); 1504 MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2)); 1505 1506 DebugLoc DL = CMPI2->getDebugLoc(); 1507 Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass); 1508 BuildMI(MBB2, MBB2.begin(), DL, 1509 TII->get(PPC::PHI), NewVReg) 1510 .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1) 1511 .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp); 1512 BI2->getOperand(1).setReg(NewVReg); 1513 } 1514 else { 1515 // We finally eliminate compare instruction in MBB2. 1516 BI2->getOperand(1).setReg(BI1->getOperand(1).getReg()); 1517 CMPI2->eraseFromParent(); 1518 } 1519 BI2->getOperand(1).setIsKill(true); 1520 BI1->getOperand(1).setIsKill(false); 1521 1522 LLVM_DEBUG(dbgs() << "into a compare and two branches:\n"); 1523 LLVM_DEBUG(CMPI1->dump()); 1524 LLVM_DEBUG(BI1->dump()); 1525 LLVM_DEBUG(BI2->dump()); 1526 if (IsPartiallyRedundant) { 1527 LLVM_DEBUG(dbgs() << "The following compare is moved into " 1528 << printMBBReference(*MBBtoMoveCmp) 1529 << " to handle partial redundancy.\n"); 1530 LLVM_DEBUG(CMPI2->dump()); 1531 } 1532 1533 Simplified = true; 1534 } 1535 1536 return Simplified; 1537 } 1538 1539 // We miss the opportunity to emit an RLDIC when lowering jump tables 1540 // since ISEL sees only a single basic block. When selecting, the clear 1541 // and shift left will be in different blocks. 1542 bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI) { 1543 if (MI.getOpcode() != PPC::RLDICR) 1544 return false; 1545 1546 Register SrcReg = MI.getOperand(1).getReg(); 1547 if (!Register::isVirtualRegister(SrcReg)) 1548 return false; 1549 1550 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 1551 if (SrcMI->getOpcode() != PPC::RLDICL) 1552 return false; 1553 1554 MachineOperand MOpSHSrc = SrcMI->getOperand(2); 1555 MachineOperand MOpMBSrc = SrcMI->getOperand(3); 1556 MachineOperand MOpSHMI = MI.getOperand(2); 1557 MachineOperand MOpMEMI = MI.getOperand(3); 1558 if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() && 1559 MOpMEMI.isImm())) 1560 return false; 1561 1562 uint64_t SHSrc = MOpSHSrc.getImm(); 1563 uint64_t MBSrc = MOpMBSrc.getImm(); 1564 uint64_t SHMI = MOpSHMI.getImm(); 1565 uint64_t MEMI = MOpMEMI.getImm(); 1566 uint64_t NewSH = SHSrc + SHMI; 1567 uint64_t NewMB = MBSrc - SHMI; 1568 if (NewMB > 63 || NewSH > 63) 1569 return false; 1570 1571 // The bits cleared with RLDICL are [0, MBSrc). 1572 // The bits cleared with RLDICR are (MEMI, 63]. 1573 // After the sequence, the bits cleared are: 1574 // [0, MBSrc-SHMI) and (MEMI, 63). 1575 // 1576 // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63]. 1577 if ((63 - NewSH) != MEMI) 1578 return false; 1579 1580 LLVM_DEBUG(dbgs() << "Converting pair: "); 1581 LLVM_DEBUG(SrcMI->dump()); 1582 LLVM_DEBUG(MI.dump()); 1583 1584 MI.setDesc(TII->get(PPC::RLDIC)); 1585 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg()); 1586 MI.getOperand(2).setImm(NewSH); 1587 MI.getOperand(3).setImm(NewMB); 1588 1589 LLVM_DEBUG(dbgs() << "To: "); 1590 LLVM_DEBUG(MI.dump()); 1591 NumRotatesCollapsed++; 1592 return true; 1593 } 1594 1595 // For case in LLVM IR 1596 // entry: 1597 // %iconv = sext i32 %index to i64 1598 // br i1 undef label %true, label %false 1599 // true: 1600 // %ptr = getelementptr inbounds i32, i32* null, i64 %iconv 1601 // ... 1602 // PPCISelLowering::combineSHL fails to combine, because sext and shl are in 1603 // different BBs when conducting instruction selection. We can do a peephole 1604 // optimization to combine these two instructions into extswsli after 1605 // instruction selection. 1606 bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI, 1607 MachineInstr *&ToErase) { 1608 if (MI.getOpcode() != PPC::RLDICR) 1609 return false; 1610 1611 if (!MF->getSubtarget<PPCSubtarget>().isISA3_0()) 1612 return false; 1613 1614 assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands"); 1615 1616 MachineOperand MOpSHMI = MI.getOperand(2); 1617 MachineOperand MOpMEMI = MI.getOperand(3); 1618 if (!(MOpSHMI.isImm() && MOpMEMI.isImm())) 1619 return false; 1620 1621 uint64_t SHMI = MOpSHMI.getImm(); 1622 uint64_t MEMI = MOpMEMI.getImm(); 1623 if (SHMI + MEMI != 63) 1624 return false; 1625 1626 Register SrcReg = MI.getOperand(1).getReg(); 1627 if (!Register::isVirtualRegister(SrcReg)) 1628 return false; 1629 1630 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 1631 if (SrcMI->getOpcode() != PPC::EXTSW && 1632 SrcMI->getOpcode() != PPC::EXTSW_32_64) 1633 return false; 1634 1635 // If the register defined by extsw has more than one use, combination is not 1636 // needed. 1637 if (!MRI->hasOneNonDBGUse(SrcReg)) 1638 return false; 1639 1640 assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands"); 1641 assert(SrcMI->getOperand(1).isReg() && 1642 "EXTSW's second operand should be a register"); 1643 if (!Register::isVirtualRegister(SrcMI->getOperand(1).getReg())) 1644 return false; 1645 1646 LLVM_DEBUG(dbgs() << "Combining pair: "); 1647 LLVM_DEBUG(SrcMI->dump()); 1648 LLVM_DEBUG(MI.dump()); 1649 1650 MachineInstr *NewInstr = 1651 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), 1652 SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI) 1653 : TII->get(PPC::EXTSWSLI_32_64), 1654 MI.getOperand(0).getReg()) 1655 .add(SrcMI->getOperand(1)) 1656 .add(MOpSHMI); 1657 (void)NewInstr; 1658 1659 LLVM_DEBUG(dbgs() << "TO: "); 1660 LLVM_DEBUG(NewInstr->dump()); 1661 ++NumEXTSWAndSLDICombined; 1662 ToErase = &MI; 1663 // SrcMI, which is extsw, is of no use now, erase it. 1664 SrcMI->eraseFromParent(); 1665 return true; 1666 } 1667 1668 } // end default namespace 1669 1670 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE, 1671 "PowerPC MI Peephole Optimization", false, false) 1672 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfo) 1673 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 1674 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree) 1675 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE, 1676 "PowerPC MI Peephole Optimization", false, false) 1677 1678 char PPCMIPeephole::ID = 0; 1679 FunctionPass* 1680 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); } 1681 1682