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