1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the PowerPC implementation of the TargetInstrInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCHazardRecognizers.h"
18 #include "PPCInstrBuilder.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.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/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "ppc-instr-info"
44 #define GET_INSTRMAP_INFO
45 #define GET_INSTRINFO_CTOR_DTOR
46 #include "PPCGenInstrInfo.inc"
49 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
50 cl::desc("Disable analysis for CTR loops"));
52 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
53 cl::desc("Disable compare instruction optimization"), cl::Hidden);
55 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
56 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
58 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
59 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
62 // Pin the vtable to this file.
63 void PPCInstrInfo::anchor() {}
65 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
66 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
67 Subtarget(STI), RI(STI) {}
69 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
70 /// this target when scheduling the DAG.
71 ScheduleHazardRecognizer *
72 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
73 const ScheduleDAG *DAG) const {
75 static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
76 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
77 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
78 const InstrItineraryData *II =
79 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
80 return new ScoreboardHazardRecognizer(II, DAG);
83 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
86 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
87 /// to use for this target when scheduling the DAG.
88 ScheduleHazardRecognizer *
89 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
90 const ScheduleDAG *DAG) const {
92 DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
94 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
95 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
97 // Most subtargets use a PPC970 recognizer.
98 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
99 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
100 assert(DAG->TII && "No InstrInfo?");
102 return new PPCHazardRecognizer970(*DAG);
105 return new ScoreboardHazardRecognizer(II, DAG);
109 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
110 const MachineInstr *DefMI, unsigned DefIdx,
111 const MachineInstr *UseMI,
112 unsigned UseIdx) const {
113 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
116 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
117 unsigned Reg = DefMO.getReg();
119 const TargetRegisterInfo *TRI = &getRegisterInfo();
121 if (TRI->isVirtualRegister(Reg)) {
122 const MachineRegisterInfo *MRI =
123 &DefMI->getParent()->getParent()->getRegInfo();
124 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
125 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
127 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
128 PPC::CRBITRCRegClass.contains(Reg);
131 if (UseMI->isBranch() && IsRegCR) {
133 Latency = getInstrLatency(ItinData, DefMI);
135 // On some cores, there is an additional delay between writing to a condition
136 // register, and using it from a branch.
137 unsigned Directive = Subtarget.getDarwinDirective();
159 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
160 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
161 unsigned &SrcReg, unsigned &DstReg,
162 unsigned &SubIdx) const {
163 switch (MI.getOpcode()) {
164 default: return false;
166 case PPC::EXTSW_32_64:
167 SrcReg = MI.getOperand(1).getReg();
168 DstReg = MI.getOperand(0).getReg();
169 SubIdx = PPC::sub_32;
174 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
175 int &FrameIndex) const {
176 // Note: This list must be kept consistent with LoadRegFromStackSlot.
177 switch (MI->getOpcode()) {
183 case PPC::RESTORE_CR:
184 case PPC::RESTORE_CRBIT:
187 case PPC::RESTORE_VRSAVE:
188 // Check for the operands added by addFrameReference (the immediate is the
189 // offset which defaults to 0).
190 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
191 MI->getOperand(2).isFI()) {
192 FrameIndex = MI->getOperand(2).getIndex();
193 return MI->getOperand(0).getReg();
200 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
201 int &FrameIndex) const {
202 // Note: This list must be kept consistent with StoreRegToStackSlot.
203 switch (MI->getOpcode()) {
210 case PPC::SPILL_CRBIT:
213 case PPC::SPILL_VRSAVE:
214 // Check for the operands added by addFrameReference (the immediate is the
215 // offset which defaults to 0).
216 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
217 MI->getOperand(2).isFI()) {
218 FrameIndex = MI->getOperand(2).getIndex();
219 return MI->getOperand(0).getReg();
226 // commuteInstruction - We can commute rlwimi instructions, but only if the
227 // rotate amt is zero. We also have to munge the immediates a bit.
229 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
230 MachineFunction &MF = *MI->getParent()->getParent();
232 // Normal instructions can be commuted the obvious way.
233 if (MI->getOpcode() != PPC::RLWIMI &&
234 MI->getOpcode() != PPC::RLWIMIo)
235 return TargetInstrInfo::commuteInstruction(MI, NewMI);
236 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
237 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
238 // changing the relative order of the mask operands might change what happens
239 // to the high-bits of the mask (and, thus, the result).
241 // Cannot commute if it has a non-zero rotate count.
242 if (MI->getOperand(3).getImm() != 0)
245 // If we have a zero rotate count, we have:
247 // Op0 = (Op1 & ~M) | (Op2 & M)
249 // M = mask((ME+1)&31, (MB-1)&31)
250 // Op0 = (Op2 & ~M) | (Op1 & M)
253 unsigned Reg0 = MI->getOperand(0).getReg();
254 unsigned Reg1 = MI->getOperand(1).getReg();
255 unsigned Reg2 = MI->getOperand(2).getReg();
256 unsigned SubReg1 = MI->getOperand(1).getSubReg();
257 unsigned SubReg2 = MI->getOperand(2).getSubReg();
258 bool Reg1IsKill = MI->getOperand(1).isKill();
259 bool Reg2IsKill = MI->getOperand(2).isKill();
260 bool ChangeReg0 = false;
261 // If machine instrs are no longer in two-address forms, update
262 // destination register as well.
264 // Must be two address instruction!
265 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
266 "Expecting a two-address instruction!");
267 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
273 unsigned MB = MI->getOperand(4).getImm();
274 unsigned ME = MI->getOperand(5).getImm();
277 // Create a new instruction.
278 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
279 bool Reg0IsDead = MI->getOperand(0).isDead();
280 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
281 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
282 .addReg(Reg2, getKillRegState(Reg2IsKill))
283 .addReg(Reg1, getKillRegState(Reg1IsKill))
285 .addImm((MB-1) & 31);
289 MI->getOperand(0).setReg(Reg2);
290 MI->getOperand(0).setSubReg(SubReg2);
292 MI->getOperand(2).setReg(Reg1);
293 MI->getOperand(1).setReg(Reg2);
294 MI->getOperand(2).setSubReg(SubReg1);
295 MI->getOperand(1).setSubReg(SubReg2);
296 MI->getOperand(2).setIsKill(Reg1IsKill);
297 MI->getOperand(1).setIsKill(Reg2IsKill);
299 // Swap the mask around.
300 MI->getOperand(4).setImm((ME+1) & 31);
301 MI->getOperand(5).setImm((MB-1) & 31);
305 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
306 unsigned &SrcOpIdx2) const {
307 // For VSX A-Type FMA instructions, it is the first two operands that can be
308 // commuted, however, because the non-encoded tied input operand is listed
309 // first, the operands to swap are actually the second and third.
311 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
313 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
320 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
321 MachineBasicBlock::iterator MI) const {
322 // This function is used for scheduling, and the nop wanted here is the type
323 // that terminates dispatch groups on the POWER cores.
324 unsigned Directive = Subtarget.getDarwinDirective();
327 default: Opcode = PPC::NOP; break;
328 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
329 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
330 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
334 BuildMI(MBB, MI, DL, get(Opcode));
337 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
338 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
339 NopInst.setOpcode(PPC::NOP);
343 // Note: If the condition register is set to CTR or CTR8 then this is a
344 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
345 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
346 MachineBasicBlock *&FBB,
347 SmallVectorImpl<MachineOperand> &Cond,
348 bool AllowModify) const {
349 bool isPPC64 = Subtarget.isPPC64();
351 // If the block has no terminators, it just falls into the block after it.
352 MachineBasicBlock::iterator I = MBB.end();
353 if (I == MBB.begin())
356 while (I->isDebugValue()) {
357 if (I == MBB.begin())
361 if (!isUnpredicatedTerminator(I))
364 // Get the last instruction in the block.
365 MachineInstr *LastInst = I;
367 // If there is only one terminator instruction, process it.
368 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
369 if (LastInst->getOpcode() == PPC::B) {
370 if (!LastInst->getOperand(0).isMBB())
372 TBB = LastInst->getOperand(0).getMBB();
374 } else if (LastInst->getOpcode() == PPC::BCC) {
375 if (!LastInst->getOperand(2).isMBB())
377 // Block ends with fall-through condbranch.
378 TBB = LastInst->getOperand(2).getMBB();
379 Cond.push_back(LastInst->getOperand(0));
380 Cond.push_back(LastInst->getOperand(1));
382 } else if (LastInst->getOpcode() == PPC::BC) {
383 if (!LastInst->getOperand(1).isMBB())
385 // Block ends with fall-through condbranch.
386 TBB = LastInst->getOperand(1).getMBB();
387 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
388 Cond.push_back(LastInst->getOperand(0));
390 } else if (LastInst->getOpcode() == PPC::BCn) {
391 if (!LastInst->getOperand(1).isMBB())
393 // Block ends with fall-through condbranch.
394 TBB = LastInst->getOperand(1).getMBB();
395 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
396 Cond.push_back(LastInst->getOperand(0));
398 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
399 LastInst->getOpcode() == PPC::BDNZ) {
400 if (!LastInst->getOperand(0).isMBB())
402 if (DisableCTRLoopAnal)
404 TBB = LastInst->getOperand(0).getMBB();
405 Cond.push_back(MachineOperand::CreateImm(1));
406 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
409 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
410 LastInst->getOpcode() == PPC::BDZ) {
411 if (!LastInst->getOperand(0).isMBB())
413 if (DisableCTRLoopAnal)
415 TBB = LastInst->getOperand(0).getMBB();
416 Cond.push_back(MachineOperand::CreateImm(0));
417 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
422 // Otherwise, don't know what this is.
426 // Get the instruction before it if it's a terminator.
427 MachineInstr *SecondLastInst = I;
429 // If there are three terminators, we don't know what sort of block this is.
430 if (SecondLastInst && I != MBB.begin() &&
431 isUnpredicatedTerminator(--I))
434 // If the block ends with PPC::B and PPC:BCC, handle it.
435 if (SecondLastInst->getOpcode() == PPC::BCC &&
436 LastInst->getOpcode() == PPC::B) {
437 if (!SecondLastInst->getOperand(2).isMBB() ||
438 !LastInst->getOperand(0).isMBB())
440 TBB = SecondLastInst->getOperand(2).getMBB();
441 Cond.push_back(SecondLastInst->getOperand(0));
442 Cond.push_back(SecondLastInst->getOperand(1));
443 FBB = LastInst->getOperand(0).getMBB();
445 } else if (SecondLastInst->getOpcode() == PPC::BC &&
446 LastInst->getOpcode() == PPC::B) {
447 if (!SecondLastInst->getOperand(1).isMBB() ||
448 !LastInst->getOperand(0).isMBB())
450 TBB = SecondLastInst->getOperand(1).getMBB();
451 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
452 Cond.push_back(SecondLastInst->getOperand(0));
453 FBB = LastInst->getOperand(0).getMBB();
455 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
456 LastInst->getOpcode() == PPC::B) {
457 if (!SecondLastInst->getOperand(1).isMBB() ||
458 !LastInst->getOperand(0).isMBB())
460 TBB = SecondLastInst->getOperand(1).getMBB();
461 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
462 Cond.push_back(SecondLastInst->getOperand(0));
463 FBB = LastInst->getOperand(0).getMBB();
465 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
466 SecondLastInst->getOpcode() == PPC::BDNZ) &&
467 LastInst->getOpcode() == PPC::B) {
468 if (!SecondLastInst->getOperand(0).isMBB() ||
469 !LastInst->getOperand(0).isMBB())
471 if (DisableCTRLoopAnal)
473 TBB = SecondLastInst->getOperand(0).getMBB();
474 Cond.push_back(MachineOperand::CreateImm(1));
475 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
477 FBB = LastInst->getOperand(0).getMBB();
479 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
480 SecondLastInst->getOpcode() == PPC::BDZ) &&
481 LastInst->getOpcode() == PPC::B) {
482 if (!SecondLastInst->getOperand(0).isMBB() ||
483 !LastInst->getOperand(0).isMBB())
485 if (DisableCTRLoopAnal)
487 TBB = SecondLastInst->getOperand(0).getMBB();
488 Cond.push_back(MachineOperand::CreateImm(0));
489 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
491 FBB = LastInst->getOperand(0).getMBB();
495 // If the block ends with two PPC:Bs, handle it. The second one is not
496 // executed, so remove it.
497 if (SecondLastInst->getOpcode() == PPC::B &&
498 LastInst->getOpcode() == PPC::B) {
499 if (!SecondLastInst->getOperand(0).isMBB())
501 TBB = SecondLastInst->getOperand(0).getMBB();
504 I->eraseFromParent();
508 // Otherwise, can't handle this.
512 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
513 MachineBasicBlock::iterator I = MBB.end();
514 if (I == MBB.begin()) return 0;
516 while (I->isDebugValue()) {
517 if (I == MBB.begin())
521 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
522 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
523 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
524 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
527 // Remove the branch.
528 I->eraseFromParent();
532 if (I == MBB.begin()) return 1;
534 if (I->getOpcode() != PPC::BCC &&
535 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
536 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
537 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
540 // Remove the branch.
541 I->eraseFromParent();
546 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
547 MachineBasicBlock *FBB,
548 const SmallVectorImpl<MachineOperand> &Cond,
550 // Shouldn't be a fall through.
551 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
552 assert((Cond.size() == 2 || Cond.size() == 0) &&
553 "PPC branch conditions have two components!");
555 bool isPPC64 = Subtarget.isPPC64();
559 if (Cond.empty()) // Unconditional branch
560 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
561 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
562 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
563 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
564 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
565 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
566 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
567 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
568 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
569 else // Conditional branch
570 BuildMI(&MBB, DL, get(PPC::BCC))
571 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
575 // Two-way Conditional Branch.
576 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
577 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
578 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
579 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
580 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
581 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
582 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
583 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
585 BuildMI(&MBB, DL, get(PPC::BCC))
586 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
587 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
592 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
593 const SmallVectorImpl<MachineOperand> &Cond,
594 unsigned TrueReg, unsigned FalseReg,
595 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
596 if (!Subtarget.hasISEL())
599 if (Cond.size() != 2)
602 // If this is really a bdnz-like condition, then it cannot be turned into a
604 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
607 // Check register classes.
608 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
609 const TargetRegisterClass *RC =
610 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
614 // isel is for regular integer GPRs only.
615 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
616 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
617 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
618 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
621 // FIXME: These numbers are for the A2, how well they work for other cores is
622 // an open question. On the A2, the isel instruction has a 2-cycle latency
623 // but single-cycle throughput. These numbers are used in combination with
624 // the MispredictPenalty setting from the active SchedMachineModel.
632 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
633 MachineBasicBlock::iterator MI, DebugLoc dl,
635 const SmallVectorImpl<MachineOperand> &Cond,
636 unsigned TrueReg, unsigned FalseReg) const {
637 assert(Cond.size() == 2 &&
638 "PPC branch conditions have two components!");
640 assert(Subtarget.hasISEL() &&
641 "Cannot insert select on target without ISEL support");
643 // Get the register classes.
644 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
645 const TargetRegisterClass *RC =
646 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
647 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
649 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
650 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
652 PPC::GPRCRegClass.hasSubClassEq(RC) ||
653 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
654 "isel is for regular integer GPRs only");
656 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
657 unsigned SelectPred = Cond[0].getImm();
661 switch (SelectPred) {
662 default: llvm_unreachable("invalid predicate for isel");
663 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
664 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
665 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
666 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
667 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
668 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
669 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
670 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
671 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
672 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
675 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
676 SecondReg = SwapOps ? TrueReg : FalseReg;
678 // The first input register of isel cannot be r0. If it is a member
679 // of a register class that can be r0, then copy it first (the
680 // register allocator should eliminate the copy).
681 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
682 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
683 const TargetRegisterClass *FirstRC =
684 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
685 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
686 unsigned OldFirstReg = FirstReg;
687 FirstReg = MRI.createVirtualRegister(FirstRC);
688 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
689 .addReg(OldFirstReg);
692 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
693 .addReg(FirstReg).addReg(SecondReg)
694 .addReg(Cond[1].getReg(), 0, SubIdx);
697 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
698 MachineBasicBlock::iterator I, DebugLoc DL,
699 unsigned DestReg, unsigned SrcReg,
700 bool KillSrc) const {
701 // We can end up with self copies and similar things as a result of VSX copy
702 // legalization. Promote them here.
703 const TargetRegisterInfo *TRI = &getRegisterInfo();
704 if (PPC::F8RCRegClass.contains(DestReg) &&
705 PPC::VSLRCRegClass.contains(SrcReg)) {
707 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
709 if (VSXSelfCopyCrash && SrcReg == SuperReg)
710 llvm_unreachable("nop VSX copy");
713 } else if (PPC::VRRCRegClass.contains(DestReg) &&
714 PPC::VSHRCRegClass.contains(SrcReg)) {
716 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
718 if (VSXSelfCopyCrash && SrcReg == SuperReg)
719 llvm_unreachable("nop VSX copy");
722 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
723 PPC::VSLRCRegClass.contains(DestReg)) {
725 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
727 if (VSXSelfCopyCrash && DestReg == SuperReg)
728 llvm_unreachable("nop VSX copy");
731 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
732 PPC::VSHRCRegClass.contains(DestReg)) {
734 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
736 if (VSXSelfCopyCrash && DestReg == SuperReg)
737 llvm_unreachable("nop VSX copy");
743 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
745 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
747 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
749 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
751 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
753 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
754 // There are two different ways this can be done:
755 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
756 // issue in VSU pipeline 0.
757 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
758 // can go to either pipeline.
759 // We'll always use xxlor here, because in practically all cases where
760 // copies are generated, they are close enough to some use that the
761 // lower-latency form is preferable.
763 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
765 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
768 llvm_unreachable("Impossible reg-to-reg copy");
770 const MCInstrDesc &MCID = get(Opc);
771 if (MCID.getNumOperands() == 3)
772 BuildMI(MBB, I, DL, MCID, DestReg)
773 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
775 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
778 // This function returns true if a CR spill is necessary and false otherwise.
780 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
781 unsigned SrcReg, bool isKill,
783 const TargetRegisterClass *RC,
784 SmallVectorImpl<MachineInstr*> &NewMIs,
785 bool &NonRI, bool &SpillsVRS) const{
786 // Note: If additional store instructions are added here,
787 // update isStoreToStackSlot.
790 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
791 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
792 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
794 getKillRegState(isKill)),
796 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
797 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
798 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
800 getKillRegState(isKill)),
802 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
803 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
805 getKillRegState(isKill)),
807 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
808 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
810 getKillRegState(isKill)),
812 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
813 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
815 getKillRegState(isKill)),
818 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
819 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
821 getKillRegState(isKill)),
824 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
825 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
827 getKillRegState(isKill)),
830 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
831 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
833 getKillRegState(isKill)),
836 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
837 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
839 getKillRegState(isKill)),
842 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
843 assert(Subtarget.isDarwin() &&
844 "VRSAVE only needs spill/restore on Darwin");
845 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
847 getKillRegState(isKill)),
851 llvm_unreachable("Unknown regclass!");
858 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
859 MachineBasicBlock::iterator MI,
860 unsigned SrcReg, bool isKill, int FrameIdx,
861 const TargetRegisterClass *RC,
862 const TargetRegisterInfo *TRI) const {
863 MachineFunction &MF = *MBB.getParent();
864 SmallVector<MachineInstr*, 4> NewMIs;
866 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
867 FuncInfo->setHasSpills();
869 bool NonRI = false, SpillsVRS = false;
870 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
872 FuncInfo->setSpillsCR();
875 FuncInfo->setSpillsVRSAVE();
878 FuncInfo->setHasNonRISpills();
880 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
881 MBB.insert(MI, NewMIs[i]);
883 const MachineFrameInfo &MFI = *MF.getFrameInfo();
884 MachineMemOperand *MMO =
885 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
886 MachineMemOperand::MOStore,
887 MFI.getObjectSize(FrameIdx),
888 MFI.getObjectAlignment(FrameIdx));
889 NewMIs.back()->addMemOperand(MF, MMO);
893 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
894 unsigned DestReg, int FrameIdx,
895 const TargetRegisterClass *RC,
896 SmallVectorImpl<MachineInstr*> &NewMIs,
897 bool &NonRI, bool &SpillsVRS) const{
898 // Note: If additional load instructions are added here,
899 // update isLoadFromStackSlot.
901 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
902 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
903 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
904 DestReg), FrameIdx));
905 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
906 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
907 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
909 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
910 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
912 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
913 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
915 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
916 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
917 get(PPC::RESTORE_CR), DestReg),
920 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
921 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
922 get(PPC::RESTORE_CRBIT), DestReg),
925 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
926 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
929 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
930 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
933 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
934 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
937 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
938 assert(Subtarget.isDarwin() &&
939 "VRSAVE only needs spill/restore on Darwin");
940 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
941 get(PPC::RESTORE_VRSAVE),
946 llvm_unreachable("Unknown regclass!");
953 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
954 MachineBasicBlock::iterator MI,
955 unsigned DestReg, int FrameIdx,
956 const TargetRegisterClass *RC,
957 const TargetRegisterInfo *TRI) const {
958 MachineFunction &MF = *MBB.getParent();
959 SmallVector<MachineInstr*, 4> NewMIs;
961 if (MI != MBB.end()) DL = MI->getDebugLoc();
963 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
964 FuncInfo->setHasSpills();
966 bool NonRI = false, SpillsVRS = false;
967 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
969 FuncInfo->setSpillsCR();
972 FuncInfo->setSpillsVRSAVE();
975 FuncInfo->setHasNonRISpills();
977 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
978 MBB.insert(MI, NewMIs[i]);
980 const MachineFrameInfo &MFI = *MF.getFrameInfo();
981 MachineMemOperand *MMO =
982 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
983 MachineMemOperand::MOLoad,
984 MFI.getObjectSize(FrameIdx),
985 MFI.getObjectAlignment(FrameIdx));
986 NewMIs.back()->addMemOperand(MF, MMO);
990 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
991 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
992 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
993 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
995 // Leave the CR# the same, but invert the condition.
996 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1000 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
1001 unsigned Reg, MachineRegisterInfo *MRI) const {
1002 // For some instructions, it is legal to fold ZERO into the RA register field.
1003 // A zero immediate should always be loaded with a single li.
1004 unsigned DefOpc = DefMI->getOpcode();
1005 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1007 if (!DefMI->getOperand(1).isImm())
1009 if (DefMI->getOperand(1).getImm() != 0)
1012 // Note that we cannot here invert the arguments of an isel in order to fold
1013 // a ZERO into what is presented as the second argument. All we have here
1014 // is the condition bit, and that might come from a CR-logical bit operation.
1016 const MCInstrDesc &UseMCID = UseMI->getDesc();
1018 // Only fold into real machine instructions.
1019 if (UseMCID.isPseudo())
1023 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1024 if (UseMI->getOperand(UseIdx).isReg() &&
1025 UseMI->getOperand(UseIdx).getReg() == Reg)
1028 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1029 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1031 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1033 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1034 // register (which might also be specified as a pointer class kind).
1035 if (UseInfo->isLookupPtrRegClass()) {
1036 if (UseInfo->RegClass /* Kind */ != 1)
1039 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1040 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1044 // Make sure this is not tied to an output register (or otherwise
1045 // constrained). This is true for ST?UX registers, for example, which
1046 // are tied to their output registers.
1047 if (UseInfo->Constraints != 0)
1051 if (UseInfo->isLookupPtrRegClass()) {
1052 bool isPPC64 = Subtarget.isPPC64();
1053 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1055 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1056 PPC::ZERO8 : PPC::ZERO;
1059 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1060 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1063 DefMI->eraseFromParent();
1068 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1069 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1071 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1076 // We should make sure that, if we're going to predicate both sides of a
1077 // condition (a diamond), that both sides don't define the counter register. We
1078 // can predicate counter-decrement-based branches, but while that predicates
1079 // the branching, it does not predicate the counter decrement. If we tried to
1080 // merge the triangle into one predicated block, we'd decrement the counter
1082 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1083 unsigned NumT, unsigned ExtraT,
1084 MachineBasicBlock &FMBB,
1085 unsigned NumF, unsigned ExtraF,
1086 const BranchProbability &Probability) const {
1087 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1091 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1092 // The predicated branches are identified by their type, not really by the
1093 // explicit presence of a predicate. Furthermore, some of them can be
1094 // predicated more than once. Because if conversion won't try to predicate
1095 // any instruction which already claims to be predicated (by returning true
1096 // here), always return false. In doing so, we let isPredicable() be the
1097 // final word on whether not the instruction can be (further) predicated.
1102 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1103 if (!MI->isTerminator())
1106 // Conditional branch is a special case.
1107 if (MI->isBranch() && !MI->isBarrier())
1110 return !isPredicated(MI);
1113 bool PPCInstrInfo::PredicateInstruction(
1115 const SmallVectorImpl<MachineOperand> &Pred) const {
1116 unsigned OpC = MI->getOpcode();
1117 if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1118 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1119 bool isPPC64 = Subtarget.isPPC64();
1120 MI->setDesc(get(Pred[0].getImm() ?
1121 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1122 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1123 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1124 MI->setDesc(get(PPC::BCLR));
1125 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1126 .addReg(Pred[1].getReg());
1127 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1128 MI->setDesc(get(PPC::BCLRn));
1129 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1130 .addReg(Pred[1].getReg());
1132 MI->setDesc(get(PPC::BCCLR));
1133 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1134 .addImm(Pred[0].getImm())
1135 .addReg(Pred[1].getReg());
1139 } else if (OpC == PPC::B) {
1140 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1141 bool isPPC64 = Subtarget.isPPC64();
1142 MI->setDesc(get(Pred[0].getImm() ?
1143 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1144 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1145 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1146 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1147 MI->RemoveOperand(0);
1149 MI->setDesc(get(PPC::BC));
1150 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1151 .addReg(Pred[1].getReg())
1153 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1154 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1155 MI->RemoveOperand(0);
1157 MI->setDesc(get(PPC::BCn));
1158 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1159 .addReg(Pred[1].getReg())
1162 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1163 MI->RemoveOperand(0);
1165 MI->setDesc(get(PPC::BCC));
1166 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1167 .addImm(Pred[0].getImm())
1168 .addReg(Pred[1].getReg())
1173 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1174 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1175 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1176 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1178 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1179 bool isPPC64 = Subtarget.isPPC64();
1181 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1182 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1183 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1184 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1185 .addReg(Pred[1].getReg());
1187 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1188 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1189 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1190 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1191 .addReg(Pred[1].getReg());
1195 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1196 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1197 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1198 .addImm(Pred[0].getImm())
1199 .addReg(Pred[1].getReg());
1206 bool PPCInstrInfo::SubsumesPredicate(
1207 const SmallVectorImpl<MachineOperand> &Pred1,
1208 const SmallVectorImpl<MachineOperand> &Pred2) const {
1209 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1210 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1212 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1214 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1217 // P1 can only subsume P2 if they test the same condition register.
1218 if (Pred1[1].getReg() != Pred2[1].getReg())
1221 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1222 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1227 // Does P1 subsume P2, e.g. GE subsumes GT.
1228 if (P1 == PPC::PRED_LE &&
1229 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1231 if (P1 == PPC::PRED_GE &&
1232 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1238 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1239 std::vector<MachineOperand> &Pred) const {
1240 // Note: At the present time, the contents of Pred from this function is
1241 // unused by IfConversion. This implementation follows ARM by pushing the
1242 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1243 // predicate, instructions defining CTR or CTR8 are also included as
1244 // predicate-defining instructions.
1246 const TargetRegisterClass *RCs[] =
1247 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1248 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1251 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1252 const MachineOperand &MO = MI->getOperand(i);
1253 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1254 const TargetRegisterClass *RC = RCs[c];
1256 if (MO.isDef() && RC->contains(MO.getReg())) {
1260 } else if (MO.isRegMask()) {
1261 for (TargetRegisterClass::iterator I = RC->begin(),
1262 IE = RC->end(); I != IE; ++I)
1263 if (MO.clobbersPhysReg(*I)) {
1274 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1275 unsigned OpC = MI->getOpcode();
1290 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1291 unsigned &SrcReg, unsigned &SrcReg2,
1292 int &Mask, int &Value) const {
1293 unsigned Opc = MI->getOpcode();
1296 default: return false;
1301 SrcReg = MI->getOperand(1).getReg();
1303 Value = MI->getOperand(2).getImm();
1312 SrcReg = MI->getOperand(1).getReg();
1313 SrcReg2 = MI->getOperand(2).getReg();
1318 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1319 unsigned SrcReg, unsigned SrcReg2,
1320 int Mask, int Value,
1321 const MachineRegisterInfo *MRI) const {
1325 int OpC = CmpInstr->getOpcode();
1326 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1328 // FP record forms set CR1 based on the execption status bits, not a
1329 // comparison with zero.
1330 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1333 // The record forms set the condition register based on a signed comparison
1334 // with zero (so says the ISA manual). This is not as straightforward as it
1335 // seems, however, because this is always a 64-bit comparison on PPC64, even
1336 // for instructions that are 32-bit in nature (like slw for example).
1337 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1338 // for equality checks (as those don't depend on the sign). On PPC64,
1339 // we are restricted to equality for unsigned 64-bit comparisons and for
1340 // signed 32-bit comparisons the applicability is more restricted.
1341 bool isPPC64 = Subtarget.isPPC64();
1342 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1343 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1344 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1346 // Get the unique definition of SrcReg.
1347 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1348 if (!MI) return false;
1349 int MIOpC = MI->getOpcode();
1351 bool equalityOnly = false;
1354 if (is32BitSignedCompare) {
1355 // We can perform this optimization only if MI is sign-extending.
1356 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1357 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1358 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1359 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1360 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1364 } else if (is32BitUnsignedCompare) {
1365 // We can perform this optimization, equality only, if MI is
1367 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1368 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1369 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1371 equalityOnly = true;
1375 equalityOnly = is64BitUnsignedCompare;
1377 equalityOnly = is32BitUnsignedCompare;
1380 // We need to check the uses of the condition register in order to reject
1381 // non-equality comparisons.
1382 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1383 IE = MRI->use_instr_end(); I != IE; ++I) {
1384 MachineInstr *UseMI = &*I;
1385 if (UseMI->getOpcode() == PPC::BCC) {
1386 unsigned Pred = UseMI->getOperand(0).getImm();
1387 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1389 } else if (UseMI->getOpcode() == PPC::ISEL ||
1390 UseMI->getOpcode() == PPC::ISEL8) {
1391 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1392 if (SubIdx != PPC::sub_eq)
1399 MachineBasicBlock::iterator I = CmpInstr;
1401 // Scan forward to find the first use of the compare.
1402 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1404 bool FoundUse = false;
1405 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1406 JE = MRI->use_instr_end(); J != JE; ++J)
1416 // There are two possible candidates which can be changed to set CR[01].
1417 // One is MI, the other is a SUB instruction.
1418 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1419 MachineInstr *Sub = nullptr;
1421 // MI is not a candidate for CMPrr.
1423 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1424 // same BB as the comparison. This is to allow the check below to avoid calls
1425 // (and other explicit clobbers); instead we should really check for these
1426 // more explicitly (in at least a few predecessors).
1427 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1428 // PPC does not have a record-form SUBri.
1433 const TargetRegisterInfo *TRI = &getRegisterInfo();
1436 // Get ready to iterate backward from CmpInstr.
1437 MachineBasicBlock::iterator E = MI,
1438 B = CmpInstr->getParent()->begin();
1440 for (; I != E && !noSub; --I) {
1441 const MachineInstr &Instr = *I;
1442 unsigned IOpC = Instr.getOpcode();
1444 if (&*I != CmpInstr && (
1445 Instr.modifiesRegister(PPC::CR0, TRI) ||
1446 Instr.readsRegister(PPC::CR0, TRI)))
1447 // This instruction modifies or uses the record condition register after
1448 // the one we want to change. While we could do this transformation, it
1449 // would likely not be profitable. This transformation removes one
1450 // instruction, and so even forcing RA to generate one move probably
1451 // makes it unprofitable.
1454 // Check whether CmpInstr can be made redundant by the current instruction.
1455 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1456 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1457 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1458 ((Instr.getOperand(1).getReg() == SrcReg &&
1459 Instr.getOperand(2).getReg() == SrcReg2) ||
1460 (Instr.getOperand(1).getReg() == SrcReg2 &&
1461 Instr.getOperand(2).getReg() == SrcReg))) {
1467 // The 'and' is below the comparison instruction.
1471 // Return false if no candidates exist.
1475 // The single candidate is called MI.
1479 MIOpC = MI->getOpcode();
1480 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1483 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1484 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1488 // FIXME: On the non-embedded POWER architectures, only some of the record
1489 // forms are fast, and we should use only the fast ones.
1491 // The defining instruction has a record form (or is already a record
1492 // form). It is possible, however, that we'll need to reverse the condition
1493 // code of the users.
1497 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1498 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1500 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1501 // needs to be updated to be based on SUB. Push the condition code
1502 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1503 // condition code of these operands will be modified.
1504 bool ShouldSwap = false;
1506 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1507 Sub->getOperand(2).getReg() == SrcReg;
1509 // The operands to subf are the opposite of sub, so only in the fixed-point
1510 // case, invert the order.
1511 ShouldSwap = !ShouldSwap;
1515 for (MachineRegisterInfo::use_instr_iterator
1516 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1518 MachineInstr *UseMI = &*I;
1519 if (UseMI->getOpcode() == PPC::BCC) {
1520 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1521 assert((!equalityOnly ||
1522 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1523 "Invalid predicate for equality-only optimization");
1524 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1525 PPC::getSwappedPredicate(Pred)));
1526 } else if (UseMI->getOpcode() == PPC::ISEL ||
1527 UseMI->getOpcode() == PPC::ISEL8) {
1528 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1529 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1530 "Invalid CR bit for equality-only optimization");
1532 if (NewSubReg == PPC::sub_lt)
1533 NewSubReg = PPC::sub_gt;
1534 else if (NewSubReg == PPC::sub_gt)
1535 NewSubReg = PPC::sub_lt;
1537 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1539 } else // We need to abort on a user we don't understand.
1543 // Create a new virtual register to hold the value of the CR set by the
1544 // record-form instruction. If the instruction was not previously in
1545 // record form, then set the kill flag on the CR.
1546 CmpInstr->eraseFromParent();
1548 MachineBasicBlock::iterator MII = MI;
1549 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1550 get(TargetOpcode::COPY), CRReg)
1551 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1553 if (MIOpC != NewOpC) {
1554 // We need to be careful here: we're replacing one instruction with
1555 // another, and we need to make sure that we get all of the right
1556 // implicit uses and defs. On the other hand, the caller may be holding
1557 // an iterator to this instruction, and so we can't delete it (this is
1558 // specifically the case if this is the instruction directly after the
1561 const MCInstrDesc &NewDesc = get(NewOpC);
1562 MI->setDesc(NewDesc);
1564 if (NewDesc.ImplicitDefs)
1565 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1566 *ImpDefs; ++ImpDefs)
1567 if (!MI->definesRegister(*ImpDefs))
1568 MI->addOperand(*MI->getParent()->getParent(),
1569 MachineOperand::CreateReg(*ImpDefs, true, true));
1570 if (NewDesc.ImplicitUses)
1571 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1572 *ImpUses; ++ImpUses)
1573 if (!MI->readsRegister(*ImpUses))
1574 MI->addOperand(*MI->getParent()->getParent(),
1575 MachineOperand::CreateReg(*ImpUses, false, true));
1578 // Modify the condition code of operands in OperandsToUpdate.
1579 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1580 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1581 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1582 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1584 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1585 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1590 /// GetInstSize - Return the number of bytes of code the specified
1591 /// instruction may be. This returns the maximum number of bytes.
1593 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1594 unsigned Opcode = MI->getOpcode();
1596 if (Opcode == PPC::INLINEASM) {
1597 const MachineFunction *MF = MI->getParent()->getParent();
1598 const char *AsmStr = MI->getOperand(0).getSymbolName();
1599 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1600 } else if (Opcode == TargetOpcode::STACKMAP) {
1601 return MI->getOperand(1).getImm();
1602 } else if (Opcode == TargetOpcode::PATCHPOINT) {
1603 PatchPointOpers Opers(MI);
1604 return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
1606 const MCInstrDesc &Desc = get(Opcode);
1607 return Desc.getSize();
1612 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1615 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1616 // (Altivec and scalar floating-point registers), we need to transform the
1617 // copies into subregister copies with other restrictions.
1618 struct PPCVSXFMAMutate : public MachineFunctionPass {
1620 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1621 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1625 const PPCInstrInfo *TII;
1628 bool processBlock(MachineBasicBlock &MBB) {
1629 bool Changed = false;
1631 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1632 const TargetRegisterInfo *TRI = &TII->getRegisterInfo();
1633 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1635 MachineInstr *MI = I;
1637 // The default (A-type) VSX FMA form kills the addend (it is taken from
1638 // the target register, which is then updated to reflect the result of
1639 // the FMA). If the instruction, however, kills one of the registers
1640 // used for the product, then we can use the M-form instruction (which
1641 // will take that value from the to-be-defined register).
1643 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1647 // This pass is run after register coalescing, and so we're looking for
1648 // a situation like this:
1650 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1651 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1652 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1654 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1655 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1657 // Where we can eliminate the copy by changing from the A-type to the
1658 // M-type instruction. Specifically, for this example, this means:
1659 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1660 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1662 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1663 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1664 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1666 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1668 VNInfo *AddendValNo =
1669 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1670 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1672 // The addend and this instruction must be in the same block.
1674 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1677 // The addend must be a full copy within the same register class.
1679 if (!AddendMI->isFullCopy())
1682 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1683 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1684 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1685 MRI.getRegClass(AddendSrcReg))
1688 // If AddendSrcReg is a physical register, make sure the destination
1689 // register class contains it.
1690 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1691 ->contains(AddendSrcReg))
1695 // In theory, there could be other uses of the addend copy before this
1696 // fma. We could deal with this, but that would require additional
1697 // logic below and I suspect it will not occur in any relevant
1698 // situations. Additionally, check whether the copy source is killed
1699 // prior to the fma. In order to replace the addend here with the
1700 // source of the copy, it must still be live here. We can't use
1701 // interval testing for a physical register, so as long as we're
1702 // walking the MIs we may as well test liveness here.
1703 bool OtherUsers = false, KillsAddendSrc = false;
1704 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1706 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1710 if (J->modifiesRegister(AddendSrcReg, TRI) ||
1711 J->killsRegister(AddendSrcReg, TRI)) {
1712 KillsAddendSrc = true;
1717 if (OtherUsers || KillsAddendSrc)
1720 // Find one of the product operands that is killed by this instruction.
1722 unsigned KilledProdOp = 0, OtherProdOp = 0;
1723 if (LIS->getInterval(MI->getOperand(2).getReg())
1724 .Query(FMAIdx).isKill()) {
1727 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1728 .Query(FMAIdx).isKill()) {
1733 // If there are no killed product operands, then this transformation is
1734 // likely not profitable.
1738 // For virtual registers, verify that the addend source register
1739 // is live here (as should have been assured above).
1740 assert((!TargetRegisterInfo::isVirtualRegister(AddendSrcReg) ||
1741 LIS->getInterval(AddendSrcReg).liveAt(FMAIdx)) &&
1742 "Addend source register is not live!");
1744 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1746 unsigned AddReg = AddendMI->getOperand(1).getReg();
1747 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1748 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1750 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1751 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1752 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1754 bool AddRegKill = AddendMI->getOperand(1).isKill();
1755 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1756 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1758 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1759 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1760 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1762 unsigned OldFMAReg = MI->getOperand(0).getReg();
1764 // The transformation doesn't work well with things like:
1765 // %vreg5 = A-form-op %vreg5, %vreg11, %vreg5;
1766 // so leave such things alone.
1767 if (OldFMAReg == KilledProdReg)
1770 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1771 "Addend copy not tied to old FMA output!");
1773 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1775 MI->getOperand(0).setReg(KilledProdReg);
1776 MI->getOperand(1).setReg(KilledProdReg);
1777 MI->getOperand(3).setReg(AddReg);
1778 MI->getOperand(2).setReg(OtherProdReg);
1780 MI->getOperand(0).setSubReg(KilledProdSubReg);
1781 MI->getOperand(1).setSubReg(KilledProdSubReg);
1782 MI->getOperand(3).setSubReg(AddSubReg);
1783 MI->getOperand(2).setSubReg(OtherProdSubReg);
1785 MI->getOperand(1).setIsKill(KilledProdRegKill);
1786 MI->getOperand(3).setIsKill(AddRegKill);
1787 MI->getOperand(2).setIsKill(OtherProdRegKill);
1789 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1790 MI->getOperand(3).setIsUndef(AddRegUndef);
1791 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1793 MI->setDesc(TII->get(AltOpc));
1795 DEBUG(dbgs() << " -> " << *MI);
1797 // The killed product operand was killed here, so we can reuse it now
1798 // for the result of the fma.
1800 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1801 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1802 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1804 MachineOperand &UseMO = *UI;
1805 MachineInstr *UseMI = UseMO.getParent();
1808 // Don't replace the result register of the copy we're about to erase.
1809 if (UseMI == AddendMI)
1812 UseMO.setReg(KilledProdReg);
1813 UseMO.setSubReg(KilledProdSubReg);
1816 // Extend the live intervals of the killed product operand to hold the
1819 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1820 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1822 // Don't add the segment that corresponds to the original copy.
1823 if (AI->valno == AddendValNo)
1826 VNInfo *NewFMAValNo =
1827 NewFMAInt.getNextValue(AI->start,
1828 LIS->getVNInfoAllocator());
1830 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1833 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1835 FMAInt.removeValNo(FMAValNo);
1836 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1838 // Remove the (now unused) copy.
1840 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1841 LIS->RemoveMachineInstrFromMaps(AddendMI);
1842 AddendMI->eraseFromParent();
1851 bool runOnMachineFunction(MachineFunction &MF) override {
1852 // If we don't have VSX then go ahead and return without doing
1854 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
1858 LIS = &getAnalysis<LiveIntervals>();
1860 TII = STI.getInstrInfo();
1862 bool Changed = false;
1864 if (DisableVSXFMAMutate)
1867 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1868 MachineBasicBlock &B = *I++;
1869 if (processBlock(B))
1876 void getAnalysisUsage(AnalysisUsage &AU) const override {
1877 AU.addRequired<LiveIntervals>();
1878 AU.addPreserved<LiveIntervals>();
1879 AU.addRequired<SlotIndexes>();
1880 AU.addPreserved<SlotIndexes>();
1881 MachineFunctionPass::getAnalysisUsage(AU);
1886 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1887 "PowerPC VSX FMA Mutation", false, false)
1888 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1889 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1890 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1891 "PowerPC VSX FMA Mutation", false, false)
1893 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1895 char PPCVSXFMAMutate::ID = 0;
1897 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1900 #define DEBUG_TYPE "ppc-vsx-copy"
1903 void initializePPCVSXCopyPass(PassRegistry&);
1907 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1908 // (Altivec and scalar floating-point registers), we need to transform the
1909 // copies into subregister copies with other restrictions.
1910 struct PPCVSXCopy : public MachineFunctionPass {
1912 PPCVSXCopy() : MachineFunctionPass(ID) {
1913 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1916 const TargetInstrInfo *TII;
1918 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1919 MachineRegisterInfo &MRI) {
1920 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1921 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1922 } else if (RC->contains(Reg)) {
1929 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1930 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1933 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1934 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1937 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1938 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1942 bool processBlock(MachineBasicBlock &MBB) {
1943 bool Changed = false;
1945 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1946 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1948 MachineInstr *MI = I;
1949 if (!MI->isFullCopy())
1952 MachineOperand &DstMO = MI->getOperand(0);
1953 MachineOperand &SrcMO = MI->getOperand(1);
1955 if ( IsVSReg(DstMO.getReg(), MRI) &&
1956 !IsVSReg(SrcMO.getReg(), MRI)) {
1957 // This is a copy *to* a VSX register from a non-VSX register.
1960 const TargetRegisterClass *SrcRC =
1961 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1962 &PPC::VSLRCRegClass;
1963 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1964 IsVRReg(SrcMO.getReg(), MRI)) &&
1965 "Unknown source for a VSX copy");
1967 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1968 BuildMI(MBB, MI, MI->getDebugLoc(),
1969 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1970 .addImm(1) // add 1, not 0, because there is no implicit clearing
1971 // of the high bits.
1973 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1976 // The source of the original copy is now the new virtual register.
1977 SrcMO.setReg(NewVReg);
1978 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1979 IsVSReg(SrcMO.getReg(), MRI)) {
1980 // This is a copy *from* a VSX register to a non-VSX register.
1983 const TargetRegisterClass *DstRC =
1984 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1985 &PPC::VSLRCRegClass;
1986 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1987 IsVRReg(DstMO.getReg(), MRI)) &&
1988 "Unknown destination for a VSX copy");
1990 // Copy the VSX value into a new VSX register of the correct subclass.
1991 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1992 BuildMI(MBB, MI, MI->getDebugLoc(),
1993 TII->get(TargetOpcode::COPY), NewVReg)
1996 // Transform the original copy into a subregister extraction copy.
1997 SrcMO.setReg(NewVReg);
1998 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
2007 bool runOnMachineFunction(MachineFunction &MF) override {
2008 // If we don't have VSX on the subtarget, don't do anything.
2009 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
2012 TII = STI.getInstrInfo();
2014 bool Changed = false;
2016 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2017 MachineBasicBlock &B = *I++;
2018 if (processBlock(B))
2025 void getAnalysisUsage(AnalysisUsage &AU) const override {
2026 MachineFunctionPass::getAnalysisUsage(AU);
2031 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
2032 "PowerPC VSX Copy Legalization", false, false)
2034 char PPCVSXCopy::ID = 0;
2036 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2039 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2042 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2046 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2047 // registers (mostly because the ABI code still places all values into the
2048 // "traditional" floating-point and vector registers). Remove them here.
2049 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2051 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2052 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2055 const TargetInstrInfo *TII;
2058 bool processBlock(MachineBasicBlock &MBB) {
2059 bool Changed = false;
2061 SmallVector<MachineInstr *, 4> ToDelete;
2062 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2064 MachineInstr *MI = I;
2065 if (MI->getOpcode() == PPC::XXLOR &&
2066 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2067 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2068 ToDelete.push_back(MI);
2071 if (!ToDelete.empty())
2074 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2075 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2076 ToDelete[i]->eraseFromParent();
2083 bool runOnMachineFunction(MachineFunction &MF) override {
2084 // If we don't have VSX don't bother doing anything here.
2085 const PPCSubtarget &STI = MF.getSubtarget<PPCSubtarget>();
2088 TII = STI.getInstrInfo();
2090 bool Changed = false;
2092 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2093 MachineBasicBlock &B = *I++;
2094 if (processBlock(B))
2101 void getAnalysisUsage(AnalysisUsage &AU) const override {
2102 MachineFunctionPass::getAnalysisUsage(AU);
2107 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2108 "PowerPC VSX Copy Cleanup", false, false)
2110 char PPCVSXCopyCleanup::ID = 0;
2112 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2115 #define DEBUG_TYPE "ppc-early-ret"
2116 STATISTIC(NumBCLR, "Number of early conditional returns");
2117 STATISTIC(NumBLR, "Number of early returns");
2120 void initializePPCEarlyReturnPass(PassRegistry&);
2124 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2125 // returns up, and create conditional returns, to avoid unnecessary
2126 // branch-to-blr sequences.
2127 struct PPCEarlyReturn : public MachineFunctionPass {
2129 PPCEarlyReturn() : MachineFunctionPass(ID) {
2130 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2133 const TargetInstrInfo *TII;
2136 bool processBlock(MachineBasicBlock &ReturnMBB) {
2137 bool Changed = false;
2139 MachineBasicBlock::iterator I = ReturnMBB.begin();
2140 I = ReturnMBB.SkipPHIsAndLabels(I);
2142 // The block must be essentially empty except for the blr.
2143 if (I == ReturnMBB.end() ||
2144 (I->getOpcode() != PPC::BLR && I->getOpcode() != PPC::BLR8) ||
2145 I != ReturnMBB.getLastNonDebugInstr())
2148 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2149 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2150 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2151 bool OtherReference = false, BlockChanged = false;
2152 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2153 MachineInstrBuilder MIB;
2154 if (J->getOpcode() == PPC::B) {
2155 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2156 // This is an unconditional branch to the return. Replace the
2157 // branch with a blr.
2159 BuildMI(**PI, J, J->getDebugLoc(), TII->get(I->getOpcode()));
2160 MIB.copyImplicitOps(I);
2161 MachineBasicBlock::iterator K = J--;
2162 K->eraseFromParent();
2163 BlockChanged = true;
2167 } else if (J->getOpcode() == PPC::BCC) {
2168 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2169 // This is a conditional branch to the return. Replace the branch
2171 MIB = BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2172 .addImm(J->getOperand(0).getImm())
2173 .addReg(J->getOperand(1).getReg());
2174 MIB.copyImplicitOps(I);
2175 MachineBasicBlock::iterator K = J--;
2176 K->eraseFromParent();
2177 BlockChanged = true;
2181 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2182 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2183 // This is a conditional branch to the return. Replace the branch
2185 MIB = BuildMI(**PI, J, J->getDebugLoc(),
2186 TII->get(J->getOpcode() == PPC::BC ?
2187 PPC::BCLR : PPC::BCLRn))
2188 .addReg(J->getOperand(0).getReg());
2189 MIB.copyImplicitOps(I);
2190 MachineBasicBlock::iterator K = J--;
2191 K->eraseFromParent();
2192 BlockChanged = true;
2196 } else if (J->isBranch()) {
2197 if (J->isIndirectBranch()) {
2198 if (ReturnMBB.hasAddressTaken())
2199 OtherReference = true;
2201 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2202 if (J->getOperand(i).isMBB() &&
2203 J->getOperand(i).getMBB() == &ReturnMBB)
2204 OtherReference = true;
2205 } else if (!J->isTerminator() && !J->isDebugValue())
2208 if (J == (*PI)->begin())
2214 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2215 OtherReference = true;
2217 // Predecessors are stored in a vector and can't be removed here.
2218 if (!OtherReference && BlockChanged) {
2219 PredToRemove.push_back(*PI);
2226 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2227 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2229 if (Changed && !ReturnMBB.hasAddressTaken()) {
2230 // We now might be able to merge this blr-only block into its
2231 // by-layout predecessor.
2232 if (ReturnMBB.pred_size() == 1 &&
2233 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2234 // Move the blr into the preceding block.
2235 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2236 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2237 PrevMBB.removeSuccessor(&ReturnMBB);
2240 if (ReturnMBB.pred_empty())
2241 ReturnMBB.eraseFromParent();
2248 bool runOnMachineFunction(MachineFunction &MF) override {
2249 TII = MF.getSubtarget().getInstrInfo();
2251 bool Changed = false;
2253 // If the function does not have at least two blocks, then there is
2258 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2259 MachineBasicBlock &B = *I++;
2260 if (processBlock(B))
2267 void getAnalysisUsage(AnalysisUsage &AU) const override {
2268 MachineFunctionPass::getAnalysisUsage(AU);
2273 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2274 "PowerPC Early-Return Creation", false, false)
2276 char PPCEarlyReturn::ID = 0;
2278 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }