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/MC/MCAsmInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "ppc-instr-info"
43 #define GET_INSTRMAP_INFO
44 #define GET_INSTRINFO_CTOR_DTOR
45 #include "PPCGenInstrInfo.inc"
48 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
49 cl::desc("Disable analysis for CTR loops"));
51 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
52 cl::desc("Disable compare instruction optimization"), cl::Hidden);
54 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
55 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
57 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
58 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
61 // Pin the vtable to this file.
62 void PPCInstrInfo::anchor() {}
64 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
65 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
66 Subtarget(STI), RI(STI) {}
68 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
69 /// this target when scheduling the DAG.
70 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
71 const TargetMachine *TM,
72 const ScheduleDAG *DAG) const {
73 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
74 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
75 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
76 const InstrItineraryData *II = TM->getInstrItineraryData();
77 return new ScoreboardHazardRecognizer(II, DAG);
80 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
83 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
84 /// to use for this target when scheduling the DAG.
85 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
86 const InstrItineraryData *II,
87 const ScheduleDAG *DAG) const {
89 DAG->TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
91 if (Directive == PPC::DIR_PWR7)
92 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
94 // Most subtargets use a PPC970 recognizer.
95 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
96 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
97 assert(DAG->TII && "No InstrInfo?");
99 return new PPCHazardRecognizer970(*DAG);
102 return new ScoreboardHazardRecognizer(II, DAG);
106 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
107 const MachineInstr *DefMI, unsigned DefIdx,
108 const MachineInstr *UseMI,
109 unsigned UseIdx) const {
110 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
113 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
114 unsigned Reg = DefMO.getReg();
116 const TargetRegisterInfo *TRI = &getRegisterInfo();
118 if (TRI->isVirtualRegister(Reg)) {
119 const MachineRegisterInfo *MRI =
120 &DefMI->getParent()->getParent()->getRegInfo();
121 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
122 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
124 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
125 PPC::CRBITRCRegClass.contains(Reg);
128 if (UseMI->isBranch() && IsRegCR) {
130 Latency = getInstrLatency(ItinData, DefMI);
132 // On some cores, there is an additional delay between writing to a condition
133 // register, and using it from a branch.
134 unsigned Directive = Subtarget.getDarwinDirective();
155 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
156 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
157 unsigned &SrcReg, unsigned &DstReg,
158 unsigned &SubIdx) const {
159 switch (MI.getOpcode()) {
160 default: return false;
162 case PPC::EXTSW_32_64:
163 SrcReg = MI.getOperand(1).getReg();
164 DstReg = MI.getOperand(0).getReg();
165 SubIdx = PPC::sub_32;
170 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
171 int &FrameIndex) const {
172 // Note: This list must be kept consistent with LoadRegFromStackSlot.
173 switch (MI->getOpcode()) {
179 case PPC::RESTORE_CR:
180 case PPC::RESTORE_CRBIT:
183 case PPC::RESTORE_VRSAVE:
184 // Check for the operands added by addFrameReference (the immediate is the
185 // offset which defaults to 0).
186 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
187 MI->getOperand(2).isFI()) {
188 FrameIndex = MI->getOperand(2).getIndex();
189 return MI->getOperand(0).getReg();
196 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
197 int &FrameIndex) const {
198 // Note: This list must be kept consistent with StoreRegToStackSlot.
199 switch (MI->getOpcode()) {
206 case PPC::SPILL_CRBIT:
209 case PPC::SPILL_VRSAVE:
210 // Check for the operands added by addFrameReference (the immediate is the
211 // offset which defaults to 0).
212 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
213 MI->getOperand(2).isFI()) {
214 FrameIndex = MI->getOperand(2).getIndex();
215 return MI->getOperand(0).getReg();
222 // commuteInstruction - We can commute rlwimi instructions, but only if the
223 // rotate amt is zero. We also have to munge the immediates a bit.
225 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
226 MachineFunction &MF = *MI->getParent()->getParent();
228 // Normal instructions can be commuted the obvious way.
229 if (MI->getOpcode() != PPC::RLWIMI &&
230 MI->getOpcode() != PPC::RLWIMIo &&
231 MI->getOpcode() != PPC::RLWIMI8 &&
232 MI->getOpcode() != PPC::RLWIMI8o)
233 return TargetInstrInfo::commuteInstruction(MI, NewMI);
235 // Cannot commute if it has a non-zero rotate count.
236 if (MI->getOperand(3).getImm() != 0)
239 // If we have a zero rotate count, we have:
241 // Op0 = (Op1 & ~M) | (Op2 & M)
243 // M = mask((ME+1)&31, (MB-1)&31)
244 // Op0 = (Op2 & ~M) | (Op1 & M)
247 unsigned Reg0 = MI->getOperand(0).getReg();
248 unsigned Reg1 = MI->getOperand(1).getReg();
249 unsigned Reg2 = MI->getOperand(2).getReg();
250 unsigned SubReg1 = MI->getOperand(1).getSubReg();
251 unsigned SubReg2 = MI->getOperand(2).getSubReg();
252 bool Reg1IsKill = MI->getOperand(1).isKill();
253 bool Reg2IsKill = MI->getOperand(2).isKill();
254 bool ChangeReg0 = false;
255 // If machine instrs are no longer in two-address forms, update
256 // destination register as well.
258 // Must be two address instruction!
259 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
260 "Expecting a two-address instruction!");
261 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
267 unsigned MB = MI->getOperand(4).getImm();
268 unsigned ME = MI->getOperand(5).getImm();
271 // Create a new instruction.
272 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
273 bool Reg0IsDead = MI->getOperand(0).isDead();
274 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
275 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
276 .addReg(Reg2, getKillRegState(Reg2IsKill))
277 .addReg(Reg1, getKillRegState(Reg1IsKill))
279 .addImm((MB-1) & 31);
283 MI->getOperand(0).setReg(Reg2);
284 MI->getOperand(0).setSubReg(SubReg2);
286 MI->getOperand(2).setReg(Reg1);
287 MI->getOperand(1).setReg(Reg2);
288 MI->getOperand(2).setSubReg(SubReg1);
289 MI->getOperand(1).setSubReg(SubReg2);
290 MI->getOperand(2).setIsKill(Reg1IsKill);
291 MI->getOperand(1).setIsKill(Reg2IsKill);
293 // Swap the mask around.
294 MI->getOperand(4).setImm((ME+1) & 31);
295 MI->getOperand(5).setImm((MB-1) & 31);
299 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
300 unsigned &SrcOpIdx2) const {
301 // For VSX A-Type FMA instructions, it is the first two operands that can be
302 // commuted, however, because the non-encoded tied input operand is listed
303 // first, the operands to swap are actually the second and third.
305 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
307 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
314 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
315 MachineBasicBlock::iterator MI) const {
316 // This function is used for scheduling, and the nop wanted here is the type
317 // that terminates dispatch groups on the POWER cores.
318 unsigned Directive = Subtarget.getDarwinDirective();
321 default: Opcode = PPC::NOP; break;
322 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
323 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
327 BuildMI(MBB, MI, DL, get(Opcode));
331 // Note: If the condition register is set to CTR or CTR8 then this is a
332 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
333 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
334 MachineBasicBlock *&FBB,
335 SmallVectorImpl<MachineOperand> &Cond,
336 bool AllowModify) const {
337 bool isPPC64 = Subtarget.isPPC64();
339 // If the block has no terminators, it just falls into the block after it.
340 MachineBasicBlock::iterator I = MBB.end();
341 if (I == MBB.begin())
344 while (I->isDebugValue()) {
345 if (I == MBB.begin())
349 if (!isUnpredicatedTerminator(I))
352 // Get the last instruction in the block.
353 MachineInstr *LastInst = I;
355 // If there is only one terminator instruction, process it.
356 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
357 if (LastInst->getOpcode() == PPC::B) {
358 if (!LastInst->getOperand(0).isMBB())
360 TBB = LastInst->getOperand(0).getMBB();
362 } else if (LastInst->getOpcode() == PPC::BCC) {
363 if (!LastInst->getOperand(2).isMBB())
365 // Block ends with fall-through condbranch.
366 TBB = LastInst->getOperand(2).getMBB();
367 Cond.push_back(LastInst->getOperand(0));
368 Cond.push_back(LastInst->getOperand(1));
370 } else if (LastInst->getOpcode() == PPC::BC) {
371 if (!LastInst->getOperand(1).isMBB())
373 // Block ends with fall-through condbranch.
374 TBB = LastInst->getOperand(1).getMBB();
375 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
376 Cond.push_back(LastInst->getOperand(0));
378 } else if (LastInst->getOpcode() == PPC::BCn) {
379 if (!LastInst->getOperand(1).isMBB())
381 // Block ends with fall-through condbranch.
382 TBB = LastInst->getOperand(1).getMBB();
383 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
384 Cond.push_back(LastInst->getOperand(0));
386 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
387 LastInst->getOpcode() == PPC::BDNZ) {
388 if (!LastInst->getOperand(0).isMBB())
390 if (DisableCTRLoopAnal)
392 TBB = LastInst->getOperand(0).getMBB();
393 Cond.push_back(MachineOperand::CreateImm(1));
394 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
397 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
398 LastInst->getOpcode() == PPC::BDZ) {
399 if (!LastInst->getOperand(0).isMBB())
401 if (DisableCTRLoopAnal)
403 TBB = LastInst->getOperand(0).getMBB();
404 Cond.push_back(MachineOperand::CreateImm(0));
405 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
410 // Otherwise, don't know what this is.
414 // Get the instruction before it if it's a terminator.
415 MachineInstr *SecondLastInst = I;
417 // If there are three terminators, we don't know what sort of block this is.
418 if (SecondLastInst && I != MBB.begin() &&
419 isUnpredicatedTerminator(--I))
422 // If the block ends with PPC::B and PPC:BCC, handle it.
423 if (SecondLastInst->getOpcode() == PPC::BCC &&
424 LastInst->getOpcode() == PPC::B) {
425 if (!SecondLastInst->getOperand(2).isMBB() ||
426 !LastInst->getOperand(0).isMBB())
428 TBB = SecondLastInst->getOperand(2).getMBB();
429 Cond.push_back(SecondLastInst->getOperand(0));
430 Cond.push_back(SecondLastInst->getOperand(1));
431 FBB = LastInst->getOperand(0).getMBB();
433 } else if (SecondLastInst->getOpcode() == PPC::BC &&
434 LastInst->getOpcode() == PPC::B) {
435 if (!SecondLastInst->getOperand(1).isMBB() ||
436 !LastInst->getOperand(0).isMBB())
438 TBB = SecondLastInst->getOperand(1).getMBB();
439 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
440 Cond.push_back(SecondLastInst->getOperand(0));
441 FBB = LastInst->getOperand(0).getMBB();
443 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
444 LastInst->getOpcode() == PPC::B) {
445 if (!SecondLastInst->getOperand(1).isMBB() ||
446 !LastInst->getOperand(0).isMBB())
448 TBB = SecondLastInst->getOperand(1).getMBB();
449 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
450 Cond.push_back(SecondLastInst->getOperand(0));
451 FBB = LastInst->getOperand(0).getMBB();
453 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
454 SecondLastInst->getOpcode() == PPC::BDNZ) &&
455 LastInst->getOpcode() == PPC::B) {
456 if (!SecondLastInst->getOperand(0).isMBB() ||
457 !LastInst->getOperand(0).isMBB())
459 if (DisableCTRLoopAnal)
461 TBB = SecondLastInst->getOperand(0).getMBB();
462 Cond.push_back(MachineOperand::CreateImm(1));
463 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
465 FBB = LastInst->getOperand(0).getMBB();
467 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
468 SecondLastInst->getOpcode() == PPC::BDZ) &&
469 LastInst->getOpcode() == PPC::B) {
470 if (!SecondLastInst->getOperand(0).isMBB() ||
471 !LastInst->getOperand(0).isMBB())
473 if (DisableCTRLoopAnal)
475 TBB = SecondLastInst->getOperand(0).getMBB();
476 Cond.push_back(MachineOperand::CreateImm(0));
477 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
479 FBB = LastInst->getOperand(0).getMBB();
483 // If the block ends with two PPC:Bs, handle it. The second one is not
484 // executed, so remove it.
485 if (SecondLastInst->getOpcode() == PPC::B &&
486 LastInst->getOpcode() == PPC::B) {
487 if (!SecondLastInst->getOperand(0).isMBB())
489 TBB = SecondLastInst->getOperand(0).getMBB();
492 I->eraseFromParent();
496 // Otherwise, can't handle this.
500 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
501 MachineBasicBlock::iterator I = MBB.end();
502 if (I == MBB.begin()) return 0;
504 while (I->isDebugValue()) {
505 if (I == MBB.begin())
509 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
510 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
511 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
512 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
515 // Remove the branch.
516 I->eraseFromParent();
520 if (I == MBB.begin()) return 1;
522 if (I->getOpcode() != PPC::BCC &&
523 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
524 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
525 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
528 // Remove the branch.
529 I->eraseFromParent();
534 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
535 MachineBasicBlock *FBB,
536 const SmallVectorImpl<MachineOperand> &Cond,
538 // Shouldn't be a fall through.
539 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
540 assert((Cond.size() == 2 || Cond.size() == 0) &&
541 "PPC branch conditions have two components!");
543 bool isPPC64 = Subtarget.isPPC64();
547 if (Cond.empty()) // Unconditional branch
548 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
549 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
550 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
551 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
552 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
553 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
554 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
555 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
556 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
557 else // Conditional branch
558 BuildMI(&MBB, DL, get(PPC::BCC))
559 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
563 // Two-way Conditional Branch.
564 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
565 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
566 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
567 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
568 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
569 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
570 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
571 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
573 BuildMI(&MBB, DL, get(PPC::BCC))
574 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
575 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
580 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
581 const SmallVectorImpl<MachineOperand> &Cond,
582 unsigned TrueReg, unsigned FalseReg,
583 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
584 if (!Subtarget.hasISEL())
587 if (Cond.size() != 2)
590 // If this is really a bdnz-like condition, then it cannot be turned into a
592 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
595 // Check register classes.
596 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
597 const TargetRegisterClass *RC =
598 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
602 // isel is for regular integer GPRs only.
603 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
604 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
605 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
606 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
609 // FIXME: These numbers are for the A2, how well they work for other cores is
610 // an open question. On the A2, the isel instruction has a 2-cycle latency
611 // but single-cycle throughput. These numbers are used in combination with
612 // the MispredictPenalty setting from the active SchedMachineModel.
620 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
621 MachineBasicBlock::iterator MI, DebugLoc dl,
623 const SmallVectorImpl<MachineOperand> &Cond,
624 unsigned TrueReg, unsigned FalseReg) const {
625 assert(Cond.size() == 2 &&
626 "PPC branch conditions have two components!");
628 assert(Subtarget.hasISEL() &&
629 "Cannot insert select on target without ISEL support");
631 // Get the register classes.
632 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
633 const TargetRegisterClass *RC =
634 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
635 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
637 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
638 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
640 PPC::GPRCRegClass.hasSubClassEq(RC) ||
641 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
642 "isel is for regular integer GPRs only");
644 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
645 unsigned SelectPred = Cond[0].getImm();
649 switch (SelectPred) {
650 default: llvm_unreachable("invalid predicate for isel");
651 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
652 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
653 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
654 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
655 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
656 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
657 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
658 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
659 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
660 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
663 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
664 SecondReg = SwapOps ? TrueReg : FalseReg;
666 // The first input register of isel cannot be r0. If it is a member
667 // of a register class that can be r0, then copy it first (the
668 // register allocator should eliminate the copy).
669 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
670 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
671 const TargetRegisterClass *FirstRC =
672 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
673 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
674 unsigned OldFirstReg = FirstReg;
675 FirstReg = MRI.createVirtualRegister(FirstRC);
676 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
677 .addReg(OldFirstReg);
680 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
681 .addReg(FirstReg).addReg(SecondReg)
682 .addReg(Cond[1].getReg(), 0, SubIdx);
685 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
686 MachineBasicBlock::iterator I, DebugLoc DL,
687 unsigned DestReg, unsigned SrcReg,
688 bool KillSrc) const {
689 // We can end up with self copies and similar things as a result of VSX copy
690 // legalization. Promote them here.
691 const TargetRegisterInfo *TRI = &getRegisterInfo();
692 if (PPC::F8RCRegClass.contains(DestReg) &&
693 PPC::VSLRCRegClass.contains(SrcReg)) {
695 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
697 if (VSXSelfCopyCrash && SrcReg == SuperReg)
698 llvm_unreachable("nop VSX copy");
701 } else if (PPC::VRRCRegClass.contains(DestReg) &&
702 PPC::VSHRCRegClass.contains(SrcReg)) {
704 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
706 if (VSXSelfCopyCrash && SrcReg == SuperReg)
707 llvm_unreachable("nop VSX copy");
710 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
711 PPC::VSLRCRegClass.contains(DestReg)) {
713 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
715 if (VSXSelfCopyCrash && DestReg == SuperReg)
716 llvm_unreachable("nop VSX copy");
719 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
720 PPC::VSHRCRegClass.contains(DestReg)) {
722 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
724 if (VSXSelfCopyCrash && DestReg == SuperReg)
725 llvm_unreachable("nop VSX copy");
731 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
733 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
735 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
737 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
739 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
741 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
742 // There are two different ways this can be done:
743 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
744 // issue in VSU pipeline 0.
745 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
746 // can go to either pipeline.
747 // We'll always use xxlor here, because in practically all cases where
748 // copies are generated, they are close enough to some use that the
749 // lower-latency form is preferable.
751 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
753 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
756 llvm_unreachable("Impossible reg-to-reg copy");
758 const MCInstrDesc &MCID = get(Opc);
759 if (MCID.getNumOperands() == 3)
760 BuildMI(MBB, I, DL, MCID, DestReg)
761 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
763 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
766 // This function returns true if a CR spill is necessary and false otherwise.
768 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
769 unsigned SrcReg, bool isKill,
771 const TargetRegisterClass *RC,
772 SmallVectorImpl<MachineInstr*> &NewMIs,
773 bool &NonRI, bool &SpillsVRS) const{
774 // Note: If additional store instructions are added here,
775 // update isStoreToStackSlot.
778 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
779 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
780 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
782 getKillRegState(isKill)),
784 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
785 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
786 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
788 getKillRegState(isKill)),
790 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
791 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
793 getKillRegState(isKill)),
795 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
796 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
798 getKillRegState(isKill)),
800 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
801 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
803 getKillRegState(isKill)),
806 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
807 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
809 getKillRegState(isKill)),
812 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
813 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
815 getKillRegState(isKill)),
818 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
819 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
821 getKillRegState(isKill)),
824 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
825 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
827 getKillRegState(isKill)),
830 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
831 assert(Subtarget.isDarwin() &&
832 "VRSAVE only needs spill/restore on Darwin");
833 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
835 getKillRegState(isKill)),
839 llvm_unreachable("Unknown regclass!");
846 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
847 MachineBasicBlock::iterator MI,
848 unsigned SrcReg, bool isKill, int FrameIdx,
849 const TargetRegisterClass *RC,
850 const TargetRegisterInfo *TRI) const {
851 MachineFunction &MF = *MBB.getParent();
852 SmallVector<MachineInstr*, 4> NewMIs;
854 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
855 FuncInfo->setHasSpills();
857 bool NonRI = false, SpillsVRS = false;
858 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
860 FuncInfo->setSpillsCR();
863 FuncInfo->setSpillsVRSAVE();
866 FuncInfo->setHasNonRISpills();
868 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
869 MBB.insert(MI, NewMIs[i]);
871 const MachineFrameInfo &MFI = *MF.getFrameInfo();
872 MachineMemOperand *MMO =
873 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
874 MachineMemOperand::MOStore,
875 MFI.getObjectSize(FrameIdx),
876 MFI.getObjectAlignment(FrameIdx));
877 NewMIs.back()->addMemOperand(MF, MMO);
881 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
882 unsigned DestReg, int FrameIdx,
883 const TargetRegisterClass *RC,
884 SmallVectorImpl<MachineInstr*> &NewMIs,
885 bool &NonRI, bool &SpillsVRS) const{
886 // Note: If additional load instructions are added here,
887 // update isLoadFromStackSlot.
889 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
890 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
891 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
892 DestReg), FrameIdx));
893 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
894 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
895 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
897 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
898 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
900 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
901 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
903 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
904 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
905 get(PPC::RESTORE_CR), DestReg),
908 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
909 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
910 get(PPC::RESTORE_CRBIT), DestReg),
913 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
914 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
917 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
918 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
921 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
922 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
925 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
926 assert(Subtarget.isDarwin() &&
927 "VRSAVE only needs spill/restore on Darwin");
928 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
929 get(PPC::RESTORE_VRSAVE),
934 llvm_unreachable("Unknown regclass!");
941 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
942 MachineBasicBlock::iterator MI,
943 unsigned DestReg, int FrameIdx,
944 const TargetRegisterClass *RC,
945 const TargetRegisterInfo *TRI) const {
946 MachineFunction &MF = *MBB.getParent();
947 SmallVector<MachineInstr*, 4> NewMIs;
949 if (MI != MBB.end()) DL = MI->getDebugLoc();
951 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
952 FuncInfo->setHasSpills();
954 bool NonRI = false, SpillsVRS = false;
955 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
957 FuncInfo->setSpillsCR();
960 FuncInfo->setSpillsVRSAVE();
963 FuncInfo->setHasNonRISpills();
965 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
966 MBB.insert(MI, NewMIs[i]);
968 const MachineFrameInfo &MFI = *MF.getFrameInfo();
969 MachineMemOperand *MMO =
970 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
971 MachineMemOperand::MOLoad,
972 MFI.getObjectSize(FrameIdx),
973 MFI.getObjectAlignment(FrameIdx));
974 NewMIs.back()->addMemOperand(MF, MMO);
978 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
979 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
980 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
981 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
983 // Leave the CR# the same, but invert the condition.
984 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
988 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
989 unsigned Reg, MachineRegisterInfo *MRI) const {
990 // For some instructions, it is legal to fold ZERO into the RA register field.
991 // A zero immediate should always be loaded with a single li.
992 unsigned DefOpc = DefMI->getOpcode();
993 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
995 if (!DefMI->getOperand(1).isImm())
997 if (DefMI->getOperand(1).getImm() != 0)
1000 // Note that we cannot here invert the arguments of an isel in order to fold
1001 // a ZERO into what is presented as the second argument. All we have here
1002 // is the condition bit, and that might come from a CR-logical bit operation.
1004 const MCInstrDesc &UseMCID = UseMI->getDesc();
1006 // Only fold into real machine instructions.
1007 if (UseMCID.isPseudo())
1011 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1012 if (UseMI->getOperand(UseIdx).isReg() &&
1013 UseMI->getOperand(UseIdx).getReg() == Reg)
1016 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1017 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1019 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1021 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1022 // register (which might also be specified as a pointer class kind).
1023 if (UseInfo->isLookupPtrRegClass()) {
1024 if (UseInfo->RegClass /* Kind */ != 1)
1027 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1028 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1032 // Make sure this is not tied to an output register (or otherwise
1033 // constrained). This is true for ST?UX registers, for example, which
1034 // are tied to their output registers.
1035 if (UseInfo->Constraints != 0)
1039 if (UseInfo->isLookupPtrRegClass()) {
1040 bool isPPC64 = Subtarget.isPPC64();
1041 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1043 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1044 PPC::ZERO8 : PPC::ZERO;
1047 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1048 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1051 DefMI->eraseFromParent();
1056 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1057 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1059 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1064 // We should make sure that, if we're going to predicate both sides of a
1065 // condition (a diamond), that both sides don't define the counter register. We
1066 // can predicate counter-decrement-based branches, but while that predicates
1067 // the branching, it does not predicate the counter decrement. If we tried to
1068 // merge the triangle into one predicated block, we'd decrement the counter
1070 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1071 unsigned NumT, unsigned ExtraT,
1072 MachineBasicBlock &FMBB,
1073 unsigned NumF, unsigned ExtraF,
1074 const BranchProbability &Probability) const {
1075 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1079 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1080 // The predicated branches are identified by their type, not really by the
1081 // explicit presence of a predicate. Furthermore, some of them can be
1082 // predicated more than once. Because if conversion won't try to predicate
1083 // any instruction which already claims to be predicated (by returning true
1084 // here), always return false. In doing so, we let isPredicable() be the
1085 // final word on whether not the instruction can be (further) predicated.
1090 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1091 if (!MI->isTerminator())
1094 // Conditional branch is a special case.
1095 if (MI->isBranch() && !MI->isBarrier())
1098 return !isPredicated(MI);
1101 bool PPCInstrInfo::PredicateInstruction(
1103 const SmallVectorImpl<MachineOperand> &Pred) const {
1104 unsigned OpC = MI->getOpcode();
1105 if (OpC == PPC::BLR) {
1106 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1107 bool isPPC64 = Subtarget.isPPC64();
1108 MI->setDesc(get(Pred[0].getImm() ?
1109 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1110 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1111 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1112 MI->setDesc(get(PPC::BCLR));
1113 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1114 .addReg(Pred[1].getReg());
1115 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1116 MI->setDesc(get(PPC::BCLRn));
1117 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1118 .addReg(Pred[1].getReg());
1120 MI->setDesc(get(PPC::BCCLR));
1121 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1122 .addImm(Pred[0].getImm())
1123 .addReg(Pred[1].getReg());
1127 } else if (OpC == PPC::B) {
1128 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1129 bool isPPC64 = Subtarget.isPPC64();
1130 MI->setDesc(get(Pred[0].getImm() ?
1131 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1132 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1133 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1134 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1135 MI->RemoveOperand(0);
1137 MI->setDesc(get(PPC::BC));
1138 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1139 .addReg(Pred[1].getReg())
1141 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1142 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1143 MI->RemoveOperand(0);
1145 MI->setDesc(get(PPC::BCn));
1146 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1147 .addReg(Pred[1].getReg())
1150 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1151 MI->RemoveOperand(0);
1153 MI->setDesc(get(PPC::BCC));
1154 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1155 .addImm(Pred[0].getImm())
1156 .addReg(Pred[1].getReg())
1161 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1162 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1163 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1164 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1166 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1167 bool isPPC64 = Subtarget.isPPC64();
1169 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1170 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1171 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1172 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1173 .addReg(Pred[1].getReg());
1175 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1176 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1177 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1178 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1179 .addReg(Pred[1].getReg());
1183 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1184 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1185 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1186 .addImm(Pred[0].getImm())
1187 .addReg(Pred[1].getReg());
1194 bool PPCInstrInfo::SubsumesPredicate(
1195 const SmallVectorImpl<MachineOperand> &Pred1,
1196 const SmallVectorImpl<MachineOperand> &Pred2) const {
1197 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1198 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1200 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1202 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1205 // P1 can only subsume P2 if they test the same condition register.
1206 if (Pred1[1].getReg() != Pred2[1].getReg())
1209 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1210 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1215 // Does P1 subsume P2, e.g. GE subsumes GT.
1216 if (P1 == PPC::PRED_LE &&
1217 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1219 if (P1 == PPC::PRED_GE &&
1220 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1226 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1227 std::vector<MachineOperand> &Pred) const {
1228 // Note: At the present time, the contents of Pred from this function is
1229 // unused by IfConversion. This implementation follows ARM by pushing the
1230 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1231 // predicate, instructions defining CTR or CTR8 are also included as
1232 // predicate-defining instructions.
1234 const TargetRegisterClass *RCs[] =
1235 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1236 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1239 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1240 const MachineOperand &MO = MI->getOperand(i);
1241 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1242 const TargetRegisterClass *RC = RCs[c];
1244 if (MO.isDef() && RC->contains(MO.getReg())) {
1248 } else if (MO.isRegMask()) {
1249 for (TargetRegisterClass::iterator I = RC->begin(),
1250 IE = RC->end(); I != IE; ++I)
1251 if (MO.clobbersPhysReg(*I)) {
1262 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1263 unsigned OpC = MI->getOpcode();
1277 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1278 unsigned &SrcReg, unsigned &SrcReg2,
1279 int &Mask, int &Value) const {
1280 unsigned Opc = MI->getOpcode();
1283 default: return false;
1288 SrcReg = MI->getOperand(1).getReg();
1290 Value = MI->getOperand(2).getImm();
1299 SrcReg = MI->getOperand(1).getReg();
1300 SrcReg2 = MI->getOperand(2).getReg();
1305 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1306 unsigned SrcReg, unsigned SrcReg2,
1307 int Mask, int Value,
1308 const MachineRegisterInfo *MRI) const {
1312 int OpC = CmpInstr->getOpcode();
1313 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1315 // FP record forms set CR1 based on the execption status bits, not a
1316 // comparison with zero.
1317 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1320 // The record forms set the condition register based on a signed comparison
1321 // with zero (so says the ISA manual). This is not as straightforward as it
1322 // seems, however, because this is always a 64-bit comparison on PPC64, even
1323 // for instructions that are 32-bit in nature (like slw for example).
1324 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1325 // for equality checks (as those don't depend on the sign). On PPC64,
1326 // we are restricted to equality for unsigned 64-bit comparisons and for
1327 // signed 32-bit comparisons the applicability is more restricted.
1328 bool isPPC64 = Subtarget.isPPC64();
1329 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1330 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1331 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1333 // Get the unique definition of SrcReg.
1334 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1335 if (!MI) return false;
1336 int MIOpC = MI->getOpcode();
1338 bool equalityOnly = false;
1341 if (is32BitSignedCompare) {
1342 // We can perform this optimization only if MI is sign-extending.
1343 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1344 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1345 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1346 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1347 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1351 } else if (is32BitUnsignedCompare) {
1352 // We can perform this optimization, equality only, if MI is
1354 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1355 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1356 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1358 equalityOnly = true;
1362 equalityOnly = is64BitUnsignedCompare;
1364 equalityOnly = is32BitUnsignedCompare;
1367 // We need to check the uses of the condition register in order to reject
1368 // non-equality comparisons.
1369 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1370 IE = MRI->use_instr_end(); I != IE; ++I) {
1371 MachineInstr *UseMI = &*I;
1372 if (UseMI->getOpcode() == PPC::BCC) {
1373 unsigned Pred = UseMI->getOperand(0).getImm();
1374 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1376 } else if (UseMI->getOpcode() == PPC::ISEL ||
1377 UseMI->getOpcode() == PPC::ISEL8) {
1378 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1379 if (SubIdx != PPC::sub_eq)
1386 MachineBasicBlock::iterator I = CmpInstr;
1388 // Scan forward to find the first use of the compare.
1389 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1391 bool FoundUse = false;
1392 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1393 JE = MRI->use_instr_end(); J != JE; ++J)
1403 // There are two possible candidates which can be changed to set CR[01].
1404 // One is MI, the other is a SUB instruction.
1405 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1406 MachineInstr *Sub = nullptr;
1408 // MI is not a candidate for CMPrr.
1410 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1411 // same BB as the comparison. This is to allow the check below to avoid calls
1412 // (and other explicit clobbers); instead we should really check for these
1413 // more explicitly (in at least a few predecessors).
1414 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1415 // PPC does not have a record-form SUBri.
1420 const TargetRegisterInfo *TRI = &getRegisterInfo();
1423 // Get ready to iterate backward from CmpInstr.
1424 MachineBasicBlock::iterator E = MI,
1425 B = CmpInstr->getParent()->begin();
1427 for (; I != E && !noSub; --I) {
1428 const MachineInstr &Instr = *I;
1429 unsigned IOpC = Instr.getOpcode();
1431 if (&*I != CmpInstr && (
1432 Instr.modifiesRegister(PPC::CR0, TRI) ||
1433 Instr.readsRegister(PPC::CR0, TRI)))
1434 // This instruction modifies or uses the record condition register after
1435 // the one we want to change. While we could do this transformation, it
1436 // would likely not be profitable. This transformation removes one
1437 // instruction, and so even forcing RA to generate one move probably
1438 // makes it unprofitable.
1441 // Check whether CmpInstr can be made redundant by the current instruction.
1442 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1443 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1444 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1445 ((Instr.getOperand(1).getReg() == SrcReg &&
1446 Instr.getOperand(2).getReg() == SrcReg2) ||
1447 (Instr.getOperand(1).getReg() == SrcReg2 &&
1448 Instr.getOperand(2).getReg() == SrcReg))) {
1454 // The 'and' is below the comparison instruction.
1458 // Return false if no candidates exist.
1462 // The single candidate is called MI.
1466 MIOpC = MI->getOpcode();
1467 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1470 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1471 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1475 // FIXME: On the non-embedded POWER architectures, only some of the record
1476 // forms are fast, and we should use only the fast ones.
1478 // The defining instruction has a record form (or is already a record
1479 // form). It is possible, however, that we'll need to reverse the condition
1480 // code of the users.
1484 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1485 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1487 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1488 // needs to be updated to be based on SUB. Push the condition code
1489 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1490 // condition code of these operands will be modified.
1491 bool ShouldSwap = false;
1493 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1494 Sub->getOperand(2).getReg() == SrcReg;
1496 // The operands to subf are the opposite of sub, so only in the fixed-point
1497 // case, invert the order.
1498 ShouldSwap = !ShouldSwap;
1502 for (MachineRegisterInfo::use_instr_iterator
1503 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1505 MachineInstr *UseMI = &*I;
1506 if (UseMI->getOpcode() == PPC::BCC) {
1507 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1508 assert((!equalityOnly ||
1509 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1510 "Invalid predicate for equality-only optimization");
1511 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1512 PPC::getSwappedPredicate(Pred)));
1513 } else if (UseMI->getOpcode() == PPC::ISEL ||
1514 UseMI->getOpcode() == PPC::ISEL8) {
1515 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1516 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1517 "Invalid CR bit for equality-only optimization");
1519 if (NewSubReg == PPC::sub_lt)
1520 NewSubReg = PPC::sub_gt;
1521 else if (NewSubReg == PPC::sub_gt)
1522 NewSubReg = PPC::sub_lt;
1524 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1526 } else // We need to abort on a user we don't understand.
1530 // Create a new virtual register to hold the value of the CR set by the
1531 // record-form instruction. If the instruction was not previously in
1532 // record form, then set the kill flag on the CR.
1533 CmpInstr->eraseFromParent();
1535 MachineBasicBlock::iterator MII = MI;
1536 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1537 get(TargetOpcode::COPY), CRReg)
1538 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1540 if (MIOpC != NewOpC) {
1541 // We need to be careful here: we're replacing one instruction with
1542 // another, and we need to make sure that we get all of the right
1543 // implicit uses and defs. On the other hand, the caller may be holding
1544 // an iterator to this instruction, and so we can't delete it (this is
1545 // specifically the case if this is the instruction directly after the
1548 const MCInstrDesc &NewDesc = get(NewOpC);
1549 MI->setDesc(NewDesc);
1551 if (NewDesc.ImplicitDefs)
1552 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1553 *ImpDefs; ++ImpDefs)
1554 if (!MI->definesRegister(*ImpDefs))
1555 MI->addOperand(*MI->getParent()->getParent(),
1556 MachineOperand::CreateReg(*ImpDefs, true, true));
1557 if (NewDesc.ImplicitUses)
1558 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1559 *ImpUses; ++ImpUses)
1560 if (!MI->readsRegister(*ImpUses))
1561 MI->addOperand(*MI->getParent()->getParent(),
1562 MachineOperand::CreateReg(*ImpUses, false, true));
1565 // Modify the condition code of operands in OperandsToUpdate.
1566 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1567 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1568 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1569 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1571 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1572 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1577 /// GetInstSize - Return the number of bytes of code the specified
1578 /// instruction may be. This returns the maximum number of bytes.
1580 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1581 unsigned Opcode = MI->getOpcode();
1583 if (Opcode == PPC::INLINEASM) {
1584 const MachineFunction *MF = MI->getParent()->getParent();
1585 const char *AsmStr = MI->getOperand(0).getSymbolName();
1586 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1588 const MCInstrDesc &Desc = get(Opcode);
1589 return Desc.getSize();
1594 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1597 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1598 // (Altivec and scalar floating-point registers), we need to transform the
1599 // copies into subregister copies with other restrictions.
1600 struct PPCVSXFMAMutate : public MachineFunctionPass {
1602 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1603 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1608 const PPCTargetMachine *TM;
1609 const PPCInstrInfo *TII;
1612 bool processBlock(MachineBasicBlock &MBB) {
1613 bool Changed = false;
1615 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1616 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1618 MachineInstr *MI = I;
1620 // The default (A-type) VSX FMA form kills the addend (it is taken from
1621 // the target register, which is then updated to reflect the result of
1622 // the FMA). If the instruction, however, kills one of the registers
1623 // used for the product, then we can use the M-form instruction (which
1624 // will take that value from the to-be-defined register).
1626 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1630 // This pass is run after register coalescing, and so we're looking for
1631 // a situation like this:
1633 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1634 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1635 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1637 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1638 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1640 // Where we can eliminate the copy by changing from the A-type to the
1641 // M-type instruction. Specifically, for this example, this means:
1642 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1643 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1645 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1646 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1647 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1649 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1651 VNInfo *AddendValNo =
1652 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1653 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1655 // The addend and this instruction must be in the same block.
1657 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1660 // The addend must be a full copy within the same register class.
1662 if (!AddendMI->isFullCopy())
1665 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1666 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1667 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1668 MRI.getRegClass(AddendSrcReg))
1671 // If AddendSrcReg is a physical register, make sure the destination
1672 // register class contains it.
1673 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1674 ->contains(AddendSrcReg))
1678 // In theory, there could be other uses of the addend copy before this
1679 // fma. We could deal with this, but that would require additional
1680 // logic below and I suspect it will not occur in any relevant
1682 bool OtherUsers = false;
1683 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1685 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1693 // Find one of the product operands that is killed by this instruction.
1695 unsigned KilledProdOp = 0, OtherProdOp = 0;
1696 if (LIS->getInterval(MI->getOperand(2).getReg())
1697 .Query(FMAIdx).isKill()) {
1700 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1701 .Query(FMAIdx).isKill()) {
1706 // If there are no killed product operands, then this transformation is
1707 // likely not profitable.
1711 // In order to replace the addend here with the source of the copy,
1712 // it must still be live here.
1713 if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1716 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1718 unsigned AddReg = AddendMI->getOperand(1).getReg();
1719 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1720 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1722 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1723 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1724 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1726 bool AddRegKill = AddendMI->getOperand(1).isKill();
1727 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1728 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1730 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1731 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1732 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1734 unsigned OldFMAReg = MI->getOperand(0).getReg();
1736 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1737 "Addend copy not tied to old FMA output!");
1739 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1741 MI->getOperand(0).setReg(KilledProdReg);
1742 MI->getOperand(1).setReg(KilledProdReg);
1743 MI->getOperand(3).setReg(AddReg);
1744 MI->getOperand(2).setReg(OtherProdReg);
1746 MI->getOperand(0).setSubReg(KilledProdSubReg);
1747 MI->getOperand(1).setSubReg(KilledProdSubReg);
1748 MI->getOperand(3).setSubReg(AddSubReg);
1749 MI->getOperand(2).setSubReg(OtherProdSubReg);
1751 MI->getOperand(1).setIsKill(KilledProdRegKill);
1752 MI->getOperand(3).setIsKill(AddRegKill);
1753 MI->getOperand(2).setIsKill(OtherProdRegKill);
1755 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1756 MI->getOperand(3).setIsUndef(AddRegUndef);
1757 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1759 MI->setDesc(TII->get(AltOpc));
1761 DEBUG(dbgs() << " -> " << *MI);
1763 // The killed product operand was killed here, so we can reuse it now
1764 // for the result of the fma.
1766 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1767 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1768 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1770 MachineOperand &UseMO = *UI;
1771 MachineInstr *UseMI = UseMO.getParent();
1774 // Don't replace the result register of the copy we're about to erase.
1775 if (UseMI == AddendMI)
1778 UseMO.setReg(KilledProdReg);
1779 UseMO.setSubReg(KilledProdSubReg);
1782 // Extend the live intervals of the killed product operand to hold the
1785 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1786 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1788 // Don't add the segment that corresponds to the original copy.
1789 if (AI->valno == AddendValNo)
1792 VNInfo *NewFMAValNo =
1793 NewFMAInt.getNextValue(AI->start,
1794 LIS->getVNInfoAllocator());
1796 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1799 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1801 FMAInt.removeValNo(FMAValNo);
1802 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1804 // Remove the (now unused) copy.
1806 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1807 LIS->RemoveMachineInstrFromMaps(AddendMI);
1808 AddendMI->eraseFromParent();
1817 bool runOnMachineFunction(MachineFunction &MF) override {
1818 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1819 // If we don't have VSX then go ahead and return without doing
1821 if (!TM->getSubtargetImpl()->hasVSX())
1824 LIS = &getAnalysis<LiveIntervals>();
1826 TII = TM->getInstrInfo();
1828 bool Changed = false;
1830 if (DisableVSXFMAMutate)
1833 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1834 MachineBasicBlock &B = *I++;
1835 if (processBlock(B))
1842 void getAnalysisUsage(AnalysisUsage &AU) const override {
1843 AU.addRequired<LiveIntervals>();
1844 AU.addPreserved<LiveIntervals>();
1845 AU.addRequired<SlotIndexes>();
1846 AU.addPreserved<SlotIndexes>();
1847 MachineFunctionPass::getAnalysisUsage(AU);
1852 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1853 "PowerPC VSX FMA Mutation", false, false)
1854 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1855 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1856 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1857 "PowerPC VSX FMA Mutation", false, false)
1859 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1861 char PPCVSXFMAMutate::ID = 0;
1863 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1866 #define DEBUG_TYPE "ppc-vsx-copy"
1869 void initializePPCVSXCopyPass(PassRegistry&);
1873 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1874 // (Altivec and scalar floating-point registers), we need to transform the
1875 // copies into subregister copies with other restrictions.
1876 struct PPCVSXCopy : public MachineFunctionPass {
1878 PPCVSXCopy() : MachineFunctionPass(ID) {
1879 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1882 const PPCTargetMachine *TM;
1883 const PPCInstrInfo *TII;
1885 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1886 MachineRegisterInfo &MRI) {
1887 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1888 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1889 } else if (RC->contains(Reg)) {
1896 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1897 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1900 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1901 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1904 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1905 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1909 bool processBlock(MachineBasicBlock &MBB) {
1910 bool Changed = false;
1912 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1913 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1915 MachineInstr *MI = I;
1916 if (!MI->isFullCopy())
1919 MachineOperand &DstMO = MI->getOperand(0);
1920 MachineOperand &SrcMO = MI->getOperand(1);
1922 if ( IsVSReg(DstMO.getReg(), MRI) &&
1923 !IsVSReg(SrcMO.getReg(), MRI)) {
1924 // This is a copy *to* a VSX register from a non-VSX register.
1927 const TargetRegisterClass *SrcRC =
1928 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1929 &PPC::VSLRCRegClass;
1930 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1931 IsVRReg(SrcMO.getReg(), MRI)) &&
1932 "Unknown source for a VSX copy");
1934 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1935 BuildMI(MBB, MI, MI->getDebugLoc(),
1936 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1937 .addImm(1) // add 1, not 0, because there is no implicit clearing
1938 // of the high bits.
1940 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1943 // The source of the original copy is now the new virtual register.
1944 SrcMO.setReg(NewVReg);
1945 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1946 IsVSReg(SrcMO.getReg(), MRI)) {
1947 // This is a copy *from* a VSX register to a non-VSX register.
1950 const TargetRegisterClass *DstRC =
1951 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1952 &PPC::VSLRCRegClass;
1953 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1954 IsVRReg(DstMO.getReg(), MRI)) &&
1955 "Unknown destination for a VSX copy");
1957 // Copy the VSX value into a new VSX register of the correct subclass.
1958 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1959 BuildMI(MBB, MI, MI->getDebugLoc(),
1960 TII->get(TargetOpcode::COPY), NewVReg)
1963 // Transform the original copy into a subregister extraction copy.
1964 SrcMO.setReg(NewVReg);
1965 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1974 bool runOnMachineFunction(MachineFunction &MF) override {
1975 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1976 // If we don't have VSX on the subtarget, don't do anything.
1977 if (!TM->getSubtargetImpl()->hasVSX())
1979 TII = TM->getInstrInfo();
1981 bool Changed = false;
1983 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1984 MachineBasicBlock &B = *I++;
1985 if (processBlock(B))
1992 void getAnalysisUsage(AnalysisUsage &AU) const override {
1993 MachineFunctionPass::getAnalysisUsage(AU);
1998 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
1999 "PowerPC VSX Copy Legalization", false, false)
2001 char PPCVSXCopy::ID = 0;
2003 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2006 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2009 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2013 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2014 // registers (mostly because the ABI code still places all values into the
2015 // "traditional" floating-point and vector registers). Remove them here.
2016 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2018 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2019 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2022 const PPCTargetMachine *TM;
2023 const PPCInstrInfo *TII;
2026 bool processBlock(MachineBasicBlock &MBB) {
2027 bool Changed = false;
2029 SmallVector<MachineInstr *, 4> ToDelete;
2030 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2032 MachineInstr *MI = I;
2033 if (MI->getOpcode() == PPC::XXLOR &&
2034 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2035 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2036 ToDelete.push_back(MI);
2039 if (!ToDelete.empty())
2042 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2043 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2044 ToDelete[i]->eraseFromParent();
2051 bool runOnMachineFunction(MachineFunction &MF) override {
2052 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2053 // If we don't have VSX don't bother doing anything here.
2054 if (!TM->getSubtargetImpl()->hasVSX())
2056 TII = TM->getInstrInfo();
2058 bool Changed = false;
2060 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2061 MachineBasicBlock &B = *I++;
2062 if (processBlock(B))
2069 void getAnalysisUsage(AnalysisUsage &AU) const override {
2070 MachineFunctionPass::getAnalysisUsage(AU);
2075 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2076 "PowerPC VSX Copy Cleanup", false, false)
2078 char PPCVSXCopyCleanup::ID = 0;
2080 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2083 #define DEBUG_TYPE "ppc-early-ret"
2084 STATISTIC(NumBCLR, "Number of early conditional returns");
2085 STATISTIC(NumBLR, "Number of early returns");
2088 void initializePPCEarlyReturnPass(PassRegistry&);
2092 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2093 // returns up, and create conditional returns, to avoid unnecessary
2094 // branch-to-blr sequences.
2095 struct PPCEarlyReturn : public MachineFunctionPass {
2097 PPCEarlyReturn() : MachineFunctionPass(ID) {
2098 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2101 const PPCTargetMachine *TM;
2102 const PPCInstrInfo *TII;
2105 bool processBlock(MachineBasicBlock &ReturnMBB) {
2106 bool Changed = false;
2108 MachineBasicBlock::iterator I = ReturnMBB.begin();
2109 I = ReturnMBB.SkipPHIsAndLabels(I);
2111 // The block must be essentially empty except for the blr.
2112 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2113 I != ReturnMBB.getLastNonDebugInstr())
2116 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2117 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2118 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2119 bool OtherReference = false, BlockChanged = false;
2120 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2121 if (J->getOpcode() == PPC::B) {
2122 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2123 // This is an unconditional branch to the return. Replace the
2124 // branch with a blr.
2125 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2126 MachineBasicBlock::iterator K = J--;
2127 K->eraseFromParent();
2128 BlockChanged = true;
2132 } else if (J->getOpcode() == PPC::BCC) {
2133 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2134 // This is a conditional branch to the return. Replace the branch
2136 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2137 .addImm(J->getOperand(0).getImm())
2138 .addReg(J->getOperand(1).getReg());
2139 MachineBasicBlock::iterator K = J--;
2140 K->eraseFromParent();
2141 BlockChanged = true;
2145 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2146 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2147 // This is a conditional branch to the return. Replace the branch
2149 BuildMI(**PI, J, J->getDebugLoc(),
2150 TII->get(J->getOpcode() == PPC::BC ?
2151 PPC::BCLR : PPC::BCLRn))
2152 .addReg(J->getOperand(0).getReg());
2153 MachineBasicBlock::iterator K = J--;
2154 K->eraseFromParent();
2155 BlockChanged = true;
2159 } else if (J->isBranch()) {
2160 if (J->isIndirectBranch()) {
2161 if (ReturnMBB.hasAddressTaken())
2162 OtherReference = true;
2164 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2165 if (J->getOperand(i).isMBB() &&
2166 J->getOperand(i).getMBB() == &ReturnMBB)
2167 OtherReference = true;
2168 } else if (!J->isTerminator() && !J->isDebugValue())
2171 if (J == (*PI)->begin())
2177 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2178 OtherReference = true;
2180 // Predecessors are stored in a vector and can't be removed here.
2181 if (!OtherReference && BlockChanged) {
2182 PredToRemove.push_back(*PI);
2189 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2190 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2192 if (Changed && !ReturnMBB.hasAddressTaken()) {
2193 // We now might be able to merge this blr-only block into its
2194 // by-layout predecessor.
2195 if (ReturnMBB.pred_size() == 1 &&
2196 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2197 // Move the blr into the preceding block.
2198 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2199 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2200 PrevMBB.removeSuccessor(&ReturnMBB);
2203 if (ReturnMBB.pred_empty())
2204 ReturnMBB.eraseFromParent();
2211 bool runOnMachineFunction(MachineFunction &MF) override {
2212 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2213 TII = TM->getInstrInfo();
2215 bool Changed = false;
2217 // If the function does not have at least two blocks, then there is
2222 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2223 MachineBasicBlock &B = *I++;
2224 if (processBlock(B))
2231 void getAnalysisUsage(AnalysisUsage &AU) const override {
2232 MachineFunctionPass::getAnalysisUsage(AU);
2237 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2238 "PowerPC Early-Return Creation", false, false)
2240 char PPCEarlyReturn::ID = 0;
2242 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }