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