1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===// 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 file contains the PowerPC implementation of the TargetInstrInfo class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCInstrInfo.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCHazardRecognizers.h" 17 #include "PPCInstrBuilder.h" 18 #include "PPCMachineFunctionInfo.h" 19 #include "PPCTargetMachine.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/CodeGen/LiveIntervals.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunctionPass.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineMemOperand.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/PseudoSourceValue.h" 30 #include "llvm/CodeGen/ScheduleDAG.h" 31 #include "llvm/CodeGen/SlotIndexes.h" 32 #include "llvm/CodeGen/StackMaps.h" 33 #include "llvm/MC/MCAsmInfo.h" 34 #include "llvm/MC/MCInst.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/TargetRegistry.h" 39 #include "llvm/Support/raw_ostream.h" 40 41 using namespace llvm; 42 43 #define DEBUG_TYPE "ppc-instr-info" 44 45 #define GET_INSTRMAP_INFO 46 #define GET_INSTRINFO_CTOR_DTOR 47 #include "PPCGenInstrInfo.inc" 48 49 STATISTIC(NumStoreSPILLVSRRCAsVec, 50 "Number of spillvsrrc spilled to stack as vec"); 51 STATISTIC(NumStoreSPILLVSRRCAsGpr, 52 "Number of spillvsrrc spilled to stack as gpr"); 53 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc"); 54 STATISTIC(CmpIselsConverted, 55 "Number of ISELs that depend on comparison of constants converted"); 56 STATISTIC(MissedConvertibleImmediateInstrs, 57 "Number of compare-immediate instructions fed by constants"); 58 STATISTIC(NumRcRotatesConvertedToRcAnd, 59 "Number of record-form rotates converted to record-form andi"); 60 61 static cl:: 62 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden, 63 cl::desc("Disable analysis for CTR loops")); 64 65 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt", 66 cl::desc("Disable compare instruction optimization"), cl::Hidden); 67 68 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy", 69 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"), 70 cl::Hidden); 71 72 static cl::opt<bool> 73 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden, 74 cl::desc("Use the old (incorrect) instruction latency calculation")); 75 76 // Pin the vtable to this file. 77 void PPCInstrInfo::anchor() {} 78 79 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI) 80 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP, 81 /* CatchRetOpcode */ -1, 82 STI.isPPC64() ? PPC::BLR8 : PPC::BLR), 83 Subtarget(STI), RI(STI.getTargetMachine()) {} 84 85 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for 86 /// this target when scheduling the DAG. 87 ScheduleHazardRecognizer * 88 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, 89 const ScheduleDAG *DAG) const { 90 unsigned Directive = 91 static_cast<const PPCSubtarget *>(STI)->getCPUDirective(); 92 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 || 93 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) { 94 const InstrItineraryData *II = 95 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData(); 96 return new ScoreboardHazardRecognizer(II, DAG); 97 } 98 99 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG); 100 } 101 102 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer 103 /// to use for this target when scheduling the DAG. 104 ScheduleHazardRecognizer * 105 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 106 const ScheduleDAG *DAG) const { 107 unsigned Directive = 108 DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective(); 109 110 // FIXME: Leaving this as-is until we have POWER9 scheduling info 111 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8) 112 return new PPCDispatchGroupSBHazardRecognizer(II, DAG); 113 114 // Most subtargets use a PPC970 recognizer. 115 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 && 116 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) { 117 assert(DAG->TII && "No InstrInfo?"); 118 119 return new PPCHazardRecognizer970(*DAG); 120 } 121 122 return new ScoreboardHazardRecognizer(II, DAG); 123 } 124 125 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 126 const MachineInstr &MI, 127 unsigned *PredCost) const { 128 if (!ItinData || UseOldLatencyCalc) 129 return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost); 130 131 // The default implementation of getInstrLatency calls getStageLatency, but 132 // getStageLatency does not do the right thing for us. While we have 133 // itinerary, most cores are fully pipelined, and so the itineraries only 134 // express the first part of the pipeline, not every stage. Instead, we need 135 // to use the listed output operand cycle number (using operand 0 here, which 136 // is an output). 137 138 unsigned Latency = 1; 139 unsigned DefClass = MI.getDesc().getSchedClass(); 140 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 141 const MachineOperand &MO = MI.getOperand(i); 142 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 143 continue; 144 145 int Cycle = ItinData->getOperandCycle(DefClass, i); 146 if (Cycle < 0) 147 continue; 148 149 Latency = std::max(Latency, (unsigned) Cycle); 150 } 151 152 return Latency; 153 } 154 155 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 156 const MachineInstr &DefMI, unsigned DefIdx, 157 const MachineInstr &UseMI, 158 unsigned UseIdx) const { 159 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx, 160 UseMI, UseIdx); 161 162 if (!DefMI.getParent()) 163 return Latency; 164 165 const MachineOperand &DefMO = DefMI.getOperand(DefIdx); 166 Register Reg = DefMO.getReg(); 167 168 bool IsRegCR; 169 if (Register::isVirtualRegister(Reg)) { 170 const MachineRegisterInfo *MRI = 171 &DefMI.getParent()->getParent()->getRegInfo(); 172 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) || 173 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass); 174 } else { 175 IsRegCR = PPC::CRRCRegClass.contains(Reg) || 176 PPC::CRBITRCRegClass.contains(Reg); 177 } 178 179 if (UseMI.isBranch() && IsRegCR) { 180 if (Latency < 0) 181 Latency = getInstrLatency(ItinData, DefMI); 182 183 // On some cores, there is an additional delay between writing to a condition 184 // register, and using it from a branch. 185 unsigned Directive = Subtarget.getCPUDirective(); 186 switch (Directive) { 187 default: break; 188 case PPC::DIR_7400: 189 case PPC::DIR_750: 190 case PPC::DIR_970: 191 case PPC::DIR_E5500: 192 case PPC::DIR_PWR4: 193 case PPC::DIR_PWR5: 194 case PPC::DIR_PWR5X: 195 case PPC::DIR_PWR6: 196 case PPC::DIR_PWR6X: 197 case PPC::DIR_PWR7: 198 case PPC::DIR_PWR8: 199 // FIXME: Is this needed for POWER9? 200 Latency += 2; 201 break; 202 } 203 } 204 205 return Latency; 206 } 207 208 /// This is an architecture-specific helper function of reassociateOps. 209 /// Set special operand attributes for new instructions after reassociation. 210 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1, 211 MachineInstr &OldMI2, 212 MachineInstr &NewMI1, 213 MachineInstr &NewMI2) const { 214 // Propagate FP flags from the original instructions. 215 // But clear poison-generating flags because those may not be valid now. 216 uint16_t IntersectedFlags = OldMI1.getFlags() & OldMI2.getFlags(); 217 NewMI1.setFlags(IntersectedFlags); 218 NewMI1.clearFlag(MachineInstr::MIFlag::NoSWrap); 219 NewMI1.clearFlag(MachineInstr::MIFlag::NoUWrap); 220 NewMI1.clearFlag(MachineInstr::MIFlag::IsExact); 221 222 NewMI2.setFlags(IntersectedFlags); 223 NewMI2.clearFlag(MachineInstr::MIFlag::NoSWrap); 224 NewMI2.clearFlag(MachineInstr::MIFlag::NoUWrap); 225 NewMI2.clearFlag(MachineInstr::MIFlag::IsExact); 226 } 227 228 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &MI, 229 uint16_t Flags) const { 230 MI.setFlags(Flags); 231 MI.clearFlag(MachineInstr::MIFlag::NoSWrap); 232 MI.clearFlag(MachineInstr::MIFlag::NoUWrap); 233 MI.clearFlag(MachineInstr::MIFlag::IsExact); 234 } 235 236 // This function does not list all associative and commutative operations, but 237 // only those worth feeding through the machine combiner in an attempt to 238 // reduce the critical path. Mostly, this means floating-point operations, 239 // because they have high latencies(>=5) (compared to other operations, such as 240 // and/or, which are also associative and commutative, but have low latencies). 241 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const { 242 switch (Inst.getOpcode()) { 243 // Floating point: 244 // FP Add: 245 case PPC::FADD: 246 case PPC::FADDS: 247 // FP Multiply: 248 case PPC::FMUL: 249 case PPC::FMULS: 250 // Altivec Add: 251 case PPC::VADDFP: 252 // VSX Add: 253 case PPC::XSADDDP: 254 case PPC::XVADDDP: 255 case PPC::XVADDSP: 256 case PPC::XSADDSP: 257 // VSX Multiply: 258 case PPC::XSMULDP: 259 case PPC::XVMULDP: 260 case PPC::XVMULSP: 261 case PPC::XSMULSP: 262 // QPX Add: 263 case PPC::QVFADD: 264 case PPC::QVFADDS: 265 case PPC::QVFADDSs: 266 // QPX Multiply: 267 case PPC::QVFMUL: 268 case PPC::QVFMULS: 269 case PPC::QVFMULSs: 270 return Inst.getFlag(MachineInstr::MIFlag::FmReassoc) && 271 Inst.getFlag(MachineInstr::MIFlag::FmNsz); 272 // Fixed point: 273 // Multiply: 274 case PPC::MULHD: 275 case PPC::MULLD: 276 case PPC::MULHW: 277 case PPC::MULLW: 278 return true; 279 default: 280 return false; 281 } 282 } 283 284 #define InfoArrayIdxFMAInst 0 285 #define InfoArrayIdxFAddInst 1 286 #define InfoArrayIdxFMULInst 2 287 #define InfoArrayIdxAddOpIdx 3 288 #define InfoArrayIdxMULOpIdx 4 289 // Array keeps info for FMA instructions: 290 // Index 0(InfoArrayIdxFMAInst): FMA instruction; 291 // Index 1(InfoArrayIdxFAddInst): ADD instruction assoaicted with FMA; 292 // Index 2(InfoArrayIdxFMULInst): MUL instruction assoaicted with FMA; 293 // Index 3(InfoArrayIdxAddOpIdx): ADD operand index in FMA operands; 294 // Index 4(InfoArrayIdxMULOpIdx): first MUL operand index in FMA operands; 295 // second MUL operand index is plus 1. 296 static const uint16_t FMAOpIdxInfo[][5] = { 297 // FIXME: Add more FMA instructions like XSNMADDADP and so on. 298 {PPC::XSMADDADP, PPC::XSADDDP, PPC::XSMULDP, 1, 2}, 299 {PPC::XSMADDASP, PPC::XSADDSP, PPC::XSMULSP, 1, 2}, 300 {PPC::XVMADDADP, PPC::XVADDDP, PPC::XVMULDP, 1, 2}, 301 {PPC::XVMADDASP, PPC::XVADDSP, PPC::XVMULSP, 1, 2}, 302 {PPC::FMADD, PPC::FADD, PPC::FMUL, 3, 1}, 303 {PPC::FMADDS, PPC::FADDS, PPC::FMULS, 3, 1}, 304 {PPC::QVFMADDSs, PPC::QVFADDSs, PPC::QVFMULSs, 3, 1}, 305 {PPC::QVFMADD, PPC::QVFADD, PPC::QVFMUL, 3, 1}}; 306 307 // Check if an opcode is a FMA instruction. If it is, return the index in array 308 // FMAOpIdxInfo. Otherwise, return -1. 309 int16_t PPCInstrInfo::getFMAOpIdxInfo(unsigned Opcode) const { 310 for (unsigned I = 0; I < array_lengthof(FMAOpIdxInfo); I++) 311 if (FMAOpIdxInfo[I][InfoArrayIdxFMAInst] == Opcode) 312 return I; 313 return -1; 314 } 315 316 // Try to reassociate FMA chains like below: 317 // 318 // Pattern 1: 319 // A = FADD X, Y (Leaf) 320 // B = FMA A, M21, M22 (Prev) 321 // C = FMA B, M31, M32 (Root) 322 // --> 323 // A = FMA X, M21, M22 324 // B = FMA Y, M31, M32 325 // C = FADD A, B 326 // 327 // Pattern 2: 328 // A = FMA X, M11, M12 (Leaf) 329 // B = FMA A, M21, M22 (Prev) 330 // C = FMA B, M31, M32 (Root) 331 // --> 332 // A = FMUL M11, M12 333 // B = FMA X, M21, M22 334 // D = FMA A, M31, M32 335 // C = FADD B, D 336 // 337 // breaking the dependency between A and B, allowing FMA to be executed in 338 // parallel (or back-to-back in a pipeline) instead of depending on each other. 339 bool PPCInstrInfo::getFMAPatterns( 340 MachineInstr &Root, 341 SmallVectorImpl<MachineCombinerPattern> &Patterns) const { 342 MachineBasicBlock *MBB = Root.getParent(); 343 const MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); 344 345 auto IsAllOpsVirtualReg = [](const MachineInstr &Instr) { 346 for (const auto &MO : Instr.explicit_operands()) 347 if (!(MO.isReg() && Register::isVirtualRegister(MO.getReg()))) 348 return false; 349 return true; 350 }; 351 352 auto IsReassociable = [&](const MachineInstr &Instr, int16_t &AddOpIdx, 353 bool IsLeaf, bool IsAdd) { 354 int16_t Idx = -1; 355 if (!IsAdd) { 356 Idx = getFMAOpIdxInfo(Instr.getOpcode()); 357 if (Idx < 0) 358 return false; 359 } else if (Instr.getOpcode() != 360 FMAOpIdxInfo[getFMAOpIdxInfo(Root.getOpcode())] 361 [InfoArrayIdxFAddInst]) 362 return false; 363 364 // Instruction can be reassociated. 365 // fast math flags may prohibit reassociation. 366 if (!(Instr.getFlag(MachineInstr::MIFlag::FmReassoc) && 367 Instr.getFlag(MachineInstr::MIFlag::FmNsz))) 368 return false; 369 370 // Instruction operands are virtual registers for reassociation. 371 if (!IsAllOpsVirtualReg(Instr)) 372 return false; 373 374 if (IsAdd && IsLeaf) 375 return true; 376 377 AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx]; 378 379 const MachineOperand &OpAdd = Instr.getOperand(AddOpIdx); 380 MachineInstr *MIAdd = MRI.getUniqueVRegDef(OpAdd.getReg()); 381 // If 'add' operand's def is not in current block, don't do ILP related opt. 382 if (!MIAdd || MIAdd->getParent() != MBB) 383 return false; 384 385 // If this is not Leaf FMA Instr, its 'add' operand should only have one use 386 // as this fma will be changed later. 387 return IsLeaf ? true : MRI.hasOneNonDBGUse(OpAdd.getReg()); 388 }; 389 390 int16_t AddOpIdx = -1; 391 // Root must be a valid FMA like instruction. 392 if (!IsReassociable(Root, AddOpIdx, false, false)) 393 return false; 394 395 assert((AddOpIdx >= 0) && "add operand index not right!"); 396 397 Register RegB = Root.getOperand(AddOpIdx).getReg(); 398 MachineInstr *Prev = MRI.getUniqueVRegDef(RegB); 399 400 // Prev must be a valid FMA like instruction. 401 AddOpIdx = -1; 402 if (!IsReassociable(*Prev, AddOpIdx, false, false)) 403 return false; 404 405 assert((AddOpIdx >= 0) && "add operand index not right!"); 406 407 Register RegA = Prev->getOperand(AddOpIdx).getReg(); 408 MachineInstr *Leaf = MRI.getUniqueVRegDef(RegA); 409 AddOpIdx = -1; 410 if (IsReassociable(*Leaf, AddOpIdx, true, false)) { 411 Patterns.push_back(MachineCombinerPattern::REASSOC_XMM_AMM_BMM); 412 return true; 413 } 414 if (IsReassociable(*Leaf, AddOpIdx, true, true)) { 415 Patterns.push_back(MachineCombinerPattern::REASSOC_XY_AMM_BMM); 416 return true; 417 } 418 return false; 419 } 420 421 bool PPCInstrInfo::getMachineCombinerPatterns( 422 MachineInstr &Root, 423 SmallVectorImpl<MachineCombinerPattern> &Patterns) const { 424 // Using the machine combiner in this way is potentially expensive, so 425 // restrict to when aggressive optimizations are desired. 426 if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive) 427 return false; 428 429 if (getFMAPatterns(Root, Patterns)) 430 return true; 431 432 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns); 433 } 434 435 void PPCInstrInfo::genAlternativeCodeSequence( 436 MachineInstr &Root, MachineCombinerPattern Pattern, 437 SmallVectorImpl<MachineInstr *> &InsInstrs, 438 SmallVectorImpl<MachineInstr *> &DelInstrs, 439 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const { 440 switch (Pattern) { 441 case MachineCombinerPattern::REASSOC_XY_AMM_BMM: 442 case MachineCombinerPattern::REASSOC_XMM_AMM_BMM: 443 reassociateFMA(Root, Pattern, InsInstrs, DelInstrs, InstrIdxForVirtReg); 444 break; 445 default: 446 // Reassociate default patterns. 447 TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs, 448 DelInstrs, InstrIdxForVirtReg); 449 break; 450 } 451 } 452 453 // Currently, only handle two patterns REASSOC_XY_AMM_BMM and 454 // REASSOC_XMM_AMM_BMM. See comments for getFMAPatterns. 455 void PPCInstrInfo::reassociateFMA( 456 MachineInstr &Root, MachineCombinerPattern Pattern, 457 SmallVectorImpl<MachineInstr *> &InsInstrs, 458 SmallVectorImpl<MachineInstr *> &DelInstrs, 459 DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const { 460 MachineFunction *MF = Root.getMF(); 461 MachineRegisterInfo &MRI = MF->getRegInfo(); 462 MachineOperand &OpC = Root.getOperand(0); 463 Register RegC = OpC.getReg(); 464 const TargetRegisterClass *RC = MRI.getRegClass(RegC); 465 MRI.constrainRegClass(RegC, RC); 466 467 unsigned FmaOp = Root.getOpcode(); 468 int16_t Idx = getFMAOpIdxInfo(FmaOp); 469 assert(Idx >= 0 && "Root must be a FMA instruction"); 470 471 uint16_t AddOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxAddOpIdx]; 472 uint16_t FirstMulOpIdx = FMAOpIdxInfo[Idx][InfoArrayIdxMULOpIdx]; 473 MachineInstr *Prev = MRI.getUniqueVRegDef(Root.getOperand(AddOpIdx).getReg()); 474 MachineInstr *Leaf = 475 MRI.getUniqueVRegDef(Prev->getOperand(AddOpIdx).getReg()); 476 uint16_t IntersectedFlags = 477 Root.getFlags() & Prev->getFlags() & Leaf->getFlags(); 478 479 auto GetOperandInfo = [&](const MachineOperand &Operand, Register &Reg, 480 bool &KillFlag) { 481 Reg = Operand.getReg(); 482 MRI.constrainRegClass(Reg, RC); 483 KillFlag = Operand.isKill(); 484 }; 485 486 auto GetFMAInstrInfo = [&](const MachineInstr &Instr, Register &MulOp1, 487 Register &MulOp2, bool &MulOp1KillFlag, 488 bool &MulOp2KillFlag) { 489 GetOperandInfo(Instr.getOperand(FirstMulOpIdx), MulOp1, MulOp1KillFlag); 490 GetOperandInfo(Instr.getOperand(FirstMulOpIdx + 1), MulOp2, MulOp2KillFlag); 491 }; 492 493 Register RegM11, RegM12, RegX, RegY, RegM21, RegM22, RegM31, RegM32; 494 bool KillX = false, KillY = false, KillM11 = false, KillM12 = false, 495 KillM21 = false, KillM22 = false, KillM31 = false, KillM32 = false; 496 497 GetFMAInstrInfo(Root, RegM31, RegM32, KillM31, KillM32); 498 GetFMAInstrInfo(*Prev, RegM21, RegM22, KillM21, KillM22); 499 500 if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) { 501 GetFMAInstrInfo(*Leaf, RegM11, RegM12, KillM11, KillM12); 502 GetOperandInfo(Leaf->getOperand(AddOpIdx), RegX, KillX); 503 } else if (Pattern == MachineCombinerPattern::REASSOC_XY_AMM_BMM) { 504 GetOperandInfo(Leaf->getOperand(1), RegX, KillX); 505 GetOperandInfo(Leaf->getOperand(2), RegY, KillY); 506 } 507 508 // Create new virtual registers for the new results instead of 509 // recycling legacy ones because the MachineCombiner's computation of the 510 // critical path requires a new register definition rather than an existing 511 // one. 512 Register NewVRA = MRI.createVirtualRegister(RC); 513 InstrIdxForVirtReg.insert(std::make_pair(NewVRA, 0)); 514 515 Register NewVRB = MRI.createVirtualRegister(RC); 516 InstrIdxForVirtReg.insert(std::make_pair(NewVRB, 1)); 517 518 Register NewVRD = 0; 519 if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) { 520 NewVRD = MRI.createVirtualRegister(RC); 521 InstrIdxForVirtReg.insert(std::make_pair(NewVRD, 2)); 522 } 523 524 auto AdjustOperandOrder = [&](MachineInstr *MI, Register RegAdd, bool KillAdd, 525 Register RegMul1, bool KillRegMul1, 526 Register RegMul2, bool KillRegMul2) { 527 MI->getOperand(AddOpIdx).setReg(RegAdd); 528 MI->getOperand(AddOpIdx).setIsKill(KillAdd); 529 MI->getOperand(FirstMulOpIdx).setReg(RegMul1); 530 MI->getOperand(FirstMulOpIdx).setIsKill(KillRegMul1); 531 MI->getOperand(FirstMulOpIdx + 1).setReg(RegMul2); 532 MI->getOperand(FirstMulOpIdx + 1).setIsKill(KillRegMul2); 533 }; 534 535 if (Pattern == MachineCombinerPattern::REASSOC_XY_AMM_BMM) { 536 // Create new instructions for insertion. 537 MachineInstrBuilder MINewB = 538 BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB) 539 .addReg(RegX, getKillRegState(KillX)) 540 .addReg(RegM21, getKillRegState(KillM21)) 541 .addReg(RegM22, getKillRegState(KillM22)); 542 MachineInstrBuilder MINewA = 543 BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRA) 544 .addReg(RegY, getKillRegState(KillY)) 545 .addReg(RegM31, getKillRegState(KillM31)) 546 .addReg(RegM32, getKillRegState(KillM32)); 547 // If AddOpIdx is not 1, adjust the order. 548 if (AddOpIdx != 1) { 549 AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22); 550 AdjustOperandOrder(MINewA, RegY, KillY, RegM31, KillM31, RegM32, KillM32); 551 } 552 553 MachineInstrBuilder MINewC = 554 BuildMI(*MF, Root.getDebugLoc(), 555 get(FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), RegC) 556 .addReg(NewVRB, getKillRegState(true)) 557 .addReg(NewVRA, getKillRegState(true)); 558 559 // Update flags for newly created instructions. 560 setSpecialOperandAttr(*MINewA, IntersectedFlags); 561 setSpecialOperandAttr(*MINewB, IntersectedFlags); 562 setSpecialOperandAttr(*MINewC, IntersectedFlags); 563 564 // Record new instructions for insertion. 565 InsInstrs.push_back(MINewA); 566 InsInstrs.push_back(MINewB); 567 InsInstrs.push_back(MINewC); 568 } else if (Pattern == MachineCombinerPattern::REASSOC_XMM_AMM_BMM) { 569 assert(NewVRD && "new FMA register not created!"); 570 // Create new instructions for insertion. 571 MachineInstrBuilder MINewA = 572 BuildMI(*MF, Leaf->getDebugLoc(), 573 get(FMAOpIdxInfo[Idx][InfoArrayIdxFMULInst]), NewVRA) 574 .addReg(RegM11, getKillRegState(KillM11)) 575 .addReg(RegM12, getKillRegState(KillM12)); 576 MachineInstrBuilder MINewB = 577 BuildMI(*MF, Prev->getDebugLoc(), get(FmaOp), NewVRB) 578 .addReg(RegX, getKillRegState(KillX)) 579 .addReg(RegM21, getKillRegState(KillM21)) 580 .addReg(RegM22, getKillRegState(KillM22)); 581 MachineInstrBuilder MINewD = 582 BuildMI(*MF, Root.getDebugLoc(), get(FmaOp), NewVRD) 583 .addReg(NewVRA, getKillRegState(true)) 584 .addReg(RegM31, getKillRegState(KillM31)) 585 .addReg(RegM32, getKillRegState(KillM32)); 586 // If AddOpIdx is not 1, adjust the order. 587 if (AddOpIdx != 1) { 588 AdjustOperandOrder(MINewB, RegX, KillX, RegM21, KillM21, RegM22, KillM22); 589 AdjustOperandOrder(MINewD, NewVRA, true, RegM31, KillM31, RegM32, 590 KillM32); 591 } 592 593 MachineInstrBuilder MINewC = 594 BuildMI(*MF, Root.getDebugLoc(), 595 get(FMAOpIdxInfo[Idx][InfoArrayIdxFAddInst]), RegC) 596 .addReg(NewVRB, getKillRegState(true)) 597 .addReg(NewVRD, getKillRegState(true)); 598 599 // Update flags for newly created instructions. 600 setSpecialOperandAttr(*MINewA, IntersectedFlags); 601 setSpecialOperandAttr(*MINewB, IntersectedFlags); 602 setSpecialOperandAttr(*MINewD, IntersectedFlags); 603 setSpecialOperandAttr(*MINewC, IntersectedFlags); 604 605 // Record new instructions for insertion. 606 InsInstrs.push_back(MINewA); 607 InsInstrs.push_back(MINewB); 608 InsInstrs.push_back(MINewD); 609 InsInstrs.push_back(MINewC); 610 } 611 612 assert(!InsInstrs.empty() && 613 "Insertion instructions set should not be empty!"); 614 615 // Record old instructions for deletion. 616 DelInstrs.push_back(Leaf); 617 DelInstrs.push_back(Prev); 618 DelInstrs.push_back(&Root); 619 } 620 621 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register. 622 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI, 623 Register &SrcReg, Register &DstReg, 624 unsigned &SubIdx) const { 625 switch (MI.getOpcode()) { 626 default: return false; 627 case PPC::EXTSW: 628 case PPC::EXTSW_32: 629 case PPC::EXTSW_32_64: 630 SrcReg = MI.getOperand(1).getReg(); 631 DstReg = MI.getOperand(0).getReg(); 632 SubIdx = PPC::sub_32; 633 return true; 634 } 635 } 636 637 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI, 638 int &FrameIndex) const { 639 unsigned Opcode = MI.getOpcode(); 640 const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray(); 641 const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill; 642 643 if (End != std::find(OpcodesForSpill, End, Opcode)) { 644 // Check for the operands added by addFrameReference (the immediate is the 645 // offset which defaults to 0). 646 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() && 647 MI.getOperand(2).isFI()) { 648 FrameIndex = MI.getOperand(2).getIndex(); 649 return MI.getOperand(0).getReg(); 650 } 651 } 652 return 0; 653 } 654 655 // For opcodes with the ReMaterializable flag set, this function is called to 656 // verify the instruction is really rematable. 657 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI, 658 AliasAnalysis *AA) const { 659 switch (MI.getOpcode()) { 660 default: 661 // This function should only be called for opcodes with the ReMaterializable 662 // flag set. 663 llvm_unreachable("Unknown rematerializable operation!"); 664 break; 665 case PPC::LI: 666 case PPC::LI8: 667 case PPC::LIS: 668 case PPC::LIS8: 669 case PPC::QVGPCI: 670 case PPC::ADDIStocHA: 671 case PPC::ADDIStocHA8: 672 case PPC::ADDItocL: 673 case PPC::LOAD_STACK_GUARD: 674 case PPC::XXLXORz: 675 case PPC::XXLXORspz: 676 case PPC::XXLXORdpz: 677 case PPC::XXLEQVOnes: 678 case PPC::V_SET0B: 679 case PPC::V_SET0H: 680 case PPC::V_SET0: 681 case PPC::V_SETALLONESB: 682 case PPC::V_SETALLONESH: 683 case PPC::V_SETALLONES: 684 case PPC::CRSET: 685 case PPC::CRUNSET: 686 return true; 687 } 688 return false; 689 } 690 691 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI, 692 int &FrameIndex) const { 693 unsigned Opcode = MI.getOpcode(); 694 const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray(); 695 const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill; 696 697 if (End != std::find(OpcodesForSpill, End, Opcode)) { 698 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() && 699 MI.getOperand(2).isFI()) { 700 FrameIndex = MI.getOperand(2).getIndex(); 701 return MI.getOperand(0).getReg(); 702 } 703 } 704 return 0; 705 } 706 707 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI, 708 unsigned OpIdx1, 709 unsigned OpIdx2) const { 710 MachineFunction &MF = *MI.getParent()->getParent(); 711 712 // Normal instructions can be commuted the obvious way. 713 if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec) 714 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 715 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a 716 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because 717 // changing the relative order of the mask operands might change what happens 718 // to the high-bits of the mask (and, thus, the result). 719 720 // Cannot commute if it has a non-zero rotate count. 721 if (MI.getOperand(3).getImm() != 0) 722 return nullptr; 723 724 // If we have a zero rotate count, we have: 725 // M = mask(MB,ME) 726 // Op0 = (Op1 & ~M) | (Op2 & M) 727 // Change this to: 728 // M = mask((ME+1)&31, (MB-1)&31) 729 // Op0 = (Op2 & ~M) | (Op1 & M) 730 731 // Swap op1/op2 732 assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) && 733 "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec."); 734 Register Reg0 = MI.getOperand(0).getReg(); 735 Register Reg1 = MI.getOperand(1).getReg(); 736 Register Reg2 = MI.getOperand(2).getReg(); 737 unsigned SubReg1 = MI.getOperand(1).getSubReg(); 738 unsigned SubReg2 = MI.getOperand(2).getSubReg(); 739 bool Reg1IsKill = MI.getOperand(1).isKill(); 740 bool Reg2IsKill = MI.getOperand(2).isKill(); 741 bool ChangeReg0 = false; 742 // If machine instrs are no longer in two-address forms, update 743 // destination register as well. 744 if (Reg0 == Reg1) { 745 // Must be two address instruction! 746 assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) && 747 "Expecting a two-address instruction!"); 748 assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch"); 749 Reg2IsKill = false; 750 ChangeReg0 = true; 751 } 752 753 // Masks. 754 unsigned MB = MI.getOperand(4).getImm(); 755 unsigned ME = MI.getOperand(5).getImm(); 756 757 // We can't commute a trivial mask (there is no way to represent an all-zero 758 // mask). 759 if (MB == 0 && ME == 31) 760 return nullptr; 761 762 if (NewMI) { 763 // Create a new instruction. 764 Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg(); 765 bool Reg0IsDead = MI.getOperand(0).isDead(); 766 return BuildMI(MF, MI.getDebugLoc(), MI.getDesc()) 767 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead)) 768 .addReg(Reg2, getKillRegState(Reg2IsKill)) 769 .addReg(Reg1, getKillRegState(Reg1IsKill)) 770 .addImm((ME + 1) & 31) 771 .addImm((MB - 1) & 31); 772 } 773 774 if (ChangeReg0) { 775 MI.getOperand(0).setReg(Reg2); 776 MI.getOperand(0).setSubReg(SubReg2); 777 } 778 MI.getOperand(2).setReg(Reg1); 779 MI.getOperand(1).setReg(Reg2); 780 MI.getOperand(2).setSubReg(SubReg1); 781 MI.getOperand(1).setSubReg(SubReg2); 782 MI.getOperand(2).setIsKill(Reg1IsKill); 783 MI.getOperand(1).setIsKill(Reg2IsKill); 784 785 // Swap the mask around. 786 MI.getOperand(4).setImm((ME + 1) & 31); 787 MI.getOperand(5).setImm((MB - 1) & 31); 788 return &MI; 789 } 790 791 bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI, 792 unsigned &SrcOpIdx1, 793 unsigned &SrcOpIdx2) const { 794 // For VSX A-Type FMA instructions, it is the first two operands that can be 795 // commuted, however, because the non-encoded tied input operand is listed 796 // first, the operands to swap are actually the second and third. 797 798 int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode()); 799 if (AltOpc == -1) 800 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2); 801 802 // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1 803 // and SrcOpIdx2. 804 return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3); 805 } 806 807 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB, 808 MachineBasicBlock::iterator MI) const { 809 // This function is used for scheduling, and the nop wanted here is the type 810 // that terminates dispatch groups on the POWER cores. 811 unsigned Directive = Subtarget.getCPUDirective(); 812 unsigned Opcode; 813 switch (Directive) { 814 default: Opcode = PPC::NOP; break; 815 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break; 816 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break; 817 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */ 818 // FIXME: Update when POWER9 scheduling model is ready. 819 case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break; 820 } 821 822 DebugLoc DL; 823 BuildMI(MBB, MI, DL, get(Opcode)); 824 } 825 826 /// Return the noop instruction to use for a noop. 827 void PPCInstrInfo::getNoop(MCInst &NopInst) const { 828 NopInst.setOpcode(PPC::NOP); 829 } 830 831 // Branch analysis. 832 // Note: If the condition register is set to CTR or CTR8 then this is a 833 // BDNZ (imm == 1) or BDZ (imm == 0) branch. 834 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB, 835 MachineBasicBlock *&TBB, 836 MachineBasicBlock *&FBB, 837 SmallVectorImpl<MachineOperand> &Cond, 838 bool AllowModify) const { 839 bool isPPC64 = Subtarget.isPPC64(); 840 841 // If the block has no terminators, it just falls into the block after it. 842 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 843 if (I == MBB.end()) 844 return false; 845 846 if (!isUnpredicatedTerminator(*I)) 847 return false; 848 849 if (AllowModify) { 850 // If the BB ends with an unconditional branch to the fallthrough BB, 851 // we eliminate the branch instruction. 852 if (I->getOpcode() == PPC::B && 853 MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) { 854 I->eraseFromParent(); 855 856 // We update iterator after deleting the last branch. 857 I = MBB.getLastNonDebugInstr(); 858 if (I == MBB.end() || !isUnpredicatedTerminator(*I)) 859 return false; 860 } 861 } 862 863 // Get the last instruction in the block. 864 MachineInstr &LastInst = *I; 865 866 // If there is only one terminator instruction, process it. 867 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) { 868 if (LastInst.getOpcode() == PPC::B) { 869 if (!LastInst.getOperand(0).isMBB()) 870 return true; 871 TBB = LastInst.getOperand(0).getMBB(); 872 return false; 873 } else if (LastInst.getOpcode() == PPC::BCC) { 874 if (!LastInst.getOperand(2).isMBB()) 875 return true; 876 // Block ends with fall-through condbranch. 877 TBB = LastInst.getOperand(2).getMBB(); 878 Cond.push_back(LastInst.getOperand(0)); 879 Cond.push_back(LastInst.getOperand(1)); 880 return false; 881 } else if (LastInst.getOpcode() == PPC::BC) { 882 if (!LastInst.getOperand(1).isMBB()) 883 return true; 884 // Block ends with fall-through condbranch. 885 TBB = LastInst.getOperand(1).getMBB(); 886 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 887 Cond.push_back(LastInst.getOperand(0)); 888 return false; 889 } else if (LastInst.getOpcode() == PPC::BCn) { 890 if (!LastInst.getOperand(1).isMBB()) 891 return true; 892 // Block ends with fall-through condbranch. 893 TBB = LastInst.getOperand(1).getMBB(); 894 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET)); 895 Cond.push_back(LastInst.getOperand(0)); 896 return false; 897 } else if (LastInst.getOpcode() == PPC::BDNZ8 || 898 LastInst.getOpcode() == PPC::BDNZ) { 899 if (!LastInst.getOperand(0).isMBB()) 900 return true; 901 if (DisableCTRLoopAnal) 902 return true; 903 TBB = LastInst.getOperand(0).getMBB(); 904 Cond.push_back(MachineOperand::CreateImm(1)); 905 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 906 true)); 907 return false; 908 } else if (LastInst.getOpcode() == PPC::BDZ8 || 909 LastInst.getOpcode() == PPC::BDZ) { 910 if (!LastInst.getOperand(0).isMBB()) 911 return true; 912 if (DisableCTRLoopAnal) 913 return true; 914 TBB = LastInst.getOperand(0).getMBB(); 915 Cond.push_back(MachineOperand::CreateImm(0)); 916 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 917 true)); 918 return false; 919 } 920 921 // Otherwise, don't know what this is. 922 return true; 923 } 924 925 // Get the instruction before it if it's a terminator. 926 MachineInstr &SecondLastInst = *I; 927 928 // If there are three terminators, we don't know what sort of block this is. 929 if (I != MBB.begin() && isUnpredicatedTerminator(*--I)) 930 return true; 931 932 // If the block ends with PPC::B and PPC:BCC, handle it. 933 if (SecondLastInst.getOpcode() == PPC::BCC && 934 LastInst.getOpcode() == PPC::B) { 935 if (!SecondLastInst.getOperand(2).isMBB() || 936 !LastInst.getOperand(0).isMBB()) 937 return true; 938 TBB = SecondLastInst.getOperand(2).getMBB(); 939 Cond.push_back(SecondLastInst.getOperand(0)); 940 Cond.push_back(SecondLastInst.getOperand(1)); 941 FBB = LastInst.getOperand(0).getMBB(); 942 return false; 943 } else if (SecondLastInst.getOpcode() == PPC::BC && 944 LastInst.getOpcode() == PPC::B) { 945 if (!SecondLastInst.getOperand(1).isMBB() || 946 !LastInst.getOperand(0).isMBB()) 947 return true; 948 TBB = SecondLastInst.getOperand(1).getMBB(); 949 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 950 Cond.push_back(SecondLastInst.getOperand(0)); 951 FBB = LastInst.getOperand(0).getMBB(); 952 return false; 953 } else if (SecondLastInst.getOpcode() == PPC::BCn && 954 LastInst.getOpcode() == PPC::B) { 955 if (!SecondLastInst.getOperand(1).isMBB() || 956 !LastInst.getOperand(0).isMBB()) 957 return true; 958 TBB = SecondLastInst.getOperand(1).getMBB(); 959 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET)); 960 Cond.push_back(SecondLastInst.getOperand(0)); 961 FBB = LastInst.getOperand(0).getMBB(); 962 return false; 963 } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 || 964 SecondLastInst.getOpcode() == PPC::BDNZ) && 965 LastInst.getOpcode() == PPC::B) { 966 if (!SecondLastInst.getOperand(0).isMBB() || 967 !LastInst.getOperand(0).isMBB()) 968 return true; 969 if (DisableCTRLoopAnal) 970 return true; 971 TBB = SecondLastInst.getOperand(0).getMBB(); 972 Cond.push_back(MachineOperand::CreateImm(1)); 973 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 974 true)); 975 FBB = LastInst.getOperand(0).getMBB(); 976 return false; 977 } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 || 978 SecondLastInst.getOpcode() == PPC::BDZ) && 979 LastInst.getOpcode() == PPC::B) { 980 if (!SecondLastInst.getOperand(0).isMBB() || 981 !LastInst.getOperand(0).isMBB()) 982 return true; 983 if (DisableCTRLoopAnal) 984 return true; 985 TBB = SecondLastInst.getOperand(0).getMBB(); 986 Cond.push_back(MachineOperand::CreateImm(0)); 987 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 988 true)); 989 FBB = LastInst.getOperand(0).getMBB(); 990 return false; 991 } 992 993 // If the block ends with two PPC:Bs, handle it. The second one is not 994 // executed, so remove it. 995 if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) { 996 if (!SecondLastInst.getOperand(0).isMBB()) 997 return true; 998 TBB = SecondLastInst.getOperand(0).getMBB(); 999 I = LastInst; 1000 if (AllowModify) 1001 I->eraseFromParent(); 1002 return false; 1003 } 1004 1005 // Otherwise, can't handle this. 1006 return true; 1007 } 1008 1009 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB, 1010 int *BytesRemoved) const { 1011 assert(!BytesRemoved && "code size not handled"); 1012 1013 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 1014 if (I == MBB.end()) 1015 return 0; 1016 1017 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC && 1018 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn && 1019 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ && 1020 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ) 1021 return 0; 1022 1023 // Remove the branch. 1024 I->eraseFromParent(); 1025 1026 I = MBB.end(); 1027 1028 if (I == MBB.begin()) return 1; 1029 --I; 1030 if (I->getOpcode() != PPC::BCC && 1031 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn && 1032 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ && 1033 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ) 1034 return 1; 1035 1036 // Remove the branch. 1037 I->eraseFromParent(); 1038 return 2; 1039 } 1040 1041 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB, 1042 MachineBasicBlock *TBB, 1043 MachineBasicBlock *FBB, 1044 ArrayRef<MachineOperand> Cond, 1045 const DebugLoc &DL, 1046 int *BytesAdded) const { 1047 // Shouldn't be a fall through. 1048 assert(TBB && "insertBranch must not be told to insert a fallthrough"); 1049 assert((Cond.size() == 2 || Cond.size() == 0) && 1050 "PPC branch conditions have two components!"); 1051 assert(!BytesAdded && "code size not handled"); 1052 1053 bool isPPC64 = Subtarget.isPPC64(); 1054 1055 // One-way branch. 1056 if (!FBB) { 1057 if (Cond.empty()) // Unconditional branch 1058 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB); 1059 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8) 1060 BuildMI(&MBB, DL, get(Cond[0].getImm() ? 1061 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) : 1062 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB); 1063 else if (Cond[0].getImm() == PPC::PRED_BIT_SET) 1064 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB); 1065 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET) 1066 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB); 1067 else // Conditional branch 1068 BuildMI(&MBB, DL, get(PPC::BCC)) 1069 .addImm(Cond[0].getImm()) 1070 .add(Cond[1]) 1071 .addMBB(TBB); 1072 return 1; 1073 } 1074 1075 // Two-way Conditional Branch. 1076 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8) 1077 BuildMI(&MBB, DL, get(Cond[0].getImm() ? 1078 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) : 1079 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB); 1080 else if (Cond[0].getImm() == PPC::PRED_BIT_SET) 1081 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB); 1082 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET) 1083 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB); 1084 else 1085 BuildMI(&MBB, DL, get(PPC::BCC)) 1086 .addImm(Cond[0].getImm()) 1087 .add(Cond[1]) 1088 .addMBB(TBB); 1089 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB); 1090 return 2; 1091 } 1092 1093 // Select analysis. 1094 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB, 1095 ArrayRef<MachineOperand> Cond, 1096 Register DstReg, Register TrueReg, 1097 Register FalseReg, int &CondCycles, 1098 int &TrueCycles, int &FalseCycles) const { 1099 if (Cond.size() != 2) 1100 return false; 1101 1102 // If this is really a bdnz-like condition, then it cannot be turned into a 1103 // select. 1104 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8) 1105 return false; 1106 1107 // Check register classes. 1108 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 1109 const TargetRegisterClass *RC = 1110 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg)); 1111 if (!RC) 1112 return false; 1113 1114 // isel is for regular integer GPRs only. 1115 if (!PPC::GPRCRegClass.hasSubClassEq(RC) && 1116 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) && 1117 !PPC::G8RCRegClass.hasSubClassEq(RC) && 1118 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) 1119 return false; 1120 1121 // FIXME: These numbers are for the A2, how well they work for other cores is 1122 // an open question. On the A2, the isel instruction has a 2-cycle latency 1123 // but single-cycle throughput. These numbers are used in combination with 1124 // the MispredictPenalty setting from the active SchedMachineModel. 1125 CondCycles = 1; 1126 TrueCycles = 1; 1127 FalseCycles = 1; 1128 1129 return true; 1130 } 1131 1132 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB, 1133 MachineBasicBlock::iterator MI, 1134 const DebugLoc &dl, Register DestReg, 1135 ArrayRef<MachineOperand> Cond, Register TrueReg, 1136 Register FalseReg) const { 1137 assert(Cond.size() == 2 && 1138 "PPC branch conditions have two components!"); 1139 1140 // Get the register classes. 1141 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 1142 const TargetRegisterClass *RC = 1143 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg)); 1144 assert(RC && "TrueReg and FalseReg must have overlapping register classes"); 1145 1146 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) || 1147 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC); 1148 assert((Is64Bit || 1149 PPC::GPRCRegClass.hasSubClassEq(RC) || 1150 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) && 1151 "isel is for regular integer GPRs only"); 1152 1153 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL; 1154 auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm()); 1155 1156 unsigned SubIdx = 0; 1157 bool SwapOps = false; 1158 switch (SelectPred) { 1159 case PPC::PRED_EQ: 1160 case PPC::PRED_EQ_MINUS: 1161 case PPC::PRED_EQ_PLUS: 1162 SubIdx = PPC::sub_eq; SwapOps = false; break; 1163 case PPC::PRED_NE: 1164 case PPC::PRED_NE_MINUS: 1165 case PPC::PRED_NE_PLUS: 1166 SubIdx = PPC::sub_eq; SwapOps = true; break; 1167 case PPC::PRED_LT: 1168 case PPC::PRED_LT_MINUS: 1169 case PPC::PRED_LT_PLUS: 1170 SubIdx = PPC::sub_lt; SwapOps = false; break; 1171 case PPC::PRED_GE: 1172 case PPC::PRED_GE_MINUS: 1173 case PPC::PRED_GE_PLUS: 1174 SubIdx = PPC::sub_lt; SwapOps = true; break; 1175 case PPC::PRED_GT: 1176 case PPC::PRED_GT_MINUS: 1177 case PPC::PRED_GT_PLUS: 1178 SubIdx = PPC::sub_gt; SwapOps = false; break; 1179 case PPC::PRED_LE: 1180 case PPC::PRED_LE_MINUS: 1181 case PPC::PRED_LE_PLUS: 1182 SubIdx = PPC::sub_gt; SwapOps = true; break; 1183 case PPC::PRED_UN: 1184 case PPC::PRED_UN_MINUS: 1185 case PPC::PRED_UN_PLUS: 1186 SubIdx = PPC::sub_un; SwapOps = false; break; 1187 case PPC::PRED_NU: 1188 case PPC::PRED_NU_MINUS: 1189 case PPC::PRED_NU_PLUS: 1190 SubIdx = PPC::sub_un; SwapOps = true; break; 1191 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break; 1192 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break; 1193 } 1194 1195 Register FirstReg = SwapOps ? FalseReg : TrueReg, 1196 SecondReg = SwapOps ? TrueReg : FalseReg; 1197 1198 // The first input register of isel cannot be r0. If it is a member 1199 // of a register class that can be r0, then copy it first (the 1200 // register allocator should eliminate the copy). 1201 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) || 1202 MRI.getRegClass(FirstReg)->contains(PPC::X0)) { 1203 const TargetRegisterClass *FirstRC = 1204 MRI.getRegClass(FirstReg)->contains(PPC::X0) ? 1205 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass; 1206 Register OldFirstReg = FirstReg; 1207 FirstReg = MRI.createVirtualRegister(FirstRC); 1208 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg) 1209 .addReg(OldFirstReg); 1210 } 1211 1212 BuildMI(MBB, MI, dl, get(OpCode), DestReg) 1213 .addReg(FirstReg).addReg(SecondReg) 1214 .addReg(Cond[1].getReg(), 0, SubIdx); 1215 } 1216 1217 static unsigned getCRBitValue(unsigned CRBit) { 1218 unsigned Ret = 4; 1219 if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT || 1220 CRBit == PPC::CR2LT || CRBit == PPC::CR3LT || 1221 CRBit == PPC::CR4LT || CRBit == PPC::CR5LT || 1222 CRBit == PPC::CR6LT || CRBit == PPC::CR7LT) 1223 Ret = 3; 1224 if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT || 1225 CRBit == PPC::CR2GT || CRBit == PPC::CR3GT || 1226 CRBit == PPC::CR4GT || CRBit == PPC::CR5GT || 1227 CRBit == PPC::CR6GT || CRBit == PPC::CR7GT) 1228 Ret = 2; 1229 if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ || 1230 CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ || 1231 CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ || 1232 CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ) 1233 Ret = 1; 1234 if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN || 1235 CRBit == PPC::CR2UN || CRBit == PPC::CR3UN || 1236 CRBit == PPC::CR4UN || CRBit == PPC::CR5UN || 1237 CRBit == PPC::CR6UN || CRBit == PPC::CR7UN) 1238 Ret = 0; 1239 1240 assert(Ret != 4 && "Invalid CR bit register"); 1241 return Ret; 1242 } 1243 1244 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB, 1245 MachineBasicBlock::iterator I, 1246 const DebugLoc &DL, MCRegister DestReg, 1247 MCRegister SrcReg, bool KillSrc) const { 1248 // We can end up with self copies and similar things as a result of VSX copy 1249 // legalization. Promote them here. 1250 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1251 if (PPC::F8RCRegClass.contains(DestReg) && 1252 PPC::VSRCRegClass.contains(SrcReg)) { 1253 MCRegister SuperReg = 1254 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass); 1255 1256 if (VSXSelfCopyCrash && SrcReg == SuperReg) 1257 llvm_unreachable("nop VSX copy"); 1258 1259 DestReg = SuperReg; 1260 } else if (PPC::F8RCRegClass.contains(SrcReg) && 1261 PPC::VSRCRegClass.contains(DestReg)) { 1262 MCRegister SuperReg = 1263 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass); 1264 1265 if (VSXSelfCopyCrash && DestReg == SuperReg) 1266 llvm_unreachable("nop VSX copy"); 1267 1268 SrcReg = SuperReg; 1269 } 1270 1271 // Different class register copy 1272 if (PPC::CRBITRCRegClass.contains(SrcReg) && 1273 PPC::GPRCRegClass.contains(DestReg)) { 1274 MCRegister CRReg = getCRFromCRBit(SrcReg); 1275 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg); 1276 getKillRegState(KillSrc); 1277 // Rotate the CR bit in the CR fields to be the least significant bit and 1278 // then mask with 0x1 (MB = ME = 31). 1279 BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg) 1280 .addReg(DestReg, RegState::Kill) 1281 .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg))) 1282 .addImm(31) 1283 .addImm(31); 1284 return; 1285 } else if (PPC::CRRCRegClass.contains(SrcReg) && 1286 PPC::G8RCRegClass.contains(DestReg)) { 1287 BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg); 1288 getKillRegState(KillSrc); 1289 return; 1290 } else if (PPC::CRRCRegClass.contains(SrcReg) && 1291 PPC::GPRCRegClass.contains(DestReg)) { 1292 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg); 1293 getKillRegState(KillSrc); 1294 return; 1295 } else if (PPC::G8RCRegClass.contains(SrcReg) && 1296 PPC::VSFRCRegClass.contains(DestReg)) { 1297 assert(Subtarget.hasDirectMove() && 1298 "Subtarget doesn't support directmove, don't know how to copy."); 1299 BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg); 1300 NumGPRtoVSRSpill++; 1301 getKillRegState(KillSrc); 1302 return; 1303 } else if (PPC::VSFRCRegClass.contains(SrcReg) && 1304 PPC::G8RCRegClass.contains(DestReg)) { 1305 assert(Subtarget.hasDirectMove() && 1306 "Subtarget doesn't support directmove, don't know how to copy."); 1307 BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg); 1308 getKillRegState(KillSrc); 1309 return; 1310 } else if (PPC::SPERCRegClass.contains(SrcReg) && 1311 PPC::GPRCRegClass.contains(DestReg)) { 1312 BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg); 1313 getKillRegState(KillSrc); 1314 return; 1315 } else if (PPC::GPRCRegClass.contains(SrcReg) && 1316 PPC::SPERCRegClass.contains(DestReg)) { 1317 BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg); 1318 getKillRegState(KillSrc); 1319 return; 1320 } 1321 1322 unsigned Opc; 1323 if (PPC::GPRCRegClass.contains(DestReg, SrcReg)) 1324 Opc = PPC::OR; 1325 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg)) 1326 Opc = PPC::OR8; 1327 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg)) 1328 Opc = PPC::FMR; 1329 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg)) 1330 Opc = PPC::MCRF; 1331 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg)) 1332 Opc = PPC::VOR; 1333 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg)) 1334 // There are two different ways this can be done: 1335 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only 1336 // issue in VSU pipeline 0. 1337 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but 1338 // can go to either pipeline. 1339 // We'll always use xxlor here, because in practically all cases where 1340 // copies are generated, they are close enough to some use that the 1341 // lower-latency form is preferable. 1342 Opc = PPC::XXLOR; 1343 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) || 1344 PPC::VSSRCRegClass.contains(DestReg, SrcReg)) 1345 Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf; 1346 else if (PPC::QFRCRegClass.contains(DestReg, SrcReg)) 1347 Opc = PPC::QVFMR; 1348 else if (PPC::QSRCRegClass.contains(DestReg, SrcReg)) 1349 Opc = PPC::QVFMRs; 1350 else if (PPC::QBRCRegClass.contains(DestReg, SrcReg)) 1351 Opc = PPC::QVFMRb; 1352 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg)) 1353 Opc = PPC::CROR; 1354 else if (PPC::SPERCRegClass.contains(DestReg, SrcReg)) 1355 Opc = PPC::EVOR; 1356 else 1357 llvm_unreachable("Impossible reg-to-reg copy"); 1358 1359 const MCInstrDesc &MCID = get(Opc); 1360 if (MCID.getNumOperands() == 3) 1361 BuildMI(MBB, I, DL, MCID, DestReg) 1362 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc)); 1363 else 1364 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc)); 1365 } 1366 1367 static unsigned getSpillIndex(const TargetRegisterClass *RC) { 1368 int OpcodeIndex = 0; 1369 1370 if (PPC::GPRCRegClass.hasSubClassEq(RC) || 1371 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) { 1372 OpcodeIndex = SOK_Int4Spill; 1373 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) || 1374 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) { 1375 OpcodeIndex = SOK_Int8Spill; 1376 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) { 1377 OpcodeIndex = SOK_Float8Spill; 1378 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) { 1379 OpcodeIndex = SOK_Float4Spill; 1380 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) { 1381 OpcodeIndex = SOK_SPESpill; 1382 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) { 1383 OpcodeIndex = SOK_CRSpill; 1384 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) { 1385 OpcodeIndex = SOK_CRBitSpill; 1386 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) { 1387 OpcodeIndex = SOK_VRVectorSpill; 1388 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) { 1389 OpcodeIndex = SOK_VSXVectorSpill; 1390 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) { 1391 OpcodeIndex = SOK_VectorFloat8Spill; 1392 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) { 1393 OpcodeIndex = SOK_VectorFloat4Spill; 1394 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) { 1395 OpcodeIndex = SOK_VRSaveSpill; 1396 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) { 1397 OpcodeIndex = SOK_QuadFloat8Spill; 1398 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) { 1399 OpcodeIndex = SOK_QuadFloat4Spill; 1400 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) { 1401 OpcodeIndex = SOK_QuadBitSpill; 1402 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) { 1403 OpcodeIndex = SOK_SpillToVSR; 1404 } else { 1405 llvm_unreachable("Unknown regclass!"); 1406 } 1407 return OpcodeIndex; 1408 } 1409 1410 unsigned 1411 PPCInstrInfo::getStoreOpcodeForSpill(const TargetRegisterClass *RC) const { 1412 const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray(); 1413 return OpcodesForSpill[getSpillIndex(RC)]; 1414 } 1415 1416 unsigned 1417 PPCInstrInfo::getLoadOpcodeForSpill(const TargetRegisterClass *RC) const { 1418 const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray(); 1419 return OpcodesForSpill[getSpillIndex(RC)]; 1420 } 1421 1422 void PPCInstrInfo::StoreRegToStackSlot( 1423 MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx, 1424 const TargetRegisterClass *RC, 1425 SmallVectorImpl<MachineInstr *> &NewMIs) const { 1426 unsigned Opcode = getStoreOpcodeForSpill(RC); 1427 DebugLoc DL; 1428 1429 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1430 FuncInfo->setHasSpills(); 1431 1432 NewMIs.push_back(addFrameReference( 1433 BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)), 1434 FrameIdx)); 1435 1436 if (PPC::CRRCRegClass.hasSubClassEq(RC) || 1437 PPC::CRBITRCRegClass.hasSubClassEq(RC)) 1438 FuncInfo->setSpillsCR(); 1439 1440 if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) 1441 FuncInfo->setSpillsVRSAVE(); 1442 1443 if (isXFormMemOp(Opcode)) 1444 FuncInfo->setHasNonRISpills(); 1445 } 1446 1447 void PPCInstrInfo::storeRegToStackSlotNoUpd( 1448 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg, 1449 bool isKill, int FrameIdx, const TargetRegisterClass *RC, 1450 const TargetRegisterInfo *TRI) const { 1451 MachineFunction &MF = *MBB.getParent(); 1452 SmallVector<MachineInstr *, 4> NewMIs; 1453 1454 StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs); 1455 1456 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i) 1457 MBB.insert(MI, NewMIs[i]); 1458 1459 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1460 MachineMemOperand *MMO = MF.getMachineMemOperand( 1461 MachinePointerInfo::getFixedStack(MF, FrameIdx), 1462 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 1463 MFI.getObjectAlign(FrameIdx)); 1464 NewMIs.back()->addMemOperand(MF, MMO); 1465 } 1466 1467 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB, 1468 MachineBasicBlock::iterator MI, 1469 Register SrcReg, bool isKill, 1470 int FrameIdx, 1471 const TargetRegisterClass *RC, 1472 const TargetRegisterInfo *TRI) const { 1473 // We need to avoid a situation in which the value from a VRRC register is 1474 // spilled using an Altivec instruction and reloaded into a VSRC register 1475 // using a VSX instruction. The issue with this is that the VSX 1476 // load/store instructions swap the doublewords in the vector and the Altivec 1477 // ones don't. The register classes on the spill/reload may be different if 1478 // the register is defined using an Altivec instruction and is then used by a 1479 // VSX instruction. 1480 RC = updatedRC(RC); 1481 storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI); 1482 } 1483 1484 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL, 1485 unsigned DestReg, int FrameIdx, 1486 const TargetRegisterClass *RC, 1487 SmallVectorImpl<MachineInstr *> &NewMIs) 1488 const { 1489 unsigned Opcode = getLoadOpcodeForSpill(RC); 1490 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg), 1491 FrameIdx)); 1492 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1493 1494 if (PPC::CRRCRegClass.hasSubClassEq(RC) || 1495 PPC::CRBITRCRegClass.hasSubClassEq(RC)) 1496 FuncInfo->setSpillsCR(); 1497 1498 if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) 1499 FuncInfo->setSpillsVRSAVE(); 1500 1501 if (isXFormMemOp(Opcode)) 1502 FuncInfo->setHasNonRISpills(); 1503 } 1504 1505 void PPCInstrInfo::loadRegFromStackSlotNoUpd( 1506 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, 1507 int FrameIdx, const TargetRegisterClass *RC, 1508 const TargetRegisterInfo *TRI) const { 1509 MachineFunction &MF = *MBB.getParent(); 1510 SmallVector<MachineInstr*, 4> NewMIs; 1511 DebugLoc DL; 1512 if (MI != MBB.end()) DL = MI->getDebugLoc(); 1513 1514 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1515 FuncInfo->setHasSpills(); 1516 1517 LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs); 1518 1519 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i) 1520 MBB.insert(MI, NewMIs[i]); 1521 1522 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1523 MachineMemOperand *MMO = MF.getMachineMemOperand( 1524 MachinePointerInfo::getFixedStack(MF, FrameIdx), 1525 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 1526 MFI.getObjectAlign(FrameIdx)); 1527 NewMIs.back()->addMemOperand(MF, MMO); 1528 } 1529 1530 void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB, 1531 MachineBasicBlock::iterator MI, 1532 Register DestReg, int FrameIdx, 1533 const TargetRegisterClass *RC, 1534 const TargetRegisterInfo *TRI) const { 1535 // We need to avoid a situation in which the value from a VRRC register is 1536 // spilled using an Altivec instruction and reloaded into a VSRC register 1537 // using a VSX instruction. The issue with this is that the VSX 1538 // load/store instructions swap the doublewords in the vector and the Altivec 1539 // ones don't. The register classes on the spill/reload may be different if 1540 // the register is defined using an Altivec instruction and is then used by a 1541 // VSX instruction. 1542 RC = updatedRC(RC); 1543 1544 loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI); 1545 } 1546 1547 bool PPCInstrInfo:: 1548 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const { 1549 assert(Cond.size() == 2 && "Invalid PPC branch opcode!"); 1550 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR) 1551 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0); 1552 else 1553 // Leave the CR# the same, but invert the condition. 1554 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm())); 1555 return false; 1556 } 1557 1558 // For some instructions, it is legal to fold ZERO into the RA register field. 1559 // This function performs that fold by replacing the operand with PPC::ZERO, 1560 // it does not consider whether the load immediate zero is no longer in use. 1561 bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, 1562 Register Reg) const { 1563 // A zero immediate should always be loaded with a single li. 1564 unsigned DefOpc = DefMI.getOpcode(); 1565 if (DefOpc != PPC::LI && DefOpc != PPC::LI8) 1566 return false; 1567 if (!DefMI.getOperand(1).isImm()) 1568 return false; 1569 if (DefMI.getOperand(1).getImm() != 0) 1570 return false; 1571 1572 // Note that we cannot here invert the arguments of an isel in order to fold 1573 // a ZERO into what is presented as the second argument. All we have here 1574 // is the condition bit, and that might come from a CR-logical bit operation. 1575 1576 const MCInstrDesc &UseMCID = UseMI.getDesc(); 1577 1578 // Only fold into real machine instructions. 1579 if (UseMCID.isPseudo()) 1580 return false; 1581 1582 // We need to find which of the User's operands is to be folded, that will be 1583 // the operand that matches the given register ID. 1584 unsigned UseIdx; 1585 for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx) 1586 if (UseMI.getOperand(UseIdx).isReg() && 1587 UseMI.getOperand(UseIdx).getReg() == Reg) 1588 break; 1589 1590 assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI"); 1591 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg"); 1592 1593 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx]; 1594 1595 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0 1596 // register (which might also be specified as a pointer class kind). 1597 if (UseInfo->isLookupPtrRegClass()) { 1598 if (UseInfo->RegClass /* Kind */ != 1) 1599 return false; 1600 } else { 1601 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID && 1602 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID) 1603 return false; 1604 } 1605 1606 // Make sure this is not tied to an output register (or otherwise 1607 // constrained). This is true for ST?UX registers, for example, which 1608 // are tied to their output registers. 1609 if (UseInfo->Constraints != 0) 1610 return false; 1611 1612 MCRegister ZeroReg; 1613 if (UseInfo->isLookupPtrRegClass()) { 1614 bool isPPC64 = Subtarget.isPPC64(); 1615 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO; 1616 } else { 1617 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ? 1618 PPC::ZERO8 : PPC::ZERO; 1619 } 1620 1621 UseMI.getOperand(UseIdx).setReg(ZeroReg); 1622 return true; 1623 } 1624 1625 // Folds zero into instructions which have a load immediate zero as an operand 1626 // but also recognize zero as immediate zero. If the definition of the load 1627 // has no more users it is deleted. 1628 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, 1629 Register Reg, MachineRegisterInfo *MRI) const { 1630 bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg); 1631 if (MRI->use_nodbg_empty(Reg)) 1632 DefMI.eraseFromParent(); 1633 return Changed; 1634 } 1635 1636 static bool MBBDefinesCTR(MachineBasicBlock &MBB) { 1637 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end(); 1638 I != IE; ++I) 1639 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8)) 1640 return true; 1641 return false; 1642 } 1643 1644 // We should make sure that, if we're going to predicate both sides of a 1645 // condition (a diamond), that both sides don't define the counter register. We 1646 // can predicate counter-decrement-based branches, but while that predicates 1647 // the branching, it does not predicate the counter decrement. If we tried to 1648 // merge the triangle into one predicated block, we'd decrement the counter 1649 // twice. 1650 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB, 1651 unsigned NumT, unsigned ExtraT, 1652 MachineBasicBlock &FMBB, 1653 unsigned NumF, unsigned ExtraF, 1654 BranchProbability Probability) const { 1655 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB)); 1656 } 1657 1658 1659 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const { 1660 // The predicated branches are identified by their type, not really by the 1661 // explicit presence of a predicate. Furthermore, some of them can be 1662 // predicated more than once. Because if conversion won't try to predicate 1663 // any instruction which already claims to be predicated (by returning true 1664 // here), always return false. In doing so, we let isPredicable() be the 1665 // final word on whether not the instruction can be (further) predicated. 1666 1667 return false; 1668 } 1669 1670 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI, 1671 ArrayRef<MachineOperand> Pred) const { 1672 unsigned OpC = MI.getOpcode(); 1673 if (OpC == PPC::BLR || OpC == PPC::BLR8) { 1674 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) { 1675 bool isPPC64 = Subtarget.isPPC64(); 1676 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) 1677 : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR))); 1678 // Need add Def and Use for CTR implicit operand. 1679 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1680 .addReg(Pred[1].getReg(), RegState::Implicit) 1681 .addReg(Pred[1].getReg(), RegState::ImplicitDefine); 1682 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) { 1683 MI.setDesc(get(PPC::BCLR)); 1684 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1685 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) { 1686 MI.setDesc(get(PPC::BCLRn)); 1687 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1688 } else { 1689 MI.setDesc(get(PPC::BCCLR)); 1690 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1691 .addImm(Pred[0].getImm()) 1692 .add(Pred[1]); 1693 } 1694 1695 return true; 1696 } else if (OpC == PPC::B) { 1697 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) { 1698 bool isPPC64 = Subtarget.isPPC64(); 1699 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) 1700 : (isPPC64 ? PPC::BDZ8 : PPC::BDZ))); 1701 // Need add Def and Use for CTR implicit operand. 1702 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1703 .addReg(Pred[1].getReg(), RegState::Implicit) 1704 .addReg(Pred[1].getReg(), RegState::ImplicitDefine); 1705 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) { 1706 MachineBasicBlock *MBB = MI.getOperand(0).getMBB(); 1707 MI.RemoveOperand(0); 1708 1709 MI.setDesc(get(PPC::BC)); 1710 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1711 .add(Pred[1]) 1712 .addMBB(MBB); 1713 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) { 1714 MachineBasicBlock *MBB = MI.getOperand(0).getMBB(); 1715 MI.RemoveOperand(0); 1716 1717 MI.setDesc(get(PPC::BCn)); 1718 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1719 .add(Pred[1]) 1720 .addMBB(MBB); 1721 } else { 1722 MachineBasicBlock *MBB = MI.getOperand(0).getMBB(); 1723 MI.RemoveOperand(0); 1724 1725 MI.setDesc(get(PPC::BCC)); 1726 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1727 .addImm(Pred[0].getImm()) 1728 .add(Pred[1]) 1729 .addMBB(MBB); 1730 } 1731 1732 return true; 1733 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL || 1734 OpC == PPC::BCTRL8) { 1735 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) 1736 llvm_unreachable("Cannot predicate bctr[l] on the ctr register"); 1737 1738 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8; 1739 bool isPPC64 = Subtarget.isPPC64(); 1740 1741 if (Pred[0].getImm() == PPC::PRED_BIT_SET) { 1742 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) 1743 : (setLR ? PPC::BCCTRL : PPC::BCCTR))); 1744 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1745 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) { 1746 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) 1747 : (setLR ? PPC::BCCTRLn : PPC::BCCTRn))); 1748 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1749 } else { 1750 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) 1751 : (setLR ? PPC::BCCCTRL : PPC::BCCCTR))); 1752 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1753 .addImm(Pred[0].getImm()) 1754 .add(Pred[1]); 1755 } 1756 1757 // Need add Def and Use for LR implicit operand. 1758 if (setLR) 1759 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1760 .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::Implicit) 1761 .addReg(isPPC64 ? PPC::LR8 : PPC::LR, RegState::ImplicitDefine); 1762 1763 return true; 1764 } 1765 1766 return false; 1767 } 1768 1769 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1, 1770 ArrayRef<MachineOperand> Pred2) const { 1771 assert(Pred1.size() == 2 && "Invalid PPC first predicate"); 1772 assert(Pred2.size() == 2 && "Invalid PPC second predicate"); 1773 1774 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR) 1775 return false; 1776 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR) 1777 return false; 1778 1779 // P1 can only subsume P2 if they test the same condition register. 1780 if (Pred1[1].getReg() != Pred2[1].getReg()) 1781 return false; 1782 1783 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm(); 1784 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm(); 1785 1786 if (P1 == P2) 1787 return true; 1788 1789 // Does P1 subsume P2, e.g. GE subsumes GT. 1790 if (P1 == PPC::PRED_LE && 1791 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ)) 1792 return true; 1793 if (P1 == PPC::PRED_GE && 1794 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ)) 1795 return true; 1796 1797 return false; 1798 } 1799 1800 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI, 1801 std::vector<MachineOperand> &Pred) const { 1802 // Note: At the present time, the contents of Pred from this function is 1803 // unused by IfConversion. This implementation follows ARM by pushing the 1804 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of 1805 // predicate, instructions defining CTR or CTR8 are also included as 1806 // predicate-defining instructions. 1807 1808 const TargetRegisterClass *RCs[] = 1809 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass, 1810 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass }; 1811 1812 bool Found = false; 1813 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1814 const MachineOperand &MO = MI.getOperand(i); 1815 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) { 1816 const TargetRegisterClass *RC = RCs[c]; 1817 if (MO.isReg()) { 1818 if (MO.isDef() && RC->contains(MO.getReg())) { 1819 Pred.push_back(MO); 1820 Found = true; 1821 } 1822 } else if (MO.isRegMask()) { 1823 for (TargetRegisterClass::iterator I = RC->begin(), 1824 IE = RC->end(); I != IE; ++I) 1825 if (MO.clobbersPhysReg(*I)) { 1826 Pred.push_back(MO); 1827 Found = true; 1828 } 1829 } 1830 } 1831 } 1832 1833 return Found; 1834 } 1835 1836 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg, 1837 Register &SrcReg2, int &Mask, 1838 int &Value) const { 1839 unsigned Opc = MI.getOpcode(); 1840 1841 switch (Opc) { 1842 default: return false; 1843 case PPC::CMPWI: 1844 case PPC::CMPLWI: 1845 case PPC::CMPDI: 1846 case PPC::CMPLDI: 1847 SrcReg = MI.getOperand(1).getReg(); 1848 SrcReg2 = 0; 1849 Value = MI.getOperand(2).getImm(); 1850 Mask = 0xFFFF; 1851 return true; 1852 case PPC::CMPW: 1853 case PPC::CMPLW: 1854 case PPC::CMPD: 1855 case PPC::CMPLD: 1856 case PPC::FCMPUS: 1857 case PPC::FCMPUD: 1858 SrcReg = MI.getOperand(1).getReg(); 1859 SrcReg2 = MI.getOperand(2).getReg(); 1860 Value = 0; 1861 Mask = 0; 1862 return true; 1863 } 1864 } 1865 1866 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, 1867 Register SrcReg2, int Mask, int Value, 1868 const MachineRegisterInfo *MRI) const { 1869 if (DisableCmpOpt) 1870 return false; 1871 1872 int OpC = CmpInstr.getOpcode(); 1873 Register CRReg = CmpInstr.getOperand(0).getReg(); 1874 1875 // FP record forms set CR1 based on the exception status bits, not a 1876 // comparison with zero. 1877 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD) 1878 return false; 1879 1880 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1881 // The record forms set the condition register based on a signed comparison 1882 // with zero (so says the ISA manual). This is not as straightforward as it 1883 // seems, however, because this is always a 64-bit comparison on PPC64, even 1884 // for instructions that are 32-bit in nature (like slw for example). 1885 // So, on PPC32, for unsigned comparisons, we can use the record forms only 1886 // for equality checks (as those don't depend on the sign). On PPC64, 1887 // we are restricted to equality for unsigned 64-bit comparisons and for 1888 // signed 32-bit comparisons the applicability is more restricted. 1889 bool isPPC64 = Subtarget.isPPC64(); 1890 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW; 1891 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW; 1892 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD; 1893 1894 // Look through copies unless that gets us to a physical register. 1895 Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI); 1896 if (ActualSrc.isVirtual()) 1897 SrcReg = ActualSrc; 1898 1899 // Get the unique definition of SrcReg. 1900 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg); 1901 if (!MI) return false; 1902 1903 bool equalityOnly = false; 1904 bool noSub = false; 1905 if (isPPC64) { 1906 if (is32BitSignedCompare) { 1907 // We can perform this optimization only if MI is sign-extending. 1908 if (isSignExtended(*MI)) 1909 noSub = true; 1910 else 1911 return false; 1912 } else if (is32BitUnsignedCompare) { 1913 // We can perform this optimization, equality only, if MI is 1914 // zero-extending. 1915 if (isZeroExtended(*MI)) { 1916 noSub = true; 1917 equalityOnly = true; 1918 } else 1919 return false; 1920 } else 1921 equalityOnly = is64BitUnsignedCompare; 1922 } else 1923 equalityOnly = is32BitUnsignedCompare; 1924 1925 if (equalityOnly) { 1926 // We need to check the uses of the condition register in order to reject 1927 // non-equality comparisons. 1928 for (MachineRegisterInfo::use_instr_iterator 1929 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end(); 1930 I != IE; ++I) { 1931 MachineInstr *UseMI = &*I; 1932 if (UseMI->getOpcode() == PPC::BCC) { 1933 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm(); 1934 unsigned PredCond = PPC::getPredicateCondition(Pred); 1935 // We ignore hint bits when checking for non-equality comparisons. 1936 if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE) 1937 return false; 1938 } else if (UseMI->getOpcode() == PPC::ISEL || 1939 UseMI->getOpcode() == PPC::ISEL8) { 1940 unsigned SubIdx = UseMI->getOperand(3).getSubReg(); 1941 if (SubIdx != PPC::sub_eq) 1942 return false; 1943 } else 1944 return false; 1945 } 1946 } 1947 1948 MachineBasicBlock::iterator I = CmpInstr; 1949 1950 // Scan forward to find the first use of the compare. 1951 for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL; 1952 ++I) { 1953 bool FoundUse = false; 1954 for (MachineRegisterInfo::use_instr_iterator 1955 J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end(); 1956 J != JE; ++J) 1957 if (&*J == &*I) { 1958 FoundUse = true; 1959 break; 1960 } 1961 1962 if (FoundUse) 1963 break; 1964 } 1965 1966 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate; 1967 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate; 1968 1969 // There are two possible candidates which can be changed to set CR[01]. 1970 // One is MI, the other is a SUB instruction. 1971 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1). 1972 MachineInstr *Sub = nullptr; 1973 if (SrcReg2 != 0) 1974 // MI is not a candidate for CMPrr. 1975 MI = nullptr; 1976 // FIXME: Conservatively refuse to convert an instruction which isn't in the 1977 // same BB as the comparison. This is to allow the check below to avoid calls 1978 // (and other explicit clobbers); instead we should really check for these 1979 // more explicitly (in at least a few predecessors). 1980 else if (MI->getParent() != CmpInstr.getParent()) 1981 return false; 1982 else if (Value != 0) { 1983 // The record-form instructions set CR bit based on signed comparison 1984 // against 0. We try to convert a compare against 1 or -1 into a compare 1985 // against 0 to exploit record-form instructions. For example, we change 1986 // the condition "greater than -1" into "greater than or equal to 0" 1987 // and "less than 1" into "less than or equal to 0". 1988 1989 // Since we optimize comparison based on a specific branch condition, 1990 // we don't optimize if condition code is used by more than once. 1991 if (equalityOnly || !MRI->hasOneUse(CRReg)) 1992 return false; 1993 1994 MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg); 1995 if (UseMI->getOpcode() != PPC::BCC) 1996 return false; 1997 1998 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm(); 1999 unsigned PredCond = PPC::getPredicateCondition(Pred); 2000 unsigned PredHint = PPC::getPredicateHint(Pred); 2001 int16_t Immed = (int16_t)Value; 2002 2003 // When modifying the condition in the predicate, we propagate hint bits 2004 // from the original predicate to the new one. 2005 if (Immed == -1 && PredCond == PPC::PRED_GT) 2006 // We convert "greater than -1" into "greater than or equal to 0", 2007 // since we are assuming signed comparison by !equalityOnly 2008 Pred = PPC::getPredicate(PPC::PRED_GE, PredHint); 2009 else if (Immed == -1 && PredCond == PPC::PRED_LE) 2010 // We convert "less than or equal to -1" into "less than 0". 2011 Pred = PPC::getPredicate(PPC::PRED_LT, PredHint); 2012 else if (Immed == 1 && PredCond == PPC::PRED_LT) 2013 // We convert "less than 1" into "less than or equal to 0". 2014 Pred = PPC::getPredicate(PPC::PRED_LE, PredHint); 2015 else if (Immed == 1 && PredCond == PPC::PRED_GE) 2016 // We convert "greater than or equal to 1" into "greater than 0". 2017 Pred = PPC::getPredicate(PPC::PRED_GT, PredHint); 2018 else 2019 return false; 2020 2021 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred)); 2022 } 2023 2024 // Search for Sub. 2025 --I; 2026 2027 // Get ready to iterate backward from CmpInstr. 2028 MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin(); 2029 2030 for (; I != E && !noSub; --I) { 2031 const MachineInstr &Instr = *I; 2032 unsigned IOpC = Instr.getOpcode(); 2033 2034 if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) || 2035 Instr.readsRegister(PPC::CR0, TRI))) 2036 // This instruction modifies or uses the record condition register after 2037 // the one we want to change. While we could do this transformation, it 2038 // would likely not be profitable. This transformation removes one 2039 // instruction, and so even forcing RA to generate one move probably 2040 // makes it unprofitable. 2041 return false; 2042 2043 // Check whether CmpInstr can be made redundant by the current instruction. 2044 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW || 2045 OpC == PPC::CMPD || OpC == PPC::CMPLD) && 2046 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) && 2047 ((Instr.getOperand(1).getReg() == SrcReg && 2048 Instr.getOperand(2).getReg() == SrcReg2) || 2049 (Instr.getOperand(1).getReg() == SrcReg2 && 2050 Instr.getOperand(2).getReg() == SrcReg))) { 2051 Sub = &*I; 2052 break; 2053 } 2054 2055 if (I == B) 2056 // The 'and' is below the comparison instruction. 2057 return false; 2058 } 2059 2060 // Return false if no candidates exist. 2061 if (!MI && !Sub) 2062 return false; 2063 2064 // The single candidate is called MI. 2065 if (!MI) MI = Sub; 2066 2067 int NewOpC = -1; 2068 int MIOpC = MI->getOpcode(); 2069 if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec || 2070 MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec) 2071 NewOpC = MIOpC; 2072 else { 2073 NewOpC = PPC::getRecordFormOpcode(MIOpC); 2074 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1) 2075 NewOpC = MIOpC; 2076 } 2077 2078 // FIXME: On the non-embedded POWER architectures, only some of the record 2079 // forms are fast, and we should use only the fast ones. 2080 2081 // The defining instruction has a record form (or is already a record 2082 // form). It is possible, however, that we'll need to reverse the condition 2083 // code of the users. 2084 if (NewOpC == -1) 2085 return false; 2086 2087 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP 2088 // needs to be updated to be based on SUB. Push the condition code 2089 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the 2090 // condition code of these operands will be modified. 2091 // Here, Value == 0 means we haven't converted comparison against 1 or -1 to 2092 // comparison against 0, which may modify predicate. 2093 bool ShouldSwap = false; 2094 if (Sub && Value == 0) { 2095 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 && 2096 Sub->getOperand(2).getReg() == SrcReg; 2097 2098 // The operands to subf are the opposite of sub, so only in the fixed-point 2099 // case, invert the order. 2100 ShouldSwap = !ShouldSwap; 2101 } 2102 2103 if (ShouldSwap) 2104 for (MachineRegisterInfo::use_instr_iterator 2105 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end(); 2106 I != IE; ++I) { 2107 MachineInstr *UseMI = &*I; 2108 if (UseMI->getOpcode() == PPC::BCC) { 2109 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm(); 2110 unsigned PredCond = PPC::getPredicateCondition(Pred); 2111 assert((!equalityOnly || 2112 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) && 2113 "Invalid predicate for equality-only optimization"); 2114 (void)PredCond; // To suppress warning in release build. 2115 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), 2116 PPC::getSwappedPredicate(Pred))); 2117 } else if (UseMI->getOpcode() == PPC::ISEL || 2118 UseMI->getOpcode() == PPC::ISEL8) { 2119 unsigned NewSubReg = UseMI->getOperand(3).getSubReg(); 2120 assert((!equalityOnly || NewSubReg == PPC::sub_eq) && 2121 "Invalid CR bit for equality-only optimization"); 2122 2123 if (NewSubReg == PPC::sub_lt) 2124 NewSubReg = PPC::sub_gt; 2125 else if (NewSubReg == PPC::sub_gt) 2126 NewSubReg = PPC::sub_lt; 2127 2128 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)), 2129 NewSubReg)); 2130 } else // We need to abort on a user we don't understand. 2131 return false; 2132 } 2133 assert(!(Value != 0 && ShouldSwap) && 2134 "Non-zero immediate support and ShouldSwap" 2135 "may conflict in updating predicate"); 2136 2137 // Create a new virtual register to hold the value of the CR set by the 2138 // record-form instruction. If the instruction was not previously in 2139 // record form, then set the kill flag on the CR. 2140 CmpInstr.eraseFromParent(); 2141 2142 MachineBasicBlock::iterator MII = MI; 2143 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(), 2144 get(TargetOpcode::COPY), CRReg) 2145 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0); 2146 2147 // Even if CR0 register were dead before, it is alive now since the 2148 // instruction we just built uses it. 2149 MI->clearRegisterDeads(PPC::CR0); 2150 2151 if (MIOpC != NewOpC) { 2152 // We need to be careful here: we're replacing one instruction with 2153 // another, and we need to make sure that we get all of the right 2154 // implicit uses and defs. On the other hand, the caller may be holding 2155 // an iterator to this instruction, and so we can't delete it (this is 2156 // specifically the case if this is the instruction directly after the 2157 // compare). 2158 2159 // Rotates are expensive instructions. If we're emitting a record-form 2160 // rotate that can just be an andi/andis, we should just emit that. 2161 if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) { 2162 Register GPRRes = MI->getOperand(0).getReg(); 2163 int64_t SH = MI->getOperand(2).getImm(); 2164 int64_t MB = MI->getOperand(3).getImm(); 2165 int64_t ME = MI->getOperand(4).getImm(); 2166 // We can only do this if both the start and end of the mask are in the 2167 // same halfword. 2168 bool MBInLoHWord = MB >= 16; 2169 bool MEInLoHWord = ME >= 16; 2170 uint64_t Mask = ~0LLU; 2171 2172 if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) { 2173 Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1); 2174 // The mask value needs to shift right 16 if we're emitting andis. 2175 Mask >>= MBInLoHWord ? 0 : 16; 2176 NewOpC = MIOpC == PPC::RLWINM 2177 ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec) 2178 : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec); 2179 } else if (MRI->use_empty(GPRRes) && (ME == 31) && 2180 (ME - MB + 1 == SH) && (MB >= 16)) { 2181 // If we are rotating by the exact number of bits as are in the mask 2182 // and the mask is in the least significant bits of the register, 2183 // that's just an andis. (as long as the GPR result has no uses). 2184 Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1); 2185 Mask >>= 16; 2186 NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec; 2187 } 2188 // If we've set the mask, we can transform. 2189 if (Mask != ~0LLU) { 2190 MI->RemoveOperand(4); 2191 MI->RemoveOperand(3); 2192 MI->getOperand(2).setImm(Mask); 2193 NumRcRotatesConvertedToRcAnd++; 2194 } 2195 } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) { 2196 int64_t MB = MI->getOperand(3).getImm(); 2197 if (MB >= 48) { 2198 uint64_t Mask = (1LLU << (63 - MB + 1)) - 1; 2199 NewOpC = PPC::ANDI8_rec; 2200 MI->RemoveOperand(3); 2201 MI->getOperand(2).setImm(Mask); 2202 NumRcRotatesConvertedToRcAnd++; 2203 } 2204 } 2205 2206 const MCInstrDesc &NewDesc = get(NewOpC); 2207 MI->setDesc(NewDesc); 2208 2209 if (NewDesc.ImplicitDefs) 2210 for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs(); 2211 *ImpDefs; ++ImpDefs) 2212 if (!MI->definesRegister(*ImpDefs)) 2213 MI->addOperand(*MI->getParent()->getParent(), 2214 MachineOperand::CreateReg(*ImpDefs, true, true)); 2215 if (NewDesc.ImplicitUses) 2216 for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses(); 2217 *ImpUses; ++ImpUses) 2218 if (!MI->readsRegister(*ImpUses)) 2219 MI->addOperand(*MI->getParent()->getParent(), 2220 MachineOperand::CreateReg(*ImpUses, false, true)); 2221 } 2222 assert(MI->definesRegister(PPC::CR0) && 2223 "Record-form instruction does not define cr0?"); 2224 2225 // Modify the condition code of operands in OperandsToUpdate. 2226 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to 2227 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc. 2228 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++) 2229 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second); 2230 2231 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++) 2232 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second); 2233 2234 return true; 2235 } 2236 2237 /// GetInstSize - Return the number of bytes of code the specified 2238 /// instruction may be. This returns the maximum number of bytes. 2239 /// 2240 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const { 2241 unsigned Opcode = MI.getOpcode(); 2242 2243 if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) { 2244 const MachineFunction *MF = MI.getParent()->getParent(); 2245 const char *AsmStr = MI.getOperand(0).getSymbolName(); 2246 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo()); 2247 } else if (Opcode == TargetOpcode::STACKMAP) { 2248 StackMapOpers Opers(&MI); 2249 return Opers.getNumPatchBytes(); 2250 } else if (Opcode == TargetOpcode::PATCHPOINT) { 2251 PatchPointOpers Opers(&MI); 2252 return Opers.getNumPatchBytes(); 2253 } else { 2254 return get(Opcode).getSize(); 2255 } 2256 } 2257 2258 std::pair<unsigned, unsigned> 2259 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const { 2260 const unsigned Mask = PPCII::MO_ACCESS_MASK; 2261 return std::make_pair(TF & Mask, TF & ~Mask); 2262 } 2263 2264 ArrayRef<std::pair<unsigned, const char *>> 2265 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const { 2266 using namespace PPCII; 2267 static const std::pair<unsigned, const char *> TargetFlags[] = { 2268 {MO_LO, "ppc-lo"}, 2269 {MO_HA, "ppc-ha"}, 2270 {MO_TPREL_LO, "ppc-tprel-lo"}, 2271 {MO_TPREL_HA, "ppc-tprel-ha"}, 2272 {MO_DTPREL_LO, "ppc-dtprel-lo"}, 2273 {MO_TLSLD_LO, "ppc-tlsld-lo"}, 2274 {MO_TOC_LO, "ppc-toc-lo"}, 2275 {MO_TLS, "ppc-tls"}}; 2276 return makeArrayRef(TargetFlags); 2277 } 2278 2279 ArrayRef<std::pair<unsigned, const char *>> 2280 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const { 2281 using namespace PPCII; 2282 static const std::pair<unsigned, const char *> TargetFlags[] = { 2283 {MO_PLT, "ppc-plt"}, 2284 {MO_PIC_FLAG, "ppc-pic"}, 2285 {MO_PCREL_FLAG, "ppc-pcrel"}, 2286 {MO_GOT_FLAG, "ppc-got"}, 2287 {MO_PCREL_OPT_FLAG, "ppc-opt-pcrel"}}; 2288 return makeArrayRef(TargetFlags); 2289 } 2290 2291 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction. 2292 // The VSX versions have the advantage of a full 64-register target whereas 2293 // the FP ones have the advantage of lower latency and higher throughput. So 2294 // what we are after is using the faster instructions in low register pressure 2295 // situations and using the larger register file in high register pressure 2296 // situations. 2297 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const { 2298 unsigned UpperOpcode, LowerOpcode; 2299 switch (MI.getOpcode()) { 2300 case PPC::DFLOADf32: 2301 UpperOpcode = PPC::LXSSP; 2302 LowerOpcode = PPC::LFS; 2303 break; 2304 case PPC::DFLOADf64: 2305 UpperOpcode = PPC::LXSD; 2306 LowerOpcode = PPC::LFD; 2307 break; 2308 case PPC::DFSTOREf32: 2309 UpperOpcode = PPC::STXSSP; 2310 LowerOpcode = PPC::STFS; 2311 break; 2312 case PPC::DFSTOREf64: 2313 UpperOpcode = PPC::STXSD; 2314 LowerOpcode = PPC::STFD; 2315 break; 2316 case PPC::XFLOADf32: 2317 UpperOpcode = PPC::LXSSPX; 2318 LowerOpcode = PPC::LFSX; 2319 break; 2320 case PPC::XFLOADf64: 2321 UpperOpcode = PPC::LXSDX; 2322 LowerOpcode = PPC::LFDX; 2323 break; 2324 case PPC::XFSTOREf32: 2325 UpperOpcode = PPC::STXSSPX; 2326 LowerOpcode = PPC::STFSX; 2327 break; 2328 case PPC::XFSTOREf64: 2329 UpperOpcode = PPC::STXSDX; 2330 LowerOpcode = PPC::STFDX; 2331 break; 2332 case PPC::LIWAX: 2333 UpperOpcode = PPC::LXSIWAX; 2334 LowerOpcode = PPC::LFIWAX; 2335 break; 2336 case PPC::LIWZX: 2337 UpperOpcode = PPC::LXSIWZX; 2338 LowerOpcode = PPC::LFIWZX; 2339 break; 2340 case PPC::STIWX: 2341 UpperOpcode = PPC::STXSIWX; 2342 LowerOpcode = PPC::STFIWX; 2343 break; 2344 default: 2345 llvm_unreachable("Unknown Operation!"); 2346 } 2347 2348 Register TargetReg = MI.getOperand(0).getReg(); 2349 unsigned Opcode; 2350 if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) || 2351 (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31)) 2352 Opcode = LowerOpcode; 2353 else 2354 Opcode = UpperOpcode; 2355 MI.setDesc(get(Opcode)); 2356 return true; 2357 } 2358 2359 static bool isAnImmediateOperand(const MachineOperand &MO) { 2360 return MO.isCPI() || MO.isGlobal() || MO.isImm(); 2361 } 2362 2363 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const { 2364 auto &MBB = *MI.getParent(); 2365 auto DL = MI.getDebugLoc(); 2366 2367 switch (MI.getOpcode()) { 2368 case TargetOpcode::LOAD_STACK_GUARD: { 2369 assert(Subtarget.isTargetLinux() && 2370 "Only Linux target is expected to contain LOAD_STACK_GUARD"); 2371 const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008; 2372 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2; 2373 MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ)); 2374 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 2375 .addImm(Offset) 2376 .addReg(Reg); 2377 return true; 2378 } 2379 case PPC::DFLOADf32: 2380 case PPC::DFLOADf64: 2381 case PPC::DFSTOREf32: 2382 case PPC::DFSTOREf64: { 2383 assert(Subtarget.hasP9Vector() && 2384 "Invalid D-Form Pseudo-ops on Pre-P9 target."); 2385 assert(MI.getOperand(2).isReg() && 2386 isAnImmediateOperand(MI.getOperand(1)) && 2387 "D-form op must have register and immediate operands"); 2388 return expandVSXMemPseudo(MI); 2389 } 2390 case PPC::XFLOADf32: 2391 case PPC::XFSTOREf32: 2392 case PPC::LIWAX: 2393 case PPC::LIWZX: 2394 case PPC::STIWX: { 2395 assert(Subtarget.hasP8Vector() && 2396 "Invalid X-Form Pseudo-ops on Pre-P8 target."); 2397 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() && 2398 "X-form op must have register and register operands"); 2399 return expandVSXMemPseudo(MI); 2400 } 2401 case PPC::XFLOADf64: 2402 case PPC::XFSTOREf64: { 2403 assert(Subtarget.hasVSX() && 2404 "Invalid X-Form Pseudo-ops on target that has no VSX."); 2405 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() && 2406 "X-form op must have register and register operands"); 2407 return expandVSXMemPseudo(MI); 2408 } 2409 case PPC::SPILLTOVSR_LD: { 2410 Register TargetReg = MI.getOperand(0).getReg(); 2411 if (PPC::VSFRCRegClass.contains(TargetReg)) { 2412 MI.setDesc(get(PPC::DFLOADf64)); 2413 return expandPostRAPseudo(MI); 2414 } 2415 else 2416 MI.setDesc(get(PPC::LD)); 2417 return true; 2418 } 2419 case PPC::SPILLTOVSR_ST: { 2420 Register SrcReg = MI.getOperand(0).getReg(); 2421 if (PPC::VSFRCRegClass.contains(SrcReg)) { 2422 NumStoreSPILLVSRRCAsVec++; 2423 MI.setDesc(get(PPC::DFSTOREf64)); 2424 return expandPostRAPseudo(MI); 2425 } else { 2426 NumStoreSPILLVSRRCAsGpr++; 2427 MI.setDesc(get(PPC::STD)); 2428 } 2429 return true; 2430 } 2431 case PPC::SPILLTOVSR_LDX: { 2432 Register TargetReg = MI.getOperand(0).getReg(); 2433 if (PPC::VSFRCRegClass.contains(TargetReg)) 2434 MI.setDesc(get(PPC::LXSDX)); 2435 else 2436 MI.setDesc(get(PPC::LDX)); 2437 return true; 2438 } 2439 case PPC::SPILLTOVSR_STX: { 2440 Register SrcReg = MI.getOperand(0).getReg(); 2441 if (PPC::VSFRCRegClass.contains(SrcReg)) { 2442 NumStoreSPILLVSRRCAsVec++; 2443 MI.setDesc(get(PPC::STXSDX)); 2444 } else { 2445 NumStoreSPILLVSRRCAsGpr++; 2446 MI.setDesc(get(PPC::STDX)); 2447 } 2448 return true; 2449 } 2450 2451 case PPC::CFENCE8: { 2452 auto Val = MI.getOperand(0).getReg(); 2453 BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val); 2454 BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP)) 2455 .addImm(PPC::PRED_NE_MINUS) 2456 .addReg(PPC::CR7) 2457 .addImm(1); 2458 MI.setDesc(get(PPC::ISYNC)); 2459 MI.RemoveOperand(0); 2460 return true; 2461 } 2462 } 2463 return false; 2464 } 2465 2466 // Essentially a compile-time implementation of a compare->isel sequence. 2467 // It takes two constants to compare, along with the true/false registers 2468 // and the comparison type (as a subreg to a CR field) and returns one 2469 // of the true/false registers, depending on the comparison results. 2470 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc, 2471 unsigned TrueReg, unsigned FalseReg, 2472 unsigned CRSubReg) { 2473 // Signed comparisons. The immediates are assumed to be sign-extended. 2474 if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) { 2475 switch (CRSubReg) { 2476 default: llvm_unreachable("Unknown integer comparison type."); 2477 case PPC::sub_lt: 2478 return Imm1 < Imm2 ? TrueReg : FalseReg; 2479 case PPC::sub_gt: 2480 return Imm1 > Imm2 ? TrueReg : FalseReg; 2481 case PPC::sub_eq: 2482 return Imm1 == Imm2 ? TrueReg : FalseReg; 2483 } 2484 } 2485 // Unsigned comparisons. 2486 else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) { 2487 switch (CRSubReg) { 2488 default: llvm_unreachable("Unknown integer comparison type."); 2489 case PPC::sub_lt: 2490 return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg; 2491 case PPC::sub_gt: 2492 return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg; 2493 case PPC::sub_eq: 2494 return Imm1 == Imm2 ? TrueReg : FalseReg; 2495 } 2496 } 2497 return PPC::NoRegister; 2498 } 2499 2500 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI, 2501 unsigned OpNo, 2502 int64_t Imm) const { 2503 assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG"); 2504 // Replace the REG with the Immediate. 2505 Register InUseReg = MI.getOperand(OpNo).getReg(); 2506 MI.getOperand(OpNo).ChangeToImmediate(Imm); 2507 2508 if (MI.implicit_operands().empty()) 2509 return; 2510 2511 // We need to make sure that the MI didn't have any implicit use 2512 // of this REG any more. 2513 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2514 int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI); 2515 if (UseOpIdx >= 0) { 2516 MachineOperand &MO = MI.getOperand(UseOpIdx); 2517 if (MO.isImplicit()) 2518 // The operands must always be in the following order: 2519 // - explicit reg defs, 2520 // - other explicit operands (reg uses, immediates, etc.), 2521 // - implicit reg defs 2522 // - implicit reg uses 2523 // Therefore, removing the implicit operand won't change the explicit 2524 // operands layout. 2525 MI.RemoveOperand(UseOpIdx); 2526 } 2527 } 2528 2529 // Replace an instruction with one that materializes a constant (and sets 2530 // CR0 if the original instruction was a record-form instruction). 2531 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI, 2532 const LoadImmediateInfo &LII) const { 2533 // Remove existing operands. 2534 int OperandToKeep = LII.SetCR ? 1 : 0; 2535 for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--) 2536 MI.RemoveOperand(i); 2537 2538 // Replace the instruction. 2539 if (LII.SetCR) { 2540 MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec)); 2541 // Set the immediate. 2542 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 2543 .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine); 2544 return; 2545 } 2546 else 2547 MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI)); 2548 2549 // Set the immediate. 2550 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 2551 .addImm(LII.Imm); 2552 } 2553 2554 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI, 2555 bool &SeenIntermediateUse) const { 2556 assert(!MI.getParent()->getParent()->getRegInfo().isSSA() && 2557 "Should be called after register allocation."); 2558 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2559 MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI; 2560 It++; 2561 SeenIntermediateUse = false; 2562 for (; It != E; ++It) { 2563 if (It->modifiesRegister(Reg, TRI)) 2564 return &*It; 2565 if (It->readsRegister(Reg, TRI)) 2566 SeenIntermediateUse = true; 2567 } 2568 return nullptr; 2569 } 2570 2571 MachineInstr *PPCInstrInfo::getForwardingDefMI( 2572 MachineInstr &MI, 2573 unsigned &OpNoForForwarding, 2574 bool &SeenIntermediateUse) const { 2575 OpNoForForwarding = ~0U; 2576 MachineInstr *DefMI = nullptr; 2577 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo(); 2578 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2579 // If we're in SSA, get the defs through the MRI. Otherwise, only look 2580 // within the basic block to see if the register is defined using an 2581 // LI/LI8/ADDI/ADDI8. 2582 if (MRI->isSSA()) { 2583 for (int i = 1, e = MI.getNumOperands(); i < e; i++) { 2584 if (!MI.getOperand(i).isReg()) 2585 continue; 2586 Register Reg = MI.getOperand(i).getReg(); 2587 if (!Register::isVirtualRegister(Reg)) 2588 continue; 2589 unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI); 2590 if (Register::isVirtualRegister(TrueReg)) { 2591 DefMI = MRI->getVRegDef(TrueReg); 2592 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8 || 2593 DefMI->getOpcode() == PPC::ADDI || 2594 DefMI->getOpcode() == PPC::ADDI8) { 2595 OpNoForForwarding = i; 2596 // The ADDI and LI operand maybe exist in one instruction at same 2597 // time. we prefer to fold LI operand as LI only has one Imm operand 2598 // and is more possible to be converted. So if current DefMI is 2599 // ADDI/ADDI8, we continue to find possible LI/LI8. 2600 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) 2601 break; 2602 } 2603 } 2604 } 2605 } else { 2606 // Looking back through the definition for each operand could be expensive, 2607 // so exit early if this isn't an instruction that either has an immediate 2608 // form or is already an immediate form that we can handle. 2609 ImmInstrInfo III; 2610 unsigned Opc = MI.getOpcode(); 2611 bool ConvertibleImmForm = 2612 Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI || 2613 Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 || 2614 Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI || 2615 Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec || 2616 Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 || 2617 Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 || 2618 Opc == PPC::RLWINM8_rec; 2619 bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg()) 2620 ? isVFRegister(MI.getOperand(0).getReg()) 2621 : false; 2622 if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true)) 2623 return nullptr; 2624 2625 // Don't convert or %X, %Y, %Y since that's just a register move. 2626 if ((Opc == PPC::OR || Opc == PPC::OR8) && 2627 MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) 2628 return nullptr; 2629 for (int i = 1, e = MI.getNumOperands(); i < e; i++) { 2630 MachineOperand &MO = MI.getOperand(i); 2631 SeenIntermediateUse = false; 2632 if (MO.isReg() && MO.isUse() && !MO.isImplicit()) { 2633 Register Reg = MI.getOperand(i).getReg(); 2634 // If we see another use of this reg between the def and the MI, 2635 // we want to flat it so the def isn't deleted. 2636 MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse); 2637 if (DefMI) { 2638 // Is this register defined by some form of add-immediate (including 2639 // load-immediate) within this basic block? 2640 switch (DefMI->getOpcode()) { 2641 default: 2642 break; 2643 case PPC::LI: 2644 case PPC::LI8: 2645 case PPC::ADDItocL: 2646 case PPC::ADDI: 2647 case PPC::ADDI8: 2648 OpNoForForwarding = i; 2649 return DefMI; 2650 } 2651 } 2652 } 2653 } 2654 } 2655 return OpNoForForwarding == ~0U ? nullptr : DefMI; 2656 } 2657 2658 unsigned PPCInstrInfo::getSpillTarget() const { 2659 return Subtarget.hasP9Vector() ? 1 : 0; 2660 } 2661 2662 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const { 2663 return StoreSpillOpcodesArray[getSpillTarget()]; 2664 } 2665 2666 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const { 2667 return LoadSpillOpcodesArray[getSpillTarget()]; 2668 } 2669 2670 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI, 2671 unsigned RegNo) const { 2672 // Conservatively clear kill flag for the register if the instructions are in 2673 // different basic blocks and in SSA form, because the kill flag may no longer 2674 // be right. There is no need to bother with dead flags since defs with no 2675 // uses will be handled by DCE. 2676 MachineRegisterInfo &MRI = StartMI.getParent()->getParent()->getRegInfo(); 2677 if (MRI.isSSA() && (StartMI.getParent() != EndMI.getParent())) { 2678 MRI.clearKillFlags(RegNo); 2679 return; 2680 } 2681 2682 // Instructions between [StartMI, EndMI] should be in same basic block. 2683 assert((StartMI.getParent() == EndMI.getParent()) && 2684 "Instructions are not in same basic block"); 2685 2686 bool IsKillSet = false; 2687 2688 auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) { 2689 MachineOperand &MO = MI.getOperand(Index); 2690 if (MO.isReg() && MO.isUse() && MO.isKill() && 2691 getRegisterInfo().regsOverlap(MO.getReg(), RegNo)) 2692 MO.setIsKill(false); 2693 }; 2694 2695 // Set killed flag for EndMI. 2696 // No need to do anything if EndMI defines RegNo. 2697 int UseIndex = 2698 EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo()); 2699 if (UseIndex != -1) { 2700 EndMI.getOperand(UseIndex).setIsKill(true); 2701 IsKillSet = true; 2702 // Clear killed flag for other EndMI operands related to RegNo. In some 2703 // upexpected cases, killed may be set multiple times for same register 2704 // operand in same MI. 2705 for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i) 2706 if (i != UseIndex) 2707 clearOperandKillInfo(EndMI, i); 2708 } 2709 2710 // Walking the inst in reverse order (EndMI -> StartMI]. 2711 MachineBasicBlock::reverse_iterator It = EndMI; 2712 MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend(); 2713 // EndMI has been handled above, skip it here. 2714 It++; 2715 MachineOperand *MO = nullptr; 2716 for (; It != E; ++It) { 2717 // Skip insturctions which could not be a def/use of RegNo. 2718 if (It->isDebugInstr() || It->isPosition()) 2719 continue; 2720 2721 // Clear killed flag for all It operands related to RegNo. In some 2722 // upexpected cases, killed may be set multiple times for same register 2723 // operand in same MI. 2724 for (int i = 0, e = It->getNumOperands(); i != e; ++i) 2725 clearOperandKillInfo(*It, i); 2726 2727 // If killed is not set, set killed for its last use or set dead for its def 2728 // if no use found. 2729 if (!IsKillSet) { 2730 if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) { 2731 // Use found, set it killed. 2732 IsKillSet = true; 2733 MO->setIsKill(true); 2734 continue; 2735 } else if ((MO = It->findRegisterDefOperand(RegNo, false, true, 2736 &getRegisterInfo()))) { 2737 // No use found, set dead for its def. 2738 assert(&*It == &StartMI && "No new def between StartMI and EndMI."); 2739 MO->setIsDead(true); 2740 break; 2741 } 2742 } 2743 2744 if ((&*It) == &StartMI) 2745 break; 2746 } 2747 // Ensure RegMo liveness is killed after EndMI. 2748 assert((IsKillSet || (MO && MO->isDead())) && 2749 "RegNo should be killed or dead"); 2750 } 2751 2752 // This opt tries to convert the following imm form to an index form to save an 2753 // add for stack variables. 2754 // Return false if no such pattern found. 2755 // 2756 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi 2757 // ADD instr: ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg 2758 // Imm instr: Reg = op OffsetImm, ToBeDeletedReg(killed) 2759 // 2760 // can be converted to: 2761 // 2762 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm) 2763 // Index instr: Reg = opx ScaleReg, ToBeChangedReg(killed) 2764 // 2765 // In order to eliminate ADD instr, make sure that: 2766 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in 2767 // new ADDI instr and ADDI can only take int16 Imm. 2768 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use 2769 // between ADDI and ADD instr since its original def in ADDI will be changed 2770 // in new ADDI instr. And also there should be no new def for it between 2771 // ADD and Imm instr as ToBeChangedReg will be used in Index instr. 2772 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use 2773 // between ADD and Imm instr since ADD instr will be eliminated. 2774 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be 2775 // moved to Index instr. 2776 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const { 2777 MachineFunction *MF = MI.getParent()->getParent(); 2778 MachineRegisterInfo *MRI = &MF->getRegInfo(); 2779 bool PostRA = !MRI->isSSA(); 2780 // Do this opt after PEI which is after RA. The reason is stack slot expansion 2781 // in PEI may expose such opportunities since in PEI, stack slot offsets to 2782 // frame base(OffsetAddi) are determined. 2783 if (!PostRA) 2784 return false; 2785 unsigned ToBeDeletedReg = 0; 2786 int64_t OffsetImm = 0; 2787 unsigned XFormOpcode = 0; 2788 ImmInstrInfo III; 2789 2790 // Check if Imm instr meets requirement. 2791 if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm, 2792 III)) 2793 return false; 2794 2795 bool OtherIntermediateUse = false; 2796 MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse); 2797 2798 // Exit if there is other use between ADD and Imm instr or no def found. 2799 if (OtherIntermediateUse || !ADDMI) 2800 return false; 2801 2802 // Check if ADD instr meets requirement. 2803 if (!isADDInstrEligibleForFolding(*ADDMI)) 2804 return false; 2805 2806 unsigned ScaleRegIdx = 0; 2807 int64_t OffsetAddi = 0; 2808 MachineInstr *ADDIMI = nullptr; 2809 2810 // Check if there is a valid ToBeChangedReg in ADDMI. 2811 // 1: It must be killed. 2812 // 2: Its definition must be a valid ADDIMI. 2813 // 3: It must satify int16 offset requirement. 2814 if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm)) 2815 ScaleRegIdx = 2; 2816 else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm)) 2817 ScaleRegIdx = 1; 2818 else 2819 return false; 2820 2821 assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg."); 2822 unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg(); 2823 unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg(); 2824 auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start, 2825 MachineBasicBlock::iterator End) { 2826 for (auto It = ++Start; It != End; It++) 2827 if (It->modifiesRegister(Reg, &getRegisterInfo())) 2828 return true; 2829 return false; 2830 }; 2831 2832 // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is 2833 // treated as special zero when ScaleReg is R0/X0 register. 2834 if (III.ZeroIsSpecialOrig == III.ImmOpNo && 2835 (ScaleReg == PPC::R0 || ScaleReg == PPC::X0)) 2836 return false; 2837 2838 // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr 2839 // and Imm Instr. 2840 if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI)) 2841 return false; 2842 2843 // Now start to do the transformation. 2844 LLVM_DEBUG(dbgs() << "Replace instruction: " 2845 << "\n"); 2846 LLVM_DEBUG(ADDIMI->dump()); 2847 LLVM_DEBUG(ADDMI->dump()); 2848 LLVM_DEBUG(MI.dump()); 2849 LLVM_DEBUG(dbgs() << "with: " 2850 << "\n"); 2851 2852 // Update ADDI instr. 2853 ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm); 2854 2855 // Update Imm instr. 2856 MI.setDesc(get(XFormOpcode)); 2857 MI.getOperand(III.ImmOpNo) 2858 .ChangeToRegister(ScaleReg, false, false, 2859 ADDMI->getOperand(ScaleRegIdx).isKill()); 2860 2861 MI.getOperand(III.OpNoForForwarding) 2862 .ChangeToRegister(ToBeChangedReg, false, false, true); 2863 2864 // Eliminate ADD instr. 2865 ADDMI->eraseFromParent(); 2866 2867 LLVM_DEBUG(ADDIMI->dump()); 2868 LLVM_DEBUG(MI.dump()); 2869 2870 return true; 2871 } 2872 2873 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI, 2874 int64_t &Imm) const { 2875 unsigned Opc = ADDIMI.getOpcode(); 2876 2877 // Exit if the instruction is not ADDI. 2878 if (Opc != PPC::ADDI && Opc != PPC::ADDI8) 2879 return false; 2880 2881 // The operand may not necessarily be an immediate - it could be a relocation. 2882 if (!ADDIMI.getOperand(2).isImm()) 2883 return false; 2884 2885 Imm = ADDIMI.getOperand(2).getImm(); 2886 2887 return true; 2888 } 2889 2890 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const { 2891 unsigned Opc = ADDMI.getOpcode(); 2892 2893 // Exit if the instruction is not ADD. 2894 return Opc == PPC::ADD4 || Opc == PPC::ADD8; 2895 } 2896 2897 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI, 2898 unsigned &ToBeDeletedReg, 2899 unsigned &XFormOpcode, 2900 int64_t &OffsetImm, 2901 ImmInstrInfo &III) const { 2902 // Only handle load/store. 2903 if (!MI.mayLoadOrStore()) 2904 return false; 2905 2906 unsigned Opc = MI.getOpcode(); 2907 2908 XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc); 2909 2910 // Exit if instruction has no index form. 2911 if (XFormOpcode == PPC::INSTRUCTION_LIST_END) 2912 return false; 2913 2914 // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap. 2915 if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()), 2916 III, true)) 2917 return false; 2918 2919 if (!III.IsSummingOperands) 2920 return false; 2921 2922 MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo); 2923 MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding); 2924 // Only support imm operands, not relocation slots or others. 2925 if (!ImmOperand.isImm()) 2926 return false; 2927 2928 assert(RegOperand.isReg() && "Instruction format is not right"); 2929 2930 // There are other use for ToBeDeletedReg after Imm instr, can not delete it. 2931 if (!RegOperand.isKill()) 2932 return false; 2933 2934 ToBeDeletedReg = RegOperand.getReg(); 2935 OffsetImm = ImmOperand.getImm(); 2936 2937 return true; 2938 } 2939 2940 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index, 2941 MachineInstr *&ADDIMI, 2942 int64_t &OffsetAddi, 2943 int64_t OffsetImm) const { 2944 assert((Index == 1 || Index == 2) && "Invalid operand index for add."); 2945 MachineOperand &MO = ADDMI->getOperand(Index); 2946 2947 if (!MO.isKill()) 2948 return false; 2949 2950 bool OtherIntermediateUse = false; 2951 2952 ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse); 2953 // Currently handle only one "add + Imminstr" pair case, exit if other 2954 // intermediate use for ToBeChangedReg found. 2955 // TODO: handle the cases where there are other "add + Imminstr" pairs 2956 // with same offset in Imminstr which is like: 2957 // 2958 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi 2959 // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1 2960 // Imm instr1: Reg1 = op1 OffsetImm, ToBeDeletedReg1(killed) 2961 // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2 2962 // Imm instr2: Reg2 = op2 OffsetImm, ToBeDeletedReg2(killed) 2963 // 2964 // can be converted to: 2965 // 2966 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, 2967 // (OffsetAddi + OffsetImm) 2968 // Index instr1: Reg1 = opx1 ScaleReg1, ToBeChangedReg 2969 // Index instr2: Reg2 = opx2 ScaleReg2, ToBeChangedReg(killed) 2970 2971 if (OtherIntermediateUse || !ADDIMI) 2972 return false; 2973 // Check if ADDI instr meets requirement. 2974 if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi)) 2975 return false; 2976 2977 if (isInt<16>(OffsetAddi + OffsetImm)) 2978 return true; 2979 return false; 2980 } 2981 2982 // If this instruction has an immediate form and one of its operands is a 2983 // result of a load-immediate or an add-immediate, convert it to 2984 // the immediate form if the constant is in range. 2985 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI, 2986 MachineInstr **KilledDef) const { 2987 MachineFunction *MF = MI.getParent()->getParent(); 2988 MachineRegisterInfo *MRI = &MF->getRegInfo(); 2989 bool PostRA = !MRI->isSSA(); 2990 bool SeenIntermediateUse = true; 2991 unsigned ForwardingOperand = ~0U; 2992 MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand, 2993 SeenIntermediateUse); 2994 if (!DefMI) 2995 return false; 2996 assert(ForwardingOperand < MI.getNumOperands() && 2997 "The forwarding operand needs to be valid at this point"); 2998 bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill(); 2999 bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled; 3000 if (KilledDef && KillFwdDefMI) 3001 *KilledDef = DefMI; 3002 3003 // If this is a imm instruction and its register operands is produced by ADDI, 3004 // put the imm into imm inst directly. 3005 if (RI.getMappedIdxOpcForImmOpc(MI.getOpcode()) != 3006 PPC::INSTRUCTION_LIST_END && 3007 transformToNewImmFormFedByAdd(MI, *DefMI, ForwardingOperand)) 3008 return true; 3009 3010 ImmInstrInfo III; 3011 bool IsVFReg = MI.getOperand(0).isReg() 3012 ? isVFRegister(MI.getOperand(0).getReg()) 3013 : false; 3014 bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA); 3015 // If this is a reg+reg instruction that has a reg+imm form, 3016 // and one of the operands is produced by an add-immediate, 3017 // try to convert it. 3018 if (HasImmForm && 3019 transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI, 3020 KillFwdDefMI)) 3021 return true; 3022 3023 // If this is a reg+reg instruction that has a reg+imm form, 3024 // and one of the operands is produced by LI, convert it now. 3025 if (HasImmForm && 3026 transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI)) 3027 return true; 3028 3029 // If this is not a reg+reg, but the DefMI is LI/LI8, check if its user MI 3030 // can be simpified to LI. 3031 if (!HasImmForm && simplifyToLI(MI, *DefMI, ForwardingOperand, KilledDef)) 3032 return true; 3033 3034 return false; 3035 } 3036 3037 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg, 3038 ImmInstrInfo &III, bool PostRA) const { 3039 // The vast majority of the instructions would need their operand 2 replaced 3040 // with an immediate when switching to the reg+imm form. A marked exception 3041 // are the update form loads/stores for which a constant operand 2 would need 3042 // to turn into a displacement and move operand 1 to the operand 2 position. 3043 III.ImmOpNo = 2; 3044 III.OpNoForForwarding = 2; 3045 III.ImmWidth = 16; 3046 III.ImmMustBeMultipleOf = 1; 3047 III.TruncateImmTo = 0; 3048 III.IsSummingOperands = false; 3049 switch (Opc) { 3050 default: return false; 3051 case PPC::ADD4: 3052 case PPC::ADD8: 3053 III.SignedImm = true; 3054 III.ZeroIsSpecialOrig = 0; 3055 III.ZeroIsSpecialNew = 1; 3056 III.IsCommutative = true; 3057 III.IsSummingOperands = true; 3058 III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8; 3059 break; 3060 case PPC::ADDC: 3061 case PPC::ADDC8: 3062 III.SignedImm = true; 3063 III.ZeroIsSpecialOrig = 0; 3064 III.ZeroIsSpecialNew = 0; 3065 III.IsCommutative = true; 3066 III.IsSummingOperands = true; 3067 III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8; 3068 break; 3069 case PPC::ADDC_rec: 3070 III.SignedImm = true; 3071 III.ZeroIsSpecialOrig = 0; 3072 III.ZeroIsSpecialNew = 0; 3073 III.IsCommutative = true; 3074 III.IsSummingOperands = true; 3075 III.ImmOpcode = PPC::ADDIC_rec; 3076 break; 3077 case PPC::SUBFC: 3078 case PPC::SUBFC8: 3079 III.SignedImm = true; 3080 III.ZeroIsSpecialOrig = 0; 3081 III.ZeroIsSpecialNew = 0; 3082 III.IsCommutative = false; 3083 III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8; 3084 break; 3085 case PPC::CMPW: 3086 case PPC::CMPD: 3087 III.SignedImm = true; 3088 III.ZeroIsSpecialOrig = 0; 3089 III.ZeroIsSpecialNew = 0; 3090 III.IsCommutative = false; 3091 III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI; 3092 break; 3093 case PPC::CMPLW: 3094 case PPC::CMPLD: 3095 III.SignedImm = false; 3096 III.ZeroIsSpecialOrig = 0; 3097 III.ZeroIsSpecialNew = 0; 3098 III.IsCommutative = false; 3099 III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI; 3100 break; 3101 case PPC::AND_rec: 3102 case PPC::AND8_rec: 3103 case PPC::OR: 3104 case PPC::OR8: 3105 case PPC::XOR: 3106 case PPC::XOR8: 3107 III.SignedImm = false; 3108 III.ZeroIsSpecialOrig = 0; 3109 III.ZeroIsSpecialNew = 0; 3110 III.IsCommutative = true; 3111 switch(Opc) { 3112 default: llvm_unreachable("Unknown opcode"); 3113 case PPC::AND_rec: 3114 III.ImmOpcode = PPC::ANDI_rec; 3115 break; 3116 case PPC::AND8_rec: 3117 III.ImmOpcode = PPC::ANDI8_rec; 3118 break; 3119 case PPC::OR: III.ImmOpcode = PPC::ORI; break; 3120 case PPC::OR8: III.ImmOpcode = PPC::ORI8; break; 3121 case PPC::XOR: III.ImmOpcode = PPC::XORI; break; 3122 case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break; 3123 } 3124 break; 3125 case PPC::RLWNM: 3126 case PPC::RLWNM8: 3127 case PPC::RLWNM_rec: 3128 case PPC::RLWNM8_rec: 3129 case PPC::SLW: 3130 case PPC::SLW8: 3131 case PPC::SLW_rec: 3132 case PPC::SLW8_rec: 3133 case PPC::SRW: 3134 case PPC::SRW8: 3135 case PPC::SRW_rec: 3136 case PPC::SRW8_rec: 3137 case PPC::SRAW: 3138 case PPC::SRAW_rec: 3139 III.SignedImm = false; 3140 III.ZeroIsSpecialOrig = 0; 3141 III.ZeroIsSpecialNew = 0; 3142 III.IsCommutative = false; 3143 // This isn't actually true, but the instructions ignore any of the 3144 // upper bits, so any immediate loaded with an LI is acceptable. 3145 // This does not apply to shift right algebraic because a value 3146 // out of range will produce a -1/0. 3147 III.ImmWidth = 16; 3148 if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec || 3149 Opc == PPC::RLWNM8_rec) 3150 III.TruncateImmTo = 5; 3151 else 3152 III.TruncateImmTo = 6; 3153 switch(Opc) { 3154 default: llvm_unreachable("Unknown opcode"); 3155 case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break; 3156 case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break; 3157 case PPC::RLWNM_rec: 3158 III.ImmOpcode = PPC::RLWINM_rec; 3159 break; 3160 case PPC::RLWNM8_rec: 3161 III.ImmOpcode = PPC::RLWINM8_rec; 3162 break; 3163 case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break; 3164 case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break; 3165 case PPC::SLW_rec: 3166 III.ImmOpcode = PPC::RLWINM_rec; 3167 break; 3168 case PPC::SLW8_rec: 3169 III.ImmOpcode = PPC::RLWINM8_rec; 3170 break; 3171 case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break; 3172 case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break; 3173 case PPC::SRW_rec: 3174 III.ImmOpcode = PPC::RLWINM_rec; 3175 break; 3176 case PPC::SRW8_rec: 3177 III.ImmOpcode = PPC::RLWINM8_rec; 3178 break; 3179 case PPC::SRAW: 3180 III.ImmWidth = 5; 3181 III.TruncateImmTo = 0; 3182 III.ImmOpcode = PPC::SRAWI; 3183 break; 3184 case PPC::SRAW_rec: 3185 III.ImmWidth = 5; 3186 III.TruncateImmTo = 0; 3187 III.ImmOpcode = PPC::SRAWI_rec; 3188 break; 3189 } 3190 break; 3191 case PPC::RLDCL: 3192 case PPC::RLDCL_rec: 3193 case PPC::RLDCR: 3194 case PPC::RLDCR_rec: 3195 case PPC::SLD: 3196 case PPC::SLD_rec: 3197 case PPC::SRD: 3198 case PPC::SRD_rec: 3199 case PPC::SRAD: 3200 case PPC::SRAD_rec: 3201 III.SignedImm = false; 3202 III.ZeroIsSpecialOrig = 0; 3203 III.ZeroIsSpecialNew = 0; 3204 III.IsCommutative = false; 3205 // This isn't actually true, but the instructions ignore any of the 3206 // upper bits, so any immediate loaded with an LI is acceptable. 3207 // This does not apply to shift right algebraic because a value 3208 // out of range will produce a -1/0. 3209 III.ImmWidth = 16; 3210 if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR || 3211 Opc == PPC::RLDCR_rec) 3212 III.TruncateImmTo = 6; 3213 else 3214 III.TruncateImmTo = 7; 3215 switch(Opc) { 3216 default: llvm_unreachable("Unknown opcode"); 3217 case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break; 3218 case PPC::RLDCL_rec: 3219 III.ImmOpcode = PPC::RLDICL_rec; 3220 break; 3221 case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break; 3222 case PPC::RLDCR_rec: 3223 III.ImmOpcode = PPC::RLDICR_rec; 3224 break; 3225 case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break; 3226 case PPC::SLD_rec: 3227 III.ImmOpcode = PPC::RLDICR_rec; 3228 break; 3229 case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break; 3230 case PPC::SRD_rec: 3231 III.ImmOpcode = PPC::RLDICL_rec; 3232 break; 3233 case PPC::SRAD: 3234 III.ImmWidth = 6; 3235 III.TruncateImmTo = 0; 3236 III.ImmOpcode = PPC::SRADI; 3237 break; 3238 case PPC::SRAD_rec: 3239 III.ImmWidth = 6; 3240 III.TruncateImmTo = 0; 3241 III.ImmOpcode = PPC::SRADI_rec; 3242 break; 3243 } 3244 break; 3245 // Loads and stores: 3246 case PPC::LBZX: 3247 case PPC::LBZX8: 3248 case PPC::LHZX: 3249 case PPC::LHZX8: 3250 case PPC::LHAX: 3251 case PPC::LHAX8: 3252 case PPC::LWZX: 3253 case PPC::LWZX8: 3254 case PPC::LWAX: 3255 case PPC::LDX: 3256 case PPC::LFSX: 3257 case PPC::LFDX: 3258 case PPC::STBX: 3259 case PPC::STBX8: 3260 case PPC::STHX: 3261 case PPC::STHX8: 3262 case PPC::STWX: 3263 case PPC::STWX8: 3264 case PPC::STDX: 3265 case PPC::STFSX: 3266 case PPC::STFDX: 3267 III.SignedImm = true; 3268 III.ZeroIsSpecialOrig = 1; 3269 III.ZeroIsSpecialNew = 2; 3270 III.IsCommutative = true; 3271 III.IsSummingOperands = true; 3272 III.ImmOpNo = 1; 3273 III.OpNoForForwarding = 2; 3274 switch(Opc) { 3275 default: llvm_unreachable("Unknown opcode"); 3276 case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break; 3277 case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break; 3278 case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break; 3279 case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break; 3280 case PPC::LHAX: III.ImmOpcode = PPC::LHA; break; 3281 case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break; 3282 case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break; 3283 case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break; 3284 case PPC::LWAX: 3285 III.ImmOpcode = PPC::LWA; 3286 III.ImmMustBeMultipleOf = 4; 3287 break; 3288 case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break; 3289 case PPC::LFSX: III.ImmOpcode = PPC::LFS; break; 3290 case PPC::LFDX: III.ImmOpcode = PPC::LFD; break; 3291 case PPC::STBX: III.ImmOpcode = PPC::STB; break; 3292 case PPC::STBX8: III.ImmOpcode = PPC::STB8; break; 3293 case PPC::STHX: III.ImmOpcode = PPC::STH; break; 3294 case PPC::STHX8: III.ImmOpcode = PPC::STH8; break; 3295 case PPC::STWX: III.ImmOpcode = PPC::STW; break; 3296 case PPC::STWX8: III.ImmOpcode = PPC::STW8; break; 3297 case PPC::STDX: 3298 III.ImmOpcode = PPC::STD; 3299 III.ImmMustBeMultipleOf = 4; 3300 break; 3301 case PPC::STFSX: III.ImmOpcode = PPC::STFS; break; 3302 case PPC::STFDX: III.ImmOpcode = PPC::STFD; break; 3303 } 3304 break; 3305 case PPC::LBZUX: 3306 case PPC::LBZUX8: 3307 case PPC::LHZUX: 3308 case PPC::LHZUX8: 3309 case PPC::LHAUX: 3310 case PPC::LHAUX8: 3311 case PPC::LWZUX: 3312 case PPC::LWZUX8: 3313 case PPC::LDUX: 3314 case PPC::LFSUX: 3315 case PPC::LFDUX: 3316 case PPC::STBUX: 3317 case PPC::STBUX8: 3318 case PPC::STHUX: 3319 case PPC::STHUX8: 3320 case PPC::STWUX: 3321 case PPC::STWUX8: 3322 case PPC::STDUX: 3323 case PPC::STFSUX: 3324 case PPC::STFDUX: 3325 III.SignedImm = true; 3326 III.ZeroIsSpecialOrig = 2; 3327 III.ZeroIsSpecialNew = 3; 3328 III.IsCommutative = false; 3329 III.IsSummingOperands = true; 3330 III.ImmOpNo = 2; 3331 III.OpNoForForwarding = 3; 3332 switch(Opc) { 3333 default: llvm_unreachable("Unknown opcode"); 3334 case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break; 3335 case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break; 3336 case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break; 3337 case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break; 3338 case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break; 3339 case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break; 3340 case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break; 3341 case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break; 3342 case PPC::LDUX: 3343 III.ImmOpcode = PPC::LDU; 3344 III.ImmMustBeMultipleOf = 4; 3345 break; 3346 case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break; 3347 case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break; 3348 case PPC::STBUX: III.ImmOpcode = PPC::STBU; break; 3349 case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break; 3350 case PPC::STHUX: III.ImmOpcode = PPC::STHU; break; 3351 case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break; 3352 case PPC::STWUX: III.ImmOpcode = PPC::STWU; break; 3353 case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break; 3354 case PPC::STDUX: 3355 III.ImmOpcode = PPC::STDU; 3356 III.ImmMustBeMultipleOf = 4; 3357 break; 3358 case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break; 3359 case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break; 3360 } 3361 break; 3362 // Power9 and up only. For some of these, the X-Form version has access to all 3363 // 64 VSR's whereas the D-Form only has access to the VR's. We replace those 3364 // with pseudo-ops pre-ra and for post-ra, we check that the register loaded 3365 // into or stored from is one of the VR registers. 3366 case PPC::LXVX: 3367 case PPC::LXSSPX: 3368 case PPC::LXSDX: 3369 case PPC::STXVX: 3370 case PPC::STXSSPX: 3371 case PPC::STXSDX: 3372 case PPC::XFLOADf32: 3373 case PPC::XFLOADf64: 3374 case PPC::XFSTOREf32: 3375 case PPC::XFSTOREf64: 3376 if (!Subtarget.hasP9Vector()) 3377 return false; 3378 III.SignedImm = true; 3379 III.ZeroIsSpecialOrig = 1; 3380 III.ZeroIsSpecialNew = 2; 3381 III.IsCommutative = true; 3382 III.IsSummingOperands = true; 3383 III.ImmOpNo = 1; 3384 III.OpNoForForwarding = 2; 3385 III.ImmMustBeMultipleOf = 4; 3386 switch(Opc) { 3387 default: llvm_unreachable("Unknown opcode"); 3388 case PPC::LXVX: 3389 III.ImmOpcode = PPC::LXV; 3390 III.ImmMustBeMultipleOf = 16; 3391 break; 3392 case PPC::LXSSPX: 3393 if (PostRA) { 3394 if (IsVFReg) 3395 III.ImmOpcode = PPC::LXSSP; 3396 else { 3397 III.ImmOpcode = PPC::LFS; 3398 III.ImmMustBeMultipleOf = 1; 3399 } 3400 break; 3401 } 3402 LLVM_FALLTHROUGH; 3403 case PPC::XFLOADf32: 3404 III.ImmOpcode = PPC::DFLOADf32; 3405 break; 3406 case PPC::LXSDX: 3407 if (PostRA) { 3408 if (IsVFReg) 3409 III.ImmOpcode = PPC::LXSD; 3410 else { 3411 III.ImmOpcode = PPC::LFD; 3412 III.ImmMustBeMultipleOf = 1; 3413 } 3414 break; 3415 } 3416 LLVM_FALLTHROUGH; 3417 case PPC::XFLOADf64: 3418 III.ImmOpcode = PPC::DFLOADf64; 3419 break; 3420 case PPC::STXVX: 3421 III.ImmOpcode = PPC::STXV; 3422 III.ImmMustBeMultipleOf = 16; 3423 break; 3424 case PPC::STXSSPX: 3425 if (PostRA) { 3426 if (IsVFReg) 3427 III.ImmOpcode = PPC::STXSSP; 3428 else { 3429 III.ImmOpcode = PPC::STFS; 3430 III.ImmMustBeMultipleOf = 1; 3431 } 3432 break; 3433 } 3434 LLVM_FALLTHROUGH; 3435 case PPC::XFSTOREf32: 3436 III.ImmOpcode = PPC::DFSTOREf32; 3437 break; 3438 case PPC::STXSDX: 3439 if (PostRA) { 3440 if (IsVFReg) 3441 III.ImmOpcode = PPC::STXSD; 3442 else { 3443 III.ImmOpcode = PPC::STFD; 3444 III.ImmMustBeMultipleOf = 1; 3445 } 3446 break; 3447 } 3448 LLVM_FALLTHROUGH; 3449 case PPC::XFSTOREf64: 3450 III.ImmOpcode = PPC::DFSTOREf64; 3451 break; 3452 } 3453 break; 3454 } 3455 return true; 3456 } 3457 3458 // Utility function for swaping two arbitrary operands of an instruction. 3459 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) { 3460 assert(Op1 != Op2 && "Cannot swap operand with itself."); 3461 3462 unsigned MaxOp = std::max(Op1, Op2); 3463 unsigned MinOp = std::min(Op1, Op2); 3464 MachineOperand MOp1 = MI.getOperand(MinOp); 3465 MachineOperand MOp2 = MI.getOperand(MaxOp); 3466 MI.RemoveOperand(std::max(Op1, Op2)); 3467 MI.RemoveOperand(std::min(Op1, Op2)); 3468 3469 // If the operands we are swapping are the two at the end (the common case) 3470 // we can just remove both and add them in the opposite order. 3471 if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) { 3472 MI.addOperand(MOp2); 3473 MI.addOperand(MOp1); 3474 } else { 3475 // Store all operands in a temporary vector, remove them and re-add in the 3476 // right order. 3477 SmallVector<MachineOperand, 2> MOps; 3478 unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops. 3479 for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) { 3480 MOps.push_back(MI.getOperand(i)); 3481 MI.RemoveOperand(i); 3482 } 3483 // MOp2 needs to be added next. 3484 MI.addOperand(MOp2); 3485 // Now add the rest. 3486 for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) { 3487 if (i == MaxOp) 3488 MI.addOperand(MOp1); 3489 else { 3490 MI.addOperand(MOps.back()); 3491 MOps.pop_back(); 3492 } 3493 } 3494 } 3495 } 3496 3497 // Check if the 'MI' that has the index OpNoForForwarding 3498 // meets the requirement described in the ImmInstrInfo. 3499 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI, 3500 const ImmInstrInfo &III, 3501 unsigned OpNoForForwarding 3502 ) const { 3503 // As the algorithm of checking for PPC::ZERO/PPC::ZERO8 3504 // would not work pre-RA, we can only do the check post RA. 3505 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3506 if (MRI.isSSA()) 3507 return false; 3508 3509 // Cannot do the transform if MI isn't summing the operands. 3510 if (!III.IsSummingOperands) 3511 return false; 3512 3513 // The instruction we are trying to replace must have the ZeroIsSpecialOrig set. 3514 if (!III.ZeroIsSpecialOrig) 3515 return false; 3516 3517 // We cannot do the transform if the operand we are trying to replace 3518 // isn't the same as the operand the instruction allows. 3519 if (OpNoForForwarding != III.OpNoForForwarding) 3520 return false; 3521 3522 // Check if the instruction we are trying to transform really has 3523 // the special zero register as its operand. 3524 if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO && 3525 MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8) 3526 return false; 3527 3528 // This machine instruction is convertible if it is, 3529 // 1. summing the operands. 3530 // 2. one of the operands is special zero register. 3531 // 3. the operand we are trying to replace is allowed by the MI. 3532 return true; 3533 } 3534 3535 // Check if the DefMI is the add inst and set the ImmMO and RegMO 3536 // accordingly. 3537 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI, 3538 const ImmInstrInfo &III, 3539 MachineOperand *&ImmMO, 3540 MachineOperand *&RegMO) const { 3541 unsigned Opc = DefMI.getOpcode(); 3542 if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8) 3543 return false; 3544 3545 assert(DefMI.getNumOperands() >= 3 && 3546 "Add inst must have at least three operands"); 3547 RegMO = &DefMI.getOperand(1); 3548 ImmMO = &DefMI.getOperand(2); 3549 3550 // Before RA, ADDI first operand could be a frame index. 3551 if (!RegMO->isReg()) 3552 return false; 3553 3554 // This DefMI is elgible for forwarding if it is: 3555 // 1. add inst 3556 // 2. one of the operands is Imm/CPI/Global. 3557 return isAnImmediateOperand(*ImmMO); 3558 } 3559 3560 bool PPCInstrInfo::isRegElgibleForForwarding( 3561 const MachineOperand &RegMO, const MachineInstr &DefMI, 3562 const MachineInstr &MI, bool KillDefMI, 3563 bool &IsFwdFeederRegKilled) const { 3564 // x = addi y, imm 3565 // ... 3566 // z = lfdx 0, x -> z = lfd imm(y) 3567 // The Reg "y" can be forwarded to the MI(z) only when there is no DEF 3568 // of "y" between the DEF of "x" and "z". 3569 // The query is only valid post RA. 3570 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3571 if (MRI.isSSA()) 3572 return false; 3573 3574 Register Reg = RegMO.getReg(); 3575 3576 // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg. 3577 MachineBasicBlock::const_reverse_iterator It = MI; 3578 MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend(); 3579 It++; 3580 for (; It != E; ++It) { 3581 if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI) 3582 return false; 3583 else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI) 3584 IsFwdFeederRegKilled = true; 3585 // Made it to DefMI without encountering a clobber. 3586 if ((&*It) == &DefMI) 3587 break; 3588 } 3589 assert((&*It) == &DefMI && "DefMI is missing"); 3590 3591 // If DefMI also defines the register to be forwarded, we can only forward it 3592 // if DefMI is being erased. 3593 if (DefMI.modifiesRegister(Reg, &getRegisterInfo())) 3594 return KillDefMI; 3595 3596 return true; 3597 } 3598 3599 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO, 3600 const MachineInstr &DefMI, 3601 const ImmInstrInfo &III, 3602 int64_t &Imm, 3603 int64_t BaseImm) const { 3604 assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate"); 3605 if (DefMI.getOpcode() == PPC::ADDItocL) { 3606 // The operand for ADDItocL is CPI, which isn't imm at compiling time, 3607 // However, we know that, it is 16-bit width, and has the alignment of 4. 3608 // Check if the instruction met the requirement. 3609 if (III.ImmMustBeMultipleOf > 4 || 3610 III.TruncateImmTo || III.ImmWidth != 16) 3611 return false; 3612 3613 // Going from XForm to DForm loads means that the displacement needs to be 3614 // not just an immediate but also a multiple of 4, or 16 depending on the 3615 // load. A DForm load cannot be represented if it is a multiple of say 2. 3616 // XForm loads do not have this restriction. 3617 if (ImmMO.isGlobal()) { 3618 const DataLayout &DL = ImmMO.getGlobal()->getParent()->getDataLayout(); 3619 if (ImmMO.getGlobal()->getPointerAlignment(DL) < III.ImmMustBeMultipleOf) 3620 return false; 3621 } 3622 3623 return true; 3624 } 3625 3626 if (ImmMO.isImm()) { 3627 // It is Imm, we need to check if the Imm fit the range. 3628 // Sign-extend to 64-bits. 3629 // DefMI may be folded with another imm form instruction, the result Imm is 3630 // the sum of Imm of DefMI and BaseImm which is from imm form instruction. 3631 Imm = SignExtend64<16>(ImmMO.getImm() + BaseImm); 3632 3633 if (Imm % III.ImmMustBeMultipleOf) 3634 return false; 3635 if (III.TruncateImmTo) 3636 Imm &= ((1 << III.TruncateImmTo) - 1); 3637 if (III.SignedImm) { 3638 APInt ActualValue(64, Imm, true); 3639 if (!ActualValue.isSignedIntN(III.ImmWidth)) 3640 return false; 3641 } else { 3642 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1; 3643 if ((uint64_t)Imm > UnsignedMax) 3644 return false; 3645 } 3646 } 3647 else 3648 return false; 3649 3650 // This ImmMO is forwarded if it meets the requriement describle 3651 // in ImmInstrInfo 3652 return true; 3653 } 3654 3655 bool PPCInstrInfo::simplifyToLI(MachineInstr &MI, MachineInstr &DefMI, 3656 unsigned OpNoForForwarding, 3657 MachineInstr **KilledDef) const { 3658 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) || 3659 !DefMI.getOperand(1).isImm()) 3660 return false; 3661 3662 MachineFunction *MF = MI.getParent()->getParent(); 3663 MachineRegisterInfo *MRI = &MF->getRegInfo(); 3664 bool PostRA = !MRI->isSSA(); 3665 3666 int64_t Immediate = DefMI.getOperand(1).getImm(); 3667 // Sign-extend to 64-bits. 3668 int64_t SExtImm = SignExtend64<16>(Immediate); 3669 3670 bool IsForwardingOperandKilled = MI.getOperand(OpNoForForwarding).isKill(); 3671 Register ForwardingOperandReg = MI.getOperand(OpNoForForwarding).getReg(); 3672 3673 bool ReplaceWithLI = false; 3674 bool Is64BitLI = false; 3675 int64_t NewImm = 0; 3676 bool SetCR = false; 3677 unsigned Opc = MI.getOpcode(); 3678 switch (Opc) { 3679 default: 3680 return false; 3681 3682 // FIXME: Any branches conditional on such a comparison can be made 3683 // unconditional. At this time, this happens too infrequently to be worth 3684 // the implementation effort, but if that ever changes, we could convert 3685 // such a pattern here. 3686 case PPC::CMPWI: 3687 case PPC::CMPLWI: 3688 case PPC::CMPDI: 3689 case PPC::CMPLDI: { 3690 // Doing this post-RA would require dataflow analysis to reliably find uses 3691 // of the CR register set by the compare. 3692 // No need to fixup killed/dead flag since this transformation is only valid 3693 // before RA. 3694 if (PostRA) 3695 return false; 3696 // If a compare-immediate is fed by an immediate and is itself an input of 3697 // an ISEL (the most common case) into a COPY of the correct register. 3698 bool Changed = false; 3699 Register DefReg = MI.getOperand(0).getReg(); 3700 int64_t Comparand = MI.getOperand(2).getImm(); 3701 int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 3702 ? (Comparand | 0xFFFFFFFFFFFF0000) 3703 : Comparand; 3704 3705 for (auto &CompareUseMI : MRI->use_instructions(DefReg)) { 3706 unsigned UseOpc = CompareUseMI.getOpcode(); 3707 if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8) 3708 continue; 3709 unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg(); 3710 Register TrueReg = CompareUseMI.getOperand(1).getReg(); 3711 Register FalseReg = CompareUseMI.getOperand(2).getReg(); 3712 unsigned RegToCopy = 3713 selectReg(SExtImm, SExtComparand, Opc, TrueReg, FalseReg, CRSubReg); 3714 if (RegToCopy == PPC::NoRegister) 3715 continue; 3716 // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0. 3717 if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) { 3718 CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI)); 3719 replaceInstrOperandWithImm(CompareUseMI, 1, 0); 3720 CompareUseMI.RemoveOperand(3); 3721 CompareUseMI.RemoveOperand(2); 3722 continue; 3723 } 3724 LLVM_DEBUG( 3725 dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n"); 3726 LLVM_DEBUG(DefMI.dump(); MI.dump(); CompareUseMI.dump()); 3727 LLVM_DEBUG(dbgs() << "Is converted to:\n"); 3728 // Convert to copy and remove unneeded operands. 3729 CompareUseMI.setDesc(get(PPC::COPY)); 3730 CompareUseMI.RemoveOperand(3); 3731 CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1); 3732 CmpIselsConverted++; 3733 Changed = true; 3734 LLVM_DEBUG(CompareUseMI.dump()); 3735 } 3736 if (Changed) 3737 return true; 3738 // This may end up incremented multiple times since this function is called 3739 // during a fixed-point transformation, but it is only meant to indicate the 3740 // presence of this opportunity. 3741 MissedConvertibleImmediateInstrs++; 3742 return false; 3743 } 3744 3745 // Immediate forms - may simply be convertable to an LI. 3746 case PPC::ADDI: 3747 case PPC::ADDI8: { 3748 // Does the sum fit in a 16-bit signed field? 3749 int64_t Addend = MI.getOperand(2).getImm(); 3750 if (isInt<16>(Addend + SExtImm)) { 3751 ReplaceWithLI = true; 3752 Is64BitLI = Opc == PPC::ADDI8; 3753 NewImm = Addend + SExtImm; 3754 break; 3755 } 3756 return false; 3757 } 3758 case PPC::RLDICL: 3759 case PPC::RLDICL_rec: 3760 case PPC::RLDICL_32: 3761 case PPC::RLDICL_32_64: { 3762 // Use APInt's rotate function. 3763 int64_t SH = MI.getOperand(2).getImm(); 3764 int64_t MB = MI.getOperand(3).getImm(); 3765 APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32, 3766 SExtImm, true); 3767 InVal = InVal.rotl(SH); 3768 uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1; 3769 InVal &= Mask; 3770 // Can't replace negative values with an LI as that will sign-extend 3771 // and not clear the left bits. If we're setting the CR bit, we will use 3772 // ANDI_rec which won't sign extend, so that's safe. 3773 if (isUInt<15>(InVal.getSExtValue()) || 3774 (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) { 3775 ReplaceWithLI = true; 3776 Is64BitLI = Opc != PPC::RLDICL_32; 3777 NewImm = InVal.getSExtValue(); 3778 SetCR = Opc == PPC::RLDICL_rec; 3779 break; 3780 } 3781 return false; 3782 } 3783 case PPC::RLWINM: 3784 case PPC::RLWINM8: 3785 case PPC::RLWINM_rec: 3786 case PPC::RLWINM8_rec: { 3787 int64_t SH = MI.getOperand(2).getImm(); 3788 int64_t MB = MI.getOperand(3).getImm(); 3789 int64_t ME = MI.getOperand(4).getImm(); 3790 APInt InVal(32, SExtImm, true); 3791 InVal = InVal.rotl(SH); 3792 APInt Mask = APInt::getBitsSetWithWrap(32, 32 - ME - 1, 32 - MB); 3793 InVal &= Mask; 3794 // Can't replace negative values with an LI as that will sign-extend 3795 // and not clear the left bits. If we're setting the CR bit, we will use 3796 // ANDI_rec which won't sign extend, so that's safe. 3797 bool ValueFits = isUInt<15>(InVal.getSExtValue()); 3798 ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) && 3799 isUInt<16>(InVal.getSExtValue())); 3800 if (ValueFits) { 3801 ReplaceWithLI = true; 3802 Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec; 3803 NewImm = InVal.getSExtValue(); 3804 SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec; 3805 break; 3806 } 3807 return false; 3808 } 3809 case PPC::ORI: 3810 case PPC::ORI8: 3811 case PPC::XORI: 3812 case PPC::XORI8: { 3813 int64_t LogicalImm = MI.getOperand(2).getImm(); 3814 int64_t Result = 0; 3815 if (Opc == PPC::ORI || Opc == PPC::ORI8) 3816 Result = LogicalImm | SExtImm; 3817 else 3818 Result = LogicalImm ^ SExtImm; 3819 if (isInt<16>(Result)) { 3820 ReplaceWithLI = true; 3821 Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8; 3822 NewImm = Result; 3823 break; 3824 } 3825 return false; 3826 } 3827 } 3828 3829 if (ReplaceWithLI) { 3830 // We need to be careful with CR-setting instructions we're replacing. 3831 if (SetCR) { 3832 // We don't know anything about uses when we're out of SSA, so only 3833 // replace if the new immediate will be reproduced. 3834 bool ImmChanged = (SExtImm & NewImm) != NewImm; 3835 if (PostRA && ImmChanged) 3836 return false; 3837 3838 if (!PostRA) { 3839 // If the defining load-immediate has no other uses, we can just replace 3840 // the immediate with the new immediate. 3841 if (MRI->hasOneUse(DefMI.getOperand(0).getReg())) 3842 DefMI.getOperand(1).setImm(NewImm); 3843 3844 // If we're not using the GPR result of the CR-setting instruction, we 3845 // just need to and with zero/non-zero depending on the new immediate. 3846 else if (MRI->use_empty(MI.getOperand(0).getReg())) { 3847 if (NewImm) { 3848 assert(Immediate && "Transformation converted zero to non-zero?"); 3849 NewImm = Immediate; 3850 } 3851 } else if (ImmChanged) 3852 return false; 3853 } 3854 } 3855 3856 LLVM_DEBUG(dbgs() << "Replacing instruction:\n"); 3857 LLVM_DEBUG(MI.dump()); 3858 LLVM_DEBUG(dbgs() << "Fed by:\n"); 3859 LLVM_DEBUG(DefMI.dump()); 3860 LoadImmediateInfo LII; 3861 LII.Imm = NewImm; 3862 LII.Is64Bit = Is64BitLI; 3863 LII.SetCR = SetCR; 3864 // If we're setting the CR, the original load-immediate must be kept (as an 3865 // operand to ANDI_rec/ANDI8_rec). 3866 if (KilledDef && SetCR) 3867 *KilledDef = nullptr; 3868 replaceInstrWithLI(MI, LII); 3869 3870 // Fixup killed/dead flag after transformation. 3871 // Pattern: 3872 // ForwardingOperandReg = LI imm1 3873 // y = op2 imm2, ForwardingOperandReg(killed) 3874 if (IsForwardingOperandKilled) 3875 fixupIsDeadOrKill(DefMI, MI, ForwardingOperandReg); 3876 3877 LLVM_DEBUG(dbgs() << "With:\n"); 3878 LLVM_DEBUG(MI.dump()); 3879 return true; 3880 } 3881 return false; 3882 } 3883 3884 bool PPCInstrInfo::transformToNewImmFormFedByAdd( 3885 MachineInstr &MI, MachineInstr &DefMI, unsigned OpNoForForwarding) const { 3886 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo(); 3887 bool PostRA = !MRI->isSSA(); 3888 // FIXME: extend this to post-ra. Need to do some change in getForwardingDefMI 3889 // for post-ra. 3890 if (PostRA) 3891 return false; 3892 3893 // Only handle load/store. 3894 if (!MI.mayLoadOrStore()) 3895 return false; 3896 3897 unsigned XFormOpcode = RI.getMappedIdxOpcForImmOpc(MI.getOpcode()); 3898 3899 assert((XFormOpcode != PPC::INSTRUCTION_LIST_END) && 3900 "MI must have x-form opcode"); 3901 3902 // get Imm Form info. 3903 ImmInstrInfo III; 3904 bool IsVFReg = MI.getOperand(0).isReg() 3905 ? isVFRegister(MI.getOperand(0).getReg()) 3906 : false; 3907 3908 if (!instrHasImmForm(XFormOpcode, IsVFReg, III, PostRA)) 3909 return false; 3910 3911 if (!III.IsSummingOperands) 3912 return false; 3913 3914 if (OpNoForForwarding != III.OpNoForForwarding) 3915 return false; 3916 3917 MachineOperand ImmOperandMI = MI.getOperand(III.ImmOpNo); 3918 if (!ImmOperandMI.isImm()) 3919 return false; 3920 3921 // Check DefMI. 3922 MachineOperand *ImmMO = nullptr; 3923 MachineOperand *RegMO = nullptr; 3924 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO)) 3925 return false; 3926 assert(ImmMO && RegMO && "Imm and Reg operand must have been set"); 3927 3928 // Check Imm. 3929 // Set ImmBase from imm instruction as base and get new Imm inside 3930 // isImmElgibleForForwarding. 3931 int64_t ImmBase = ImmOperandMI.getImm(); 3932 int64_t Imm = 0; 3933 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm, ImmBase)) 3934 return false; 3935 3936 // Get killed info in case fixup needed after transformation. 3937 unsigned ForwardKilledOperandReg = ~0U; 3938 if (MI.getOperand(III.OpNoForForwarding).isKill()) 3939 ForwardKilledOperandReg = MI.getOperand(III.OpNoForForwarding).getReg(); 3940 3941 // Do the transform 3942 LLVM_DEBUG(dbgs() << "Replacing instruction:\n"); 3943 LLVM_DEBUG(MI.dump()); 3944 LLVM_DEBUG(dbgs() << "Fed by:\n"); 3945 LLVM_DEBUG(DefMI.dump()); 3946 3947 MI.getOperand(III.OpNoForForwarding).setReg(RegMO->getReg()); 3948 MI.getOperand(III.OpNoForForwarding).setIsKill(RegMO->isKill()); 3949 MI.getOperand(III.ImmOpNo).setImm(Imm); 3950 3951 // FIXME: fix kill/dead flag if MI and DefMI are not in same basic block. 3952 if (DefMI.getParent() == MI.getParent()) { 3953 // Check if reg is killed between MI and DefMI. 3954 auto IsKilledFor = [&](unsigned Reg) { 3955 MachineBasicBlock::const_reverse_iterator It = MI; 3956 MachineBasicBlock::const_reverse_iterator E = DefMI; 3957 It++; 3958 for (; It != E; ++It) { 3959 if (It->killsRegister(Reg)) 3960 return true; 3961 } 3962 return false; 3963 }; 3964 3965 // Update kill flag 3966 if (RegMO->isKill() || IsKilledFor(RegMO->getReg())) 3967 fixupIsDeadOrKill(DefMI, MI, RegMO->getReg()); 3968 if (ForwardKilledOperandReg != ~0U) 3969 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg); 3970 } 3971 3972 LLVM_DEBUG(dbgs() << "With:\n"); 3973 LLVM_DEBUG(MI.dump()); 3974 return true; 3975 } 3976 3977 // If an X-Form instruction is fed by an add-immediate and one of its operands 3978 // is the literal zero, attempt to forward the source of the add-immediate to 3979 // the corresponding D-Form instruction with the displacement coming from 3980 // the immediate being added. 3981 bool PPCInstrInfo::transformToImmFormFedByAdd( 3982 MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding, 3983 MachineInstr &DefMI, bool KillDefMI) const { 3984 // RegMO ImmMO 3985 // | | 3986 // x = addi reg, imm <----- DefMI 3987 // y = op 0 , x <----- MI 3988 // | 3989 // OpNoForForwarding 3990 // Check if the MI meet the requirement described in the III. 3991 if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding)) 3992 return false; 3993 3994 // Check if the DefMI meet the requirement 3995 // described in the III. If yes, set the ImmMO and RegMO accordingly. 3996 MachineOperand *ImmMO = nullptr; 3997 MachineOperand *RegMO = nullptr; 3998 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO)) 3999 return false; 4000 assert(ImmMO && RegMO && "Imm and Reg operand must have been set"); 4001 4002 // As we get the Imm operand now, we need to check if the ImmMO meet 4003 // the requirement described in the III. If yes set the Imm. 4004 int64_t Imm = 0; 4005 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm)) 4006 return false; 4007 4008 bool IsFwdFeederRegKilled = false; 4009 // Check if the RegMO can be forwarded to MI. 4010 if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI, 4011 IsFwdFeederRegKilled)) 4012 return false; 4013 4014 // Get killed info in case fixup needed after transformation. 4015 unsigned ForwardKilledOperandReg = ~0U; 4016 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 4017 bool PostRA = !MRI.isSSA(); 4018 if (PostRA && MI.getOperand(OpNoForForwarding).isKill()) 4019 ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg(); 4020 4021 // We know that, the MI and DefMI both meet the pattern, and 4022 // the Imm also meet the requirement with the new Imm-form. 4023 // It is safe to do the transformation now. 4024 LLVM_DEBUG(dbgs() << "Replacing instruction:\n"); 4025 LLVM_DEBUG(MI.dump()); 4026 LLVM_DEBUG(dbgs() << "Fed by:\n"); 4027 LLVM_DEBUG(DefMI.dump()); 4028 4029 // Update the base reg first. 4030 MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(), 4031 false, false, 4032 RegMO->isKill()); 4033 4034 // Then, update the imm. 4035 if (ImmMO->isImm()) { 4036 // If the ImmMO is Imm, change the operand that has ZERO to that Imm 4037 // directly. 4038 replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm); 4039 } 4040 else { 4041 // Otherwise, it is Constant Pool Index(CPI) or Global, 4042 // which is relocation in fact. We need to replace the special zero 4043 // register with ImmMO. 4044 // Before that, we need to fixup the target flags for imm. 4045 // For some reason, we miss to set the flag for the ImmMO if it is CPI. 4046 if (DefMI.getOpcode() == PPC::ADDItocL) 4047 ImmMO->setTargetFlags(PPCII::MO_TOC_LO); 4048 4049 // MI didn't have the interface such as MI.setOperand(i) though 4050 // it has MI.getOperand(i). To repalce the ZERO MachineOperand with 4051 // ImmMO, we need to remove ZERO operand and all the operands behind it, 4052 // and, add the ImmMO, then, move back all the operands behind ZERO. 4053 SmallVector<MachineOperand, 2> MOps; 4054 for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) { 4055 MOps.push_back(MI.getOperand(i)); 4056 MI.RemoveOperand(i); 4057 } 4058 4059 // Remove the last MO in the list, which is ZERO operand in fact. 4060 MOps.pop_back(); 4061 // Add the imm operand. 4062 MI.addOperand(*ImmMO); 4063 // Now add the rest back. 4064 for (auto &MO : MOps) 4065 MI.addOperand(MO); 4066 } 4067 4068 // Update the opcode. 4069 MI.setDesc(get(III.ImmOpcode)); 4070 4071 // Fix up killed/dead flag after transformation. 4072 // Pattern 1: 4073 // x = ADD KilledFwdFeederReg, imm 4074 // n = opn KilledFwdFeederReg(killed), regn 4075 // y = XOP 0, x 4076 // Pattern 2: 4077 // x = ADD reg(killed), imm 4078 // y = XOP 0, x 4079 if (IsFwdFeederRegKilled || RegMO->isKill()) 4080 fixupIsDeadOrKill(DefMI, MI, RegMO->getReg()); 4081 // Pattern 3: 4082 // ForwardKilledOperandReg = ADD reg, imm 4083 // y = XOP 0, ForwardKilledOperandReg(killed) 4084 if (ForwardKilledOperandReg != ~0U) 4085 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg); 4086 4087 LLVM_DEBUG(dbgs() << "With:\n"); 4088 LLVM_DEBUG(MI.dump()); 4089 4090 return true; 4091 } 4092 4093 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI, 4094 const ImmInstrInfo &III, 4095 unsigned ConstantOpNo, 4096 MachineInstr &DefMI) const { 4097 // DefMI must be LI or LI8. 4098 if ((DefMI.getOpcode() != PPC::LI && DefMI.getOpcode() != PPC::LI8) || 4099 !DefMI.getOperand(1).isImm()) 4100 return false; 4101 4102 // Get Imm operand and Sign-extend to 64-bits. 4103 int64_t Imm = SignExtend64<16>(DefMI.getOperand(1).getImm()); 4104 4105 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 4106 bool PostRA = !MRI.isSSA(); 4107 // Exit early if we can't convert this. 4108 if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative) 4109 return false; 4110 if (Imm % III.ImmMustBeMultipleOf) 4111 return false; 4112 if (III.TruncateImmTo) 4113 Imm &= ((1 << III.TruncateImmTo) - 1); 4114 if (III.SignedImm) { 4115 APInt ActualValue(64, Imm, true); 4116 if (!ActualValue.isSignedIntN(III.ImmWidth)) 4117 return false; 4118 } else { 4119 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1; 4120 if ((uint64_t)Imm > UnsignedMax) 4121 return false; 4122 } 4123 4124 // If we're post-RA, the instructions don't agree on whether register zero is 4125 // special, we can transform this as long as the register operand that will 4126 // end up in the location where zero is special isn't R0. 4127 if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) { 4128 unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig : 4129 III.ZeroIsSpecialNew + 1; 4130 Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg(); 4131 Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg(); 4132 // If R0 is in the operand where zero is special for the new instruction, 4133 // it is unsafe to transform if the constant operand isn't that operand. 4134 if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) && 4135 ConstantOpNo != III.ZeroIsSpecialNew) 4136 return false; 4137 if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) && 4138 ConstantOpNo != PosForOrigZero) 4139 return false; 4140 } 4141 4142 // Get killed info in case fixup needed after transformation. 4143 unsigned ForwardKilledOperandReg = ~0U; 4144 if (PostRA && MI.getOperand(ConstantOpNo).isKill()) 4145 ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg(); 4146 4147 unsigned Opc = MI.getOpcode(); 4148 bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec || 4149 Opc == PPC::SRW || Opc == PPC::SRW_rec || 4150 Opc == PPC::SLW8 || Opc == PPC::SLW8_rec || 4151 Opc == PPC::SRW8 || Opc == PPC::SRW8_rec; 4152 bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec || 4153 Opc == PPC::SRD || Opc == PPC::SRD_rec; 4154 bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec || 4155 Opc == PPC::SLD_rec || Opc == PPC::SRD_rec; 4156 bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD || 4157 Opc == PPC::SRD_rec; 4158 4159 MI.setDesc(get(III.ImmOpcode)); 4160 if (ConstantOpNo == III.OpNoForForwarding) { 4161 // Converting shifts to immediate form is a bit tricky since they may do 4162 // one of three things: 4163 // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero 4164 // 2. If the shift amount is zero, the result is unchanged (save for maybe 4165 // setting CR0) 4166 // 3. If the shift amount is in [1, OpSize), it's just a shift 4167 if (SpecialShift32 || SpecialShift64) { 4168 LoadImmediateInfo LII; 4169 LII.Imm = 0; 4170 LII.SetCR = SetCR; 4171 LII.Is64Bit = SpecialShift64; 4172 uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F); 4173 if (Imm & (SpecialShift32 ? 0x20 : 0x40)) 4174 replaceInstrWithLI(MI, LII); 4175 // Shifts by zero don't change the value. If we don't need to set CR0, 4176 // just convert this to a COPY. Can't do this post-RA since we've already 4177 // cleaned up the copies. 4178 else if (!SetCR && ShAmt == 0 && !PostRA) { 4179 MI.RemoveOperand(2); 4180 MI.setDesc(get(PPC::COPY)); 4181 } else { 4182 // The 32 bit and 64 bit instructions are quite different. 4183 if (SpecialShift32) { 4184 // Left shifts use (N, 0, 31-N). 4185 // Right shifts use (32-N, N, 31) if 0 < N < 32. 4186 // use (0, 0, 31) if N == 0. 4187 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt; 4188 uint64_t MB = RightShift ? ShAmt : 0; 4189 uint64_t ME = RightShift ? 31 : 31 - ShAmt; 4190 replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH); 4191 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB) 4192 .addImm(ME); 4193 } else { 4194 // Left shifts use (N, 63-N). 4195 // Right shifts use (64-N, N) if 0 < N < 64. 4196 // use (0, 0) if N == 0. 4197 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt; 4198 uint64_t ME = RightShift ? ShAmt : 63 - ShAmt; 4199 replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH); 4200 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME); 4201 } 4202 } 4203 } else 4204 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm); 4205 } 4206 // Convert commutative instructions (switch the operands and convert the 4207 // desired one to an immediate. 4208 else if (III.IsCommutative) { 4209 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm); 4210 swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding); 4211 } else 4212 llvm_unreachable("Should have exited early!"); 4213 4214 // For instructions for which the constant register replaces a different 4215 // operand than where the immediate goes, we need to swap them. 4216 if (III.OpNoForForwarding != III.ImmOpNo) 4217 swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo); 4218 4219 // If the special R0/X0 register index are different for original instruction 4220 // and new instruction, we need to fix up the register class in new 4221 // instruction. 4222 if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) { 4223 if (III.ZeroIsSpecialNew) { 4224 // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no 4225 // need to fix up register class. 4226 Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg(); 4227 if (Register::isVirtualRegister(RegToModify)) { 4228 const TargetRegisterClass *NewRC = 4229 MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ? 4230 &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass; 4231 MRI.setRegClass(RegToModify, NewRC); 4232 } 4233 } 4234 } 4235 4236 // Fix up killed/dead flag after transformation. 4237 // Pattern: 4238 // ForwardKilledOperandReg = LI imm 4239 // y = XOP reg, ForwardKilledOperandReg(killed) 4240 if (ForwardKilledOperandReg != ~0U) 4241 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg); 4242 return true; 4243 } 4244 4245 const TargetRegisterClass * 4246 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const { 4247 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass) 4248 return &PPC::VSRCRegClass; 4249 return RC; 4250 } 4251 4252 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) { 4253 return PPC::getRecordFormOpcode(Opcode); 4254 } 4255 4256 // This function returns true if the machine instruction 4257 // always outputs a value by sign-extending a 32 bit value, 4258 // i.e. 0 to 31-th bits are same as 32-th bit. 4259 static bool isSignExtendingOp(const MachineInstr &MI) { 4260 int Opcode = MI.getOpcode(); 4261 if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS || 4262 Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec || 4263 Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA || 4264 Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 || 4265 Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 || 4266 Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX || 4267 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU || 4268 Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 || 4269 Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 || 4270 Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX || 4271 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB || 4272 Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH || 4273 Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 || 4274 Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW || 4275 Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 || 4276 Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 || 4277 Opcode == PPC::EXTSB8_32_64) 4278 return true; 4279 4280 if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33) 4281 return true; 4282 4283 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec || 4284 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) && 4285 MI.getOperand(3).getImm() > 0 && 4286 MI.getOperand(3).getImm() <= MI.getOperand(4).getImm()) 4287 return true; 4288 4289 return false; 4290 } 4291 4292 // This function returns true if the machine instruction 4293 // always outputs zeros in higher 32 bits. 4294 static bool isZeroExtendingOp(const MachineInstr &MI) { 4295 int Opcode = MI.getOpcode(); 4296 // The 16-bit immediate is sign-extended in li/lis. 4297 // If the most significant bit is zero, all higher bits are zero. 4298 if (Opcode == PPC::LI || Opcode == PPC::LI8 || 4299 Opcode == PPC::LIS || Opcode == PPC::LIS8) { 4300 int64_t Imm = MI.getOperand(1).getImm(); 4301 if (((uint64_t)Imm & ~0x7FFFuLL) == 0) 4302 return true; 4303 } 4304 4305 // We have some variations of rotate-and-mask instructions 4306 // that clear higher 32-bits. 4307 if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec || 4308 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec || 4309 Opcode == PPC::RLDICL_32_64) && 4310 MI.getOperand(3).getImm() >= 32) 4311 return true; 4312 4313 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) && 4314 MI.getOperand(3).getImm() >= 32 && 4315 MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm()) 4316 return true; 4317 4318 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec || 4319 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec || 4320 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) && 4321 MI.getOperand(3).getImm() <= MI.getOperand(4).getImm()) 4322 return true; 4323 4324 // There are other instructions that clear higher 32-bits. 4325 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec || 4326 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec || 4327 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 || 4328 Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec || 4329 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec || 4330 Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW || 4331 Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec || 4332 Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI || 4333 Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI || 4334 Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX || 4335 Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX || 4336 Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX || 4337 Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ || 4338 Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX || 4339 Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 || 4340 Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 || 4341 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 || 4342 Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || 4343 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 || 4344 Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec || 4345 Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec || 4346 Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec || 4347 Opcode == PPC::MFVSRWZ) 4348 return true; 4349 4350 return false; 4351 } 4352 4353 // This function returns true if the input MachineInstr is a TOC save 4354 // instruction. 4355 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const { 4356 if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg()) 4357 return false; 4358 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 4359 unsigned StackOffset = MI.getOperand(1).getImm(); 4360 Register StackReg = MI.getOperand(2).getReg(); 4361 if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset) 4362 return true; 4363 4364 return false; 4365 } 4366 4367 // We limit the max depth to track incoming values of PHIs or binary ops 4368 // (e.g. AND) to avoid excessive cost. 4369 const unsigned MAX_DEPTH = 1; 4370 4371 bool 4372 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt, 4373 const unsigned Depth) const { 4374 const MachineFunction *MF = MI.getParent()->getParent(); 4375 const MachineRegisterInfo *MRI = &MF->getRegInfo(); 4376 4377 // If we know this instruction returns sign- or zero-extended result, 4378 // return true. 4379 if (SignExt ? isSignExtendingOp(MI): 4380 isZeroExtendingOp(MI)) 4381 return true; 4382 4383 switch (MI.getOpcode()) { 4384 case PPC::COPY: { 4385 Register SrcReg = MI.getOperand(1).getReg(); 4386 4387 // In both ELFv1 and v2 ABI, method parameters and the return value 4388 // are sign- or zero-extended. 4389 if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) { 4390 const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>(); 4391 // We check the ZExt/SExt flags for a method parameter. 4392 if (MI.getParent()->getBasicBlock() == 4393 &MF->getFunction().getEntryBlock()) { 4394 Register VReg = MI.getOperand(0).getReg(); 4395 if (MF->getRegInfo().isLiveIn(VReg)) 4396 return SignExt ? FuncInfo->isLiveInSExt(VReg) : 4397 FuncInfo->isLiveInZExt(VReg); 4398 } 4399 4400 // For a method return value, we check the ZExt/SExt flags in attribute. 4401 // We assume the following code sequence for method call. 4402 // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1 4403 // BL8_NOP @func,... 4404 // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1 4405 // %5 = COPY %x3; G8RC:%5 4406 if (SrcReg == PPC::X3) { 4407 const MachineBasicBlock *MBB = MI.getParent(); 4408 MachineBasicBlock::const_instr_iterator II = 4409 MachineBasicBlock::const_instr_iterator(&MI); 4410 if (II != MBB->instr_begin() && 4411 (--II)->getOpcode() == PPC::ADJCALLSTACKUP) { 4412 const MachineInstr &CallMI = *(--II); 4413 if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) { 4414 const Function *CalleeFn = 4415 dyn_cast<Function>(CallMI.getOperand(0).getGlobal()); 4416 if (!CalleeFn) 4417 return false; 4418 const IntegerType *IntTy = 4419 dyn_cast<IntegerType>(CalleeFn->getReturnType()); 4420 const AttributeSet &Attrs = 4421 CalleeFn->getAttributes().getRetAttributes(); 4422 if (IntTy && IntTy->getBitWidth() <= 32) 4423 return Attrs.hasAttribute(SignExt ? Attribute::SExt : 4424 Attribute::ZExt); 4425 } 4426 } 4427 } 4428 } 4429 4430 // If this is a copy from another register, we recursively check source. 4431 if (!Register::isVirtualRegister(SrcReg)) 4432 return false; 4433 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 4434 if (SrcMI != NULL) 4435 return isSignOrZeroExtended(*SrcMI, SignExt, Depth); 4436 4437 return false; 4438 } 4439 4440 case PPC::ANDI_rec: 4441 case PPC::ANDIS_rec: 4442 case PPC::ORI: 4443 case PPC::ORIS: 4444 case PPC::XORI: 4445 case PPC::XORIS: 4446 case PPC::ANDI8_rec: 4447 case PPC::ANDIS8_rec: 4448 case PPC::ORI8: 4449 case PPC::ORIS8: 4450 case PPC::XORI8: 4451 case PPC::XORIS8: { 4452 // logical operation with 16-bit immediate does not change the upper bits. 4453 // So, we track the operand register as we do for register copy. 4454 Register SrcReg = MI.getOperand(1).getReg(); 4455 if (!Register::isVirtualRegister(SrcReg)) 4456 return false; 4457 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 4458 if (SrcMI != NULL) 4459 return isSignOrZeroExtended(*SrcMI, SignExt, Depth); 4460 4461 return false; 4462 } 4463 4464 // If all incoming values are sign-/zero-extended, 4465 // the output of OR, ISEL or PHI is also sign-/zero-extended. 4466 case PPC::OR: 4467 case PPC::OR8: 4468 case PPC::ISEL: 4469 case PPC::PHI: { 4470 if (Depth >= MAX_DEPTH) 4471 return false; 4472 4473 // The input registers for PHI are operand 1, 3, ... 4474 // The input registers for others are operand 1 and 2. 4475 unsigned E = 3, D = 1; 4476 if (MI.getOpcode() == PPC::PHI) { 4477 E = MI.getNumOperands(); 4478 D = 2; 4479 } 4480 4481 for (unsigned I = 1; I != E; I += D) { 4482 if (MI.getOperand(I).isReg()) { 4483 Register SrcReg = MI.getOperand(I).getReg(); 4484 if (!Register::isVirtualRegister(SrcReg)) 4485 return false; 4486 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 4487 if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1)) 4488 return false; 4489 } 4490 else 4491 return false; 4492 } 4493 return true; 4494 } 4495 4496 // If at least one of the incoming values of an AND is zero extended 4497 // then the output is also zero-extended. If both of the incoming values 4498 // are sign-extended then the output is also sign extended. 4499 case PPC::AND: 4500 case PPC::AND8: { 4501 if (Depth >= MAX_DEPTH) 4502 return false; 4503 4504 assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg()); 4505 4506 Register SrcReg1 = MI.getOperand(1).getReg(); 4507 Register SrcReg2 = MI.getOperand(2).getReg(); 4508 4509 if (!Register::isVirtualRegister(SrcReg1) || 4510 !Register::isVirtualRegister(SrcReg2)) 4511 return false; 4512 4513 const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1); 4514 const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2); 4515 if (!MISrc1 || !MISrc2) 4516 return false; 4517 4518 if(SignExt) 4519 return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) && 4520 isSignOrZeroExtended(*MISrc2, SignExt, Depth+1); 4521 else 4522 return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) || 4523 isSignOrZeroExtended(*MISrc2, SignExt, Depth+1); 4524 } 4525 4526 default: 4527 break; 4528 } 4529 return false; 4530 } 4531 4532 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const { 4533 return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ)); 4534 } 4535 4536 namespace { 4537 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo { 4538 MachineInstr *Loop, *EndLoop, *LoopCount; 4539 MachineFunction *MF; 4540 const TargetInstrInfo *TII; 4541 int64_t TripCount; 4542 4543 public: 4544 PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop, 4545 MachineInstr *LoopCount) 4546 : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount), 4547 MF(Loop->getParent()->getParent()), 4548 TII(MF->getSubtarget().getInstrInfo()) { 4549 // Inspect the Loop instruction up-front, as it may be deleted when we call 4550 // createTripCountGreaterCondition. 4551 if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI) 4552 TripCount = LoopCount->getOperand(1).getImm(); 4553 else 4554 TripCount = -1; 4555 } 4556 4557 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override { 4558 // Only ignore the terminator. 4559 return MI == EndLoop; 4560 } 4561 4562 Optional<bool> 4563 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB, 4564 SmallVectorImpl<MachineOperand> &Cond) override { 4565 if (TripCount == -1) { 4566 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1, 4567 // so we don't need to generate any thing here. 4568 Cond.push_back(MachineOperand::CreateImm(0)); 4569 Cond.push_back(MachineOperand::CreateReg( 4570 MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR, 4571 true)); 4572 return {}; 4573 } 4574 4575 return TripCount > TC; 4576 } 4577 4578 void setPreheader(MachineBasicBlock *NewPreheader) override { 4579 // Do nothing. We want the LOOP setup instruction to stay in the *old* 4580 // preheader, so we can use BDZ in the prologs to adapt the loop trip count. 4581 } 4582 4583 void adjustTripCount(int TripCountAdjust) override { 4584 // If the loop trip count is a compile-time value, then just change the 4585 // value. 4586 if (LoopCount->getOpcode() == PPC::LI8 || 4587 LoopCount->getOpcode() == PPC::LI) { 4588 int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust; 4589 LoopCount->getOperand(1).setImm(TripCount); 4590 return; 4591 } 4592 4593 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1, 4594 // so we don't need to generate any thing here. 4595 } 4596 4597 void disposed() override { 4598 Loop->eraseFromParent(); 4599 // Ensure the loop setup instruction is deleted too. 4600 LoopCount->eraseFromParent(); 4601 } 4602 }; 4603 } // namespace 4604 4605 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo> 4606 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const { 4607 // We really "analyze" only hardware loops right now. 4608 MachineBasicBlock::iterator I = LoopBB->getFirstTerminator(); 4609 MachineBasicBlock *Preheader = *LoopBB->pred_begin(); 4610 if (Preheader == LoopBB) 4611 Preheader = *std::next(LoopBB->pred_begin()); 4612 MachineFunction *MF = Preheader->getParent(); 4613 4614 if (I != LoopBB->end() && isBDNZ(I->getOpcode())) { 4615 SmallPtrSet<MachineBasicBlock *, 8> Visited; 4616 if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) { 4617 Register LoopCountReg = LoopInst->getOperand(0).getReg(); 4618 MachineRegisterInfo &MRI = MF->getRegInfo(); 4619 MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg); 4620 return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount); 4621 } 4622 } 4623 return nullptr; 4624 } 4625 4626 MachineInstr *PPCInstrInfo::findLoopInstr( 4627 MachineBasicBlock &PreHeader, 4628 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const { 4629 4630 unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop); 4631 4632 // The loop set-up instruction should be in preheader 4633 for (auto &I : PreHeader.instrs()) 4634 if (I.getOpcode() == LOOPi) 4635 return &I; 4636 return nullptr; 4637 } 4638 4639 // Return true if get the base operand, byte offset of an instruction and the 4640 // memory width. Width is the size of memory that is being loaded/stored. 4641 bool PPCInstrInfo::getMemOperandWithOffsetWidth( 4642 const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset, 4643 unsigned &Width, const TargetRegisterInfo *TRI) const { 4644 if (!LdSt.mayLoadOrStore()) 4645 return false; 4646 4647 // Handle only loads/stores with base register followed by immediate offset. 4648 if (LdSt.getNumExplicitOperands() != 3) 4649 return false; 4650 if (!LdSt.getOperand(1).isImm() || !LdSt.getOperand(2).isReg()) 4651 return false; 4652 4653 if (!LdSt.hasOneMemOperand()) 4654 return false; 4655 4656 Width = (*LdSt.memoperands_begin())->getSize(); 4657 Offset = LdSt.getOperand(1).getImm(); 4658 BaseReg = &LdSt.getOperand(2); 4659 return true; 4660 } 4661 4662 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint( 4663 const MachineInstr &MIa, const MachineInstr &MIb) const { 4664 assert(MIa.mayLoadOrStore() && "MIa must be a load or store."); 4665 assert(MIb.mayLoadOrStore() && "MIb must be a load or store."); 4666 4667 if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() || 4668 MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef()) 4669 return false; 4670 4671 // Retrieve the base register, offset from the base register and width. Width 4672 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If 4673 // base registers are identical, and the offset of a lower memory access + 4674 // the width doesn't overlap the offset of a higher memory access, 4675 // then the memory accesses are different. 4676 const TargetRegisterInfo *TRI = &getRegisterInfo(); 4677 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr; 4678 int64_t OffsetA = 0, OffsetB = 0; 4679 unsigned int WidthA = 0, WidthB = 0; 4680 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) && 4681 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) { 4682 if (BaseOpA->isIdenticalTo(*BaseOpB)) { 4683 int LowOffset = std::min(OffsetA, OffsetB); 4684 int HighOffset = std::max(OffsetA, OffsetB); 4685 int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB; 4686 if (LowOffset + LowWidth <= HighOffset) 4687 return true; 4688 } 4689 } 4690 return false; 4691 } 4692