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