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