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 *
71 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
72 const ScheduleDAG *DAG) const {
74 static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
75 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
76 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
77 const InstrItineraryData *II =
78 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
79 return new ScoreboardHazardRecognizer(II, DAG);
82 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
85 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
86 /// to use for this target when scheduling the DAG.
87 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
88 const InstrItineraryData *II,
89 const ScheduleDAG *DAG) const {
91 DAG->TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
93 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
94 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
96 // Most subtargets use a PPC970 recognizer.
97 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
98 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
99 assert(DAG->TII && "No InstrInfo?");
101 return new PPCHazardRecognizer970(*DAG);
104 return new ScoreboardHazardRecognizer(II, DAG);
108 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
109 const MachineInstr *DefMI, unsigned DefIdx,
110 const MachineInstr *UseMI,
111 unsigned UseIdx) const {
112 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
115 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
116 unsigned Reg = DefMO.getReg();
118 const TargetRegisterInfo *TRI = &getRegisterInfo();
120 if (TRI->isVirtualRegister(Reg)) {
121 const MachineRegisterInfo *MRI =
122 &DefMI->getParent()->getParent()->getRegInfo();
123 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
124 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
126 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
127 PPC::CRBITRCRegClass.contains(Reg);
130 if (UseMI->isBranch() && IsRegCR) {
132 Latency = getInstrLatency(ItinData, DefMI);
134 // On some cores, there is an additional delay between writing to a condition
135 // register, and using it from a branch.
136 unsigned Directive = Subtarget.getDarwinDirective();
158 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
159 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
160 unsigned &SrcReg, unsigned &DstReg,
161 unsigned &SubIdx) const {
162 switch (MI.getOpcode()) {
163 default: return false;
165 case PPC::EXTSW_32_64:
166 SrcReg = MI.getOperand(1).getReg();
167 DstReg = MI.getOperand(0).getReg();
168 SubIdx = PPC::sub_32;
173 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
174 int &FrameIndex) const {
175 // Note: This list must be kept consistent with LoadRegFromStackSlot.
176 switch (MI->getOpcode()) {
182 case PPC::RESTORE_CR:
183 case PPC::RESTORE_CRBIT:
186 case PPC::RESTORE_VRSAVE:
187 // Check for the operands added by addFrameReference (the immediate is the
188 // offset which defaults to 0).
189 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
190 MI->getOperand(2).isFI()) {
191 FrameIndex = MI->getOperand(2).getIndex();
192 return MI->getOperand(0).getReg();
199 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
200 int &FrameIndex) const {
201 // Note: This list must be kept consistent with StoreRegToStackSlot.
202 switch (MI->getOpcode()) {
209 case PPC::SPILL_CRBIT:
212 case PPC::SPILL_VRSAVE:
213 // Check for the operands added by addFrameReference (the immediate is the
214 // offset which defaults to 0).
215 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
216 MI->getOperand(2).isFI()) {
217 FrameIndex = MI->getOperand(2).getIndex();
218 return MI->getOperand(0).getReg();
225 // commuteInstruction - We can commute rlwimi instructions, but only if the
226 // rotate amt is zero. We also have to munge the immediates a bit.
228 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
229 MachineFunction &MF = *MI->getParent()->getParent();
231 // Normal instructions can be commuted the obvious way.
232 if (MI->getOpcode() != PPC::RLWIMI &&
233 MI->getOpcode() != PPC::RLWIMIo &&
234 MI->getOpcode() != PPC::RLWIMI8 &&
235 MI->getOpcode() != PPC::RLWIMI8o)
236 return TargetInstrInfo::commuteInstruction(MI, NewMI);
238 // Cannot commute if it has a non-zero rotate count.
239 if (MI->getOperand(3).getImm() != 0)
242 // If we have a zero rotate count, we have:
244 // Op0 = (Op1 & ~M) | (Op2 & M)
246 // M = mask((ME+1)&31, (MB-1)&31)
247 // Op0 = (Op2 & ~M) | (Op1 & M)
250 unsigned Reg0 = MI->getOperand(0).getReg();
251 unsigned Reg1 = MI->getOperand(1).getReg();
252 unsigned Reg2 = MI->getOperand(2).getReg();
253 unsigned SubReg1 = MI->getOperand(1).getSubReg();
254 unsigned SubReg2 = MI->getOperand(2).getSubReg();
255 bool Reg1IsKill = MI->getOperand(1).isKill();
256 bool Reg2IsKill = MI->getOperand(2).isKill();
257 bool ChangeReg0 = false;
258 // If machine instrs are no longer in two-address forms, update
259 // destination register as well.
261 // Must be two address instruction!
262 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
263 "Expecting a two-address instruction!");
264 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
270 unsigned MB = MI->getOperand(4).getImm();
271 unsigned ME = MI->getOperand(5).getImm();
274 // Create a new instruction.
275 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
276 bool Reg0IsDead = MI->getOperand(0).isDead();
277 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
278 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
279 .addReg(Reg2, getKillRegState(Reg2IsKill))
280 .addReg(Reg1, getKillRegState(Reg1IsKill))
282 .addImm((MB-1) & 31);
286 MI->getOperand(0).setReg(Reg2);
287 MI->getOperand(0).setSubReg(SubReg2);
289 MI->getOperand(2).setReg(Reg1);
290 MI->getOperand(1).setReg(Reg2);
291 MI->getOperand(2).setSubReg(SubReg1);
292 MI->getOperand(1).setSubReg(SubReg2);
293 MI->getOperand(2).setIsKill(Reg1IsKill);
294 MI->getOperand(1).setIsKill(Reg2IsKill);
296 // Swap the mask around.
297 MI->getOperand(4).setImm((ME+1) & 31);
298 MI->getOperand(5).setImm((MB-1) & 31);
302 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
303 unsigned &SrcOpIdx2) const {
304 // For VSX A-Type FMA instructions, it is the first two operands that can be
305 // commuted, however, because the non-encoded tied input operand is listed
306 // first, the operands to swap are actually the second and third.
308 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
310 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
317 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
318 MachineBasicBlock::iterator MI) const {
319 // This function is used for scheduling, and the nop wanted here is the type
320 // that terminates dispatch groups on the POWER cores.
321 unsigned Directive = Subtarget.getDarwinDirective();
324 default: Opcode = PPC::NOP; break;
325 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
326 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
327 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
331 BuildMI(MBB, MI, DL, get(Opcode));
334 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
335 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
336 NopInst.setOpcode(PPC::NOP);
340 // Note: If the condition register is set to CTR or CTR8 then this is a
341 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
342 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
343 MachineBasicBlock *&FBB,
344 SmallVectorImpl<MachineOperand> &Cond,
345 bool AllowModify) const {
346 bool isPPC64 = Subtarget.isPPC64();
348 // If the block has no terminators, it just falls into the block after it.
349 MachineBasicBlock::iterator I = MBB.end();
350 if (I == MBB.begin())
353 while (I->isDebugValue()) {
354 if (I == MBB.begin())
358 if (!isUnpredicatedTerminator(I))
361 // Get the last instruction in the block.
362 MachineInstr *LastInst = I;
364 // If there is only one terminator instruction, process it.
365 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
366 if (LastInst->getOpcode() == PPC::B) {
367 if (!LastInst->getOperand(0).isMBB())
369 TBB = LastInst->getOperand(0).getMBB();
371 } else if (LastInst->getOpcode() == PPC::BCC) {
372 if (!LastInst->getOperand(2).isMBB())
374 // Block ends with fall-through condbranch.
375 TBB = LastInst->getOperand(2).getMBB();
376 Cond.push_back(LastInst->getOperand(0));
377 Cond.push_back(LastInst->getOperand(1));
379 } else if (LastInst->getOpcode() == PPC::BC) {
380 if (!LastInst->getOperand(1).isMBB())
382 // Block ends with fall-through condbranch.
383 TBB = LastInst->getOperand(1).getMBB();
384 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
385 Cond.push_back(LastInst->getOperand(0));
387 } else if (LastInst->getOpcode() == PPC::BCn) {
388 if (!LastInst->getOperand(1).isMBB())
390 // Block ends with fall-through condbranch.
391 TBB = LastInst->getOperand(1).getMBB();
392 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
393 Cond.push_back(LastInst->getOperand(0));
395 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
396 LastInst->getOpcode() == PPC::BDNZ) {
397 if (!LastInst->getOperand(0).isMBB())
399 if (DisableCTRLoopAnal)
401 TBB = LastInst->getOperand(0).getMBB();
402 Cond.push_back(MachineOperand::CreateImm(1));
403 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
406 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
407 LastInst->getOpcode() == PPC::BDZ) {
408 if (!LastInst->getOperand(0).isMBB())
410 if (DisableCTRLoopAnal)
412 TBB = LastInst->getOperand(0).getMBB();
413 Cond.push_back(MachineOperand::CreateImm(0));
414 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
419 // Otherwise, don't know what this is.
423 // Get the instruction before it if it's a terminator.
424 MachineInstr *SecondLastInst = I;
426 // If there are three terminators, we don't know what sort of block this is.
427 if (SecondLastInst && I != MBB.begin() &&
428 isUnpredicatedTerminator(--I))
431 // If the block ends with PPC::B and PPC:BCC, handle it.
432 if (SecondLastInst->getOpcode() == PPC::BCC &&
433 LastInst->getOpcode() == PPC::B) {
434 if (!SecondLastInst->getOperand(2).isMBB() ||
435 !LastInst->getOperand(0).isMBB())
437 TBB = SecondLastInst->getOperand(2).getMBB();
438 Cond.push_back(SecondLastInst->getOperand(0));
439 Cond.push_back(SecondLastInst->getOperand(1));
440 FBB = LastInst->getOperand(0).getMBB();
442 } else if (SecondLastInst->getOpcode() == PPC::BC &&
443 LastInst->getOpcode() == PPC::B) {
444 if (!SecondLastInst->getOperand(1).isMBB() ||
445 !LastInst->getOperand(0).isMBB())
447 TBB = SecondLastInst->getOperand(1).getMBB();
448 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
449 Cond.push_back(SecondLastInst->getOperand(0));
450 FBB = LastInst->getOperand(0).getMBB();
452 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
453 LastInst->getOpcode() == PPC::B) {
454 if (!SecondLastInst->getOperand(1).isMBB() ||
455 !LastInst->getOperand(0).isMBB())
457 TBB = SecondLastInst->getOperand(1).getMBB();
458 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
459 Cond.push_back(SecondLastInst->getOperand(0));
460 FBB = LastInst->getOperand(0).getMBB();
462 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
463 SecondLastInst->getOpcode() == PPC::BDNZ) &&
464 LastInst->getOpcode() == PPC::B) {
465 if (!SecondLastInst->getOperand(0).isMBB() ||
466 !LastInst->getOperand(0).isMBB())
468 if (DisableCTRLoopAnal)
470 TBB = SecondLastInst->getOperand(0).getMBB();
471 Cond.push_back(MachineOperand::CreateImm(1));
472 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
474 FBB = LastInst->getOperand(0).getMBB();
476 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
477 SecondLastInst->getOpcode() == PPC::BDZ) &&
478 LastInst->getOpcode() == PPC::B) {
479 if (!SecondLastInst->getOperand(0).isMBB() ||
480 !LastInst->getOperand(0).isMBB())
482 if (DisableCTRLoopAnal)
484 TBB = SecondLastInst->getOperand(0).getMBB();
485 Cond.push_back(MachineOperand::CreateImm(0));
486 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
488 FBB = LastInst->getOperand(0).getMBB();
492 // If the block ends with two PPC:Bs, handle it. The second one is not
493 // executed, so remove it.
494 if (SecondLastInst->getOpcode() == PPC::B &&
495 LastInst->getOpcode() == PPC::B) {
496 if (!SecondLastInst->getOperand(0).isMBB())
498 TBB = SecondLastInst->getOperand(0).getMBB();
501 I->eraseFromParent();
505 // Otherwise, can't handle this.
509 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
510 MachineBasicBlock::iterator I = MBB.end();
511 if (I == MBB.begin()) return 0;
513 while (I->isDebugValue()) {
514 if (I == MBB.begin())
518 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
519 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
520 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
521 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
524 // Remove the branch.
525 I->eraseFromParent();
529 if (I == MBB.begin()) return 1;
531 if (I->getOpcode() != PPC::BCC &&
532 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
533 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
534 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
537 // Remove the branch.
538 I->eraseFromParent();
543 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
544 MachineBasicBlock *FBB,
545 const SmallVectorImpl<MachineOperand> &Cond,
547 // Shouldn't be a fall through.
548 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
549 assert((Cond.size() == 2 || Cond.size() == 0) &&
550 "PPC branch conditions have two components!");
552 bool isPPC64 = Subtarget.isPPC64();
556 if (Cond.empty()) // Unconditional branch
557 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
558 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
559 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
560 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
561 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
562 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
563 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
564 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
565 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
566 else // Conditional branch
567 BuildMI(&MBB, DL, get(PPC::BCC))
568 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
572 // Two-way Conditional Branch.
573 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
574 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
575 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
576 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
577 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
578 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
579 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
580 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
582 BuildMI(&MBB, DL, get(PPC::BCC))
583 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
584 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
589 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
590 const SmallVectorImpl<MachineOperand> &Cond,
591 unsigned TrueReg, unsigned FalseReg,
592 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
593 if (!Subtarget.hasISEL())
596 if (Cond.size() != 2)
599 // If this is really a bdnz-like condition, then it cannot be turned into a
601 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
604 // Check register classes.
605 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
606 const TargetRegisterClass *RC =
607 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
611 // isel is for regular integer GPRs only.
612 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
613 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
614 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
615 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
618 // FIXME: These numbers are for the A2, how well they work for other cores is
619 // an open question. On the A2, the isel instruction has a 2-cycle latency
620 // but single-cycle throughput. These numbers are used in combination with
621 // the MispredictPenalty setting from the active SchedMachineModel.
629 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
630 MachineBasicBlock::iterator MI, DebugLoc dl,
632 const SmallVectorImpl<MachineOperand> &Cond,
633 unsigned TrueReg, unsigned FalseReg) const {
634 assert(Cond.size() == 2 &&
635 "PPC branch conditions have two components!");
637 assert(Subtarget.hasISEL() &&
638 "Cannot insert select on target without ISEL support");
640 // Get the register classes.
641 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
642 const TargetRegisterClass *RC =
643 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
644 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
646 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
647 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
649 PPC::GPRCRegClass.hasSubClassEq(RC) ||
650 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
651 "isel is for regular integer GPRs only");
653 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
654 unsigned SelectPred = Cond[0].getImm();
658 switch (SelectPred) {
659 default: llvm_unreachable("invalid predicate for isel");
660 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
661 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
662 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
663 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
664 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
665 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
666 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
667 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
668 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
669 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
672 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
673 SecondReg = SwapOps ? TrueReg : FalseReg;
675 // The first input register of isel cannot be r0. If it is a member
676 // of a register class that can be r0, then copy it first (the
677 // register allocator should eliminate the copy).
678 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
679 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
680 const TargetRegisterClass *FirstRC =
681 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
682 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
683 unsigned OldFirstReg = FirstReg;
684 FirstReg = MRI.createVirtualRegister(FirstRC);
685 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
686 .addReg(OldFirstReg);
689 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
690 .addReg(FirstReg).addReg(SecondReg)
691 .addReg(Cond[1].getReg(), 0, SubIdx);
694 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
695 MachineBasicBlock::iterator I, DebugLoc DL,
696 unsigned DestReg, unsigned SrcReg,
697 bool KillSrc) const {
698 // We can end up with self copies and similar things as a result of VSX copy
699 // legalization. Promote them here.
700 const TargetRegisterInfo *TRI = &getRegisterInfo();
701 if (PPC::F8RCRegClass.contains(DestReg) &&
702 PPC::VSLRCRegClass.contains(SrcReg)) {
704 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
706 if (VSXSelfCopyCrash && SrcReg == SuperReg)
707 llvm_unreachable("nop VSX copy");
710 } else if (PPC::VRRCRegClass.contains(DestReg) &&
711 PPC::VSHRCRegClass.contains(SrcReg)) {
713 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
715 if (VSXSelfCopyCrash && SrcReg == SuperReg)
716 llvm_unreachable("nop VSX copy");
719 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
720 PPC::VSLRCRegClass.contains(DestReg)) {
722 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
724 if (VSXSelfCopyCrash && DestReg == SuperReg)
725 llvm_unreachable("nop VSX copy");
728 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
729 PPC::VSHRCRegClass.contains(DestReg)) {
731 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
733 if (VSXSelfCopyCrash && DestReg == SuperReg)
734 llvm_unreachable("nop VSX copy");
740 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
742 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
744 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
746 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
748 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
750 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
751 // There are two different ways this can be done:
752 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
753 // issue in VSU pipeline 0.
754 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
755 // can go to either pipeline.
756 // We'll always use xxlor here, because in practically all cases where
757 // copies are generated, they are close enough to some use that the
758 // lower-latency form is preferable.
760 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
762 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
765 llvm_unreachable("Impossible reg-to-reg copy");
767 const MCInstrDesc &MCID = get(Opc);
768 if (MCID.getNumOperands() == 3)
769 BuildMI(MBB, I, DL, MCID, DestReg)
770 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
772 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
775 // This function returns true if a CR spill is necessary and false otherwise.
777 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
778 unsigned SrcReg, bool isKill,
780 const TargetRegisterClass *RC,
781 SmallVectorImpl<MachineInstr*> &NewMIs,
782 bool &NonRI, bool &SpillsVRS) const{
783 // Note: If additional store instructions are added here,
784 // update isStoreToStackSlot.
787 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
788 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
789 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
791 getKillRegState(isKill)),
793 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
794 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
795 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
797 getKillRegState(isKill)),
799 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
800 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
802 getKillRegState(isKill)),
804 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
805 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
807 getKillRegState(isKill)),
809 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
810 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
812 getKillRegState(isKill)),
815 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
816 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
818 getKillRegState(isKill)),
821 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
822 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
824 getKillRegState(isKill)),
827 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
828 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
830 getKillRegState(isKill)),
833 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
834 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
836 getKillRegState(isKill)),
839 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
840 assert(Subtarget.isDarwin() &&
841 "VRSAVE only needs spill/restore on Darwin");
842 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
844 getKillRegState(isKill)),
848 llvm_unreachable("Unknown regclass!");
855 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
856 MachineBasicBlock::iterator MI,
857 unsigned SrcReg, bool isKill, int FrameIdx,
858 const TargetRegisterClass *RC,
859 const TargetRegisterInfo *TRI) const {
860 MachineFunction &MF = *MBB.getParent();
861 SmallVector<MachineInstr*, 4> NewMIs;
863 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
864 FuncInfo->setHasSpills();
866 bool NonRI = false, SpillsVRS = false;
867 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
869 FuncInfo->setSpillsCR();
872 FuncInfo->setSpillsVRSAVE();
875 FuncInfo->setHasNonRISpills();
877 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
878 MBB.insert(MI, NewMIs[i]);
880 const MachineFrameInfo &MFI = *MF.getFrameInfo();
881 MachineMemOperand *MMO =
882 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
883 MachineMemOperand::MOStore,
884 MFI.getObjectSize(FrameIdx),
885 MFI.getObjectAlignment(FrameIdx));
886 NewMIs.back()->addMemOperand(MF, MMO);
890 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
891 unsigned DestReg, int FrameIdx,
892 const TargetRegisterClass *RC,
893 SmallVectorImpl<MachineInstr*> &NewMIs,
894 bool &NonRI, bool &SpillsVRS) const{
895 // Note: If additional load instructions are added here,
896 // update isLoadFromStackSlot.
898 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
899 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
900 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
901 DestReg), FrameIdx));
902 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
903 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
904 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
906 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
907 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
909 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
910 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
912 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
913 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
914 get(PPC::RESTORE_CR), DestReg),
917 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
918 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
919 get(PPC::RESTORE_CRBIT), DestReg),
922 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
923 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
926 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
927 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
930 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
931 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
934 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
935 assert(Subtarget.isDarwin() &&
936 "VRSAVE only needs spill/restore on Darwin");
937 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
938 get(PPC::RESTORE_VRSAVE),
943 llvm_unreachable("Unknown regclass!");
950 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
951 MachineBasicBlock::iterator MI,
952 unsigned DestReg, int FrameIdx,
953 const TargetRegisterClass *RC,
954 const TargetRegisterInfo *TRI) const {
955 MachineFunction &MF = *MBB.getParent();
956 SmallVector<MachineInstr*, 4> NewMIs;
958 if (MI != MBB.end()) DL = MI->getDebugLoc();
960 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
961 FuncInfo->setHasSpills();
963 bool NonRI = false, SpillsVRS = false;
964 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
966 FuncInfo->setSpillsCR();
969 FuncInfo->setSpillsVRSAVE();
972 FuncInfo->setHasNonRISpills();
974 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
975 MBB.insert(MI, NewMIs[i]);
977 const MachineFrameInfo &MFI = *MF.getFrameInfo();
978 MachineMemOperand *MMO =
979 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
980 MachineMemOperand::MOLoad,
981 MFI.getObjectSize(FrameIdx),
982 MFI.getObjectAlignment(FrameIdx));
983 NewMIs.back()->addMemOperand(MF, MMO);
987 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
988 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
989 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
990 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
992 // Leave the CR# the same, but invert the condition.
993 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
997 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
998 unsigned Reg, MachineRegisterInfo *MRI) const {
999 // For some instructions, it is legal to fold ZERO into the RA register field.
1000 // A zero immediate should always be loaded with a single li.
1001 unsigned DefOpc = DefMI->getOpcode();
1002 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1004 if (!DefMI->getOperand(1).isImm())
1006 if (DefMI->getOperand(1).getImm() != 0)
1009 // Note that we cannot here invert the arguments of an isel in order to fold
1010 // a ZERO into what is presented as the second argument. All we have here
1011 // is the condition bit, and that might come from a CR-logical bit operation.
1013 const MCInstrDesc &UseMCID = UseMI->getDesc();
1015 // Only fold into real machine instructions.
1016 if (UseMCID.isPseudo())
1020 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1021 if (UseMI->getOperand(UseIdx).isReg() &&
1022 UseMI->getOperand(UseIdx).getReg() == Reg)
1025 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1026 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1028 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1030 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1031 // register (which might also be specified as a pointer class kind).
1032 if (UseInfo->isLookupPtrRegClass()) {
1033 if (UseInfo->RegClass /* Kind */ != 1)
1036 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1037 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1041 // Make sure this is not tied to an output register (or otherwise
1042 // constrained). This is true for ST?UX registers, for example, which
1043 // are tied to their output registers.
1044 if (UseInfo->Constraints != 0)
1048 if (UseInfo->isLookupPtrRegClass()) {
1049 bool isPPC64 = Subtarget.isPPC64();
1050 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1052 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1053 PPC::ZERO8 : PPC::ZERO;
1056 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1057 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1060 DefMI->eraseFromParent();
1065 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1066 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1068 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1073 // We should make sure that, if we're going to predicate both sides of a
1074 // condition (a diamond), that both sides don't define the counter register. We
1075 // can predicate counter-decrement-based branches, but while that predicates
1076 // the branching, it does not predicate the counter decrement. If we tried to
1077 // merge the triangle into one predicated block, we'd decrement the counter
1079 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1080 unsigned NumT, unsigned ExtraT,
1081 MachineBasicBlock &FMBB,
1082 unsigned NumF, unsigned ExtraF,
1083 const BranchProbability &Probability) const {
1084 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1088 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1089 // The predicated branches are identified by their type, not really by the
1090 // explicit presence of a predicate. Furthermore, some of them can be
1091 // predicated more than once. Because if conversion won't try to predicate
1092 // any instruction which already claims to be predicated (by returning true
1093 // here), always return false. In doing so, we let isPredicable() be the
1094 // final word on whether not the instruction can be (further) predicated.
1099 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1100 if (!MI->isTerminator())
1103 // Conditional branch is a special case.
1104 if (MI->isBranch() && !MI->isBarrier())
1107 return !isPredicated(MI);
1110 bool PPCInstrInfo::PredicateInstruction(
1112 const SmallVectorImpl<MachineOperand> &Pred) const {
1113 unsigned OpC = MI->getOpcode();
1114 if (OpC == PPC::BLR) {
1115 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1116 bool isPPC64 = Subtarget.isPPC64();
1117 MI->setDesc(get(Pred[0].getImm() ?
1118 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1119 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1120 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1121 MI->setDesc(get(PPC::BCLR));
1122 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1123 .addReg(Pred[1].getReg());
1124 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1125 MI->setDesc(get(PPC::BCLRn));
1126 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1127 .addReg(Pred[1].getReg());
1129 MI->setDesc(get(PPC::BCCLR));
1130 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1131 .addImm(Pred[0].getImm())
1132 .addReg(Pred[1].getReg());
1136 } else if (OpC == PPC::B) {
1137 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1138 bool isPPC64 = Subtarget.isPPC64();
1139 MI->setDesc(get(Pred[0].getImm() ?
1140 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1141 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1142 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1143 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1144 MI->RemoveOperand(0);
1146 MI->setDesc(get(PPC::BC));
1147 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1148 .addReg(Pred[1].getReg())
1150 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1151 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1152 MI->RemoveOperand(0);
1154 MI->setDesc(get(PPC::BCn));
1155 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1156 .addReg(Pred[1].getReg())
1159 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1160 MI->RemoveOperand(0);
1162 MI->setDesc(get(PPC::BCC));
1163 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1164 .addImm(Pred[0].getImm())
1165 .addReg(Pred[1].getReg())
1170 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1171 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1172 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1173 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1175 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1176 bool isPPC64 = Subtarget.isPPC64();
1178 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1179 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1180 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1181 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1182 .addReg(Pred[1].getReg());
1184 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1185 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1186 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1187 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1188 .addReg(Pred[1].getReg());
1192 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1193 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1194 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1195 .addImm(Pred[0].getImm())
1196 .addReg(Pred[1].getReg());
1203 bool PPCInstrInfo::SubsumesPredicate(
1204 const SmallVectorImpl<MachineOperand> &Pred1,
1205 const SmallVectorImpl<MachineOperand> &Pred2) const {
1206 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1207 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1209 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1211 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1214 // P1 can only subsume P2 if they test the same condition register.
1215 if (Pred1[1].getReg() != Pred2[1].getReg())
1218 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1219 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1224 // Does P1 subsume P2, e.g. GE subsumes GT.
1225 if (P1 == PPC::PRED_LE &&
1226 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1228 if (P1 == PPC::PRED_GE &&
1229 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1235 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1236 std::vector<MachineOperand> &Pred) const {
1237 // Note: At the present time, the contents of Pred from this function is
1238 // unused by IfConversion. This implementation follows ARM by pushing the
1239 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1240 // predicate, instructions defining CTR or CTR8 are also included as
1241 // predicate-defining instructions.
1243 const TargetRegisterClass *RCs[] =
1244 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1245 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1248 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1249 const MachineOperand &MO = MI->getOperand(i);
1250 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1251 const TargetRegisterClass *RC = RCs[c];
1253 if (MO.isDef() && RC->contains(MO.getReg())) {
1257 } else if (MO.isRegMask()) {
1258 for (TargetRegisterClass::iterator I = RC->begin(),
1259 IE = RC->end(); I != IE; ++I)
1260 if (MO.clobbersPhysReg(*I)) {
1271 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1272 unsigned OpC = MI->getOpcode();
1286 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1287 unsigned &SrcReg, unsigned &SrcReg2,
1288 int &Mask, int &Value) const {
1289 unsigned Opc = MI->getOpcode();
1292 default: return false;
1297 SrcReg = MI->getOperand(1).getReg();
1299 Value = MI->getOperand(2).getImm();
1308 SrcReg = MI->getOperand(1).getReg();
1309 SrcReg2 = MI->getOperand(2).getReg();
1314 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1315 unsigned SrcReg, unsigned SrcReg2,
1316 int Mask, int Value,
1317 const MachineRegisterInfo *MRI) const {
1321 int OpC = CmpInstr->getOpcode();
1322 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1324 // FP record forms set CR1 based on the execption status bits, not a
1325 // comparison with zero.
1326 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1329 // The record forms set the condition register based on a signed comparison
1330 // with zero (so says the ISA manual). This is not as straightforward as it
1331 // seems, however, because this is always a 64-bit comparison on PPC64, even
1332 // for instructions that are 32-bit in nature (like slw for example).
1333 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1334 // for equality checks (as those don't depend on the sign). On PPC64,
1335 // we are restricted to equality for unsigned 64-bit comparisons and for
1336 // signed 32-bit comparisons the applicability is more restricted.
1337 bool isPPC64 = Subtarget.isPPC64();
1338 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1339 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1340 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1342 // Get the unique definition of SrcReg.
1343 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1344 if (!MI) return false;
1345 int MIOpC = MI->getOpcode();
1347 bool equalityOnly = false;
1350 if (is32BitSignedCompare) {
1351 // We can perform this optimization only if MI is sign-extending.
1352 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1353 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1354 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1355 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1356 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1360 } else if (is32BitUnsignedCompare) {
1361 // We can perform this optimization, equality only, if MI is
1363 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1364 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1365 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1367 equalityOnly = true;
1371 equalityOnly = is64BitUnsignedCompare;
1373 equalityOnly = is32BitUnsignedCompare;
1376 // We need to check the uses of the condition register in order to reject
1377 // non-equality comparisons.
1378 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1379 IE = MRI->use_instr_end(); I != IE; ++I) {
1380 MachineInstr *UseMI = &*I;
1381 if (UseMI->getOpcode() == PPC::BCC) {
1382 unsigned Pred = UseMI->getOperand(0).getImm();
1383 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1385 } else if (UseMI->getOpcode() == PPC::ISEL ||
1386 UseMI->getOpcode() == PPC::ISEL8) {
1387 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1388 if (SubIdx != PPC::sub_eq)
1395 MachineBasicBlock::iterator I = CmpInstr;
1397 // Scan forward to find the first use of the compare.
1398 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1400 bool FoundUse = false;
1401 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1402 JE = MRI->use_instr_end(); J != JE; ++J)
1412 // There are two possible candidates which can be changed to set CR[01].
1413 // One is MI, the other is a SUB instruction.
1414 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1415 MachineInstr *Sub = nullptr;
1417 // MI is not a candidate for CMPrr.
1419 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1420 // same BB as the comparison. This is to allow the check below to avoid calls
1421 // (and other explicit clobbers); instead we should really check for these
1422 // more explicitly (in at least a few predecessors).
1423 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1424 // PPC does not have a record-form SUBri.
1429 const TargetRegisterInfo *TRI = &getRegisterInfo();
1432 // Get ready to iterate backward from CmpInstr.
1433 MachineBasicBlock::iterator E = MI,
1434 B = CmpInstr->getParent()->begin();
1436 for (; I != E && !noSub; --I) {
1437 const MachineInstr &Instr = *I;
1438 unsigned IOpC = Instr.getOpcode();
1440 if (&*I != CmpInstr && (
1441 Instr.modifiesRegister(PPC::CR0, TRI) ||
1442 Instr.readsRegister(PPC::CR0, TRI)))
1443 // This instruction modifies or uses the record condition register after
1444 // the one we want to change. While we could do this transformation, it
1445 // would likely not be profitable. This transformation removes one
1446 // instruction, and so even forcing RA to generate one move probably
1447 // makes it unprofitable.
1450 // Check whether CmpInstr can be made redundant by the current instruction.
1451 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1452 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1453 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1454 ((Instr.getOperand(1).getReg() == SrcReg &&
1455 Instr.getOperand(2).getReg() == SrcReg2) ||
1456 (Instr.getOperand(1).getReg() == SrcReg2 &&
1457 Instr.getOperand(2).getReg() == SrcReg))) {
1463 // The 'and' is below the comparison instruction.
1467 // Return false if no candidates exist.
1471 // The single candidate is called MI.
1475 MIOpC = MI->getOpcode();
1476 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1479 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1480 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1484 // FIXME: On the non-embedded POWER architectures, only some of the record
1485 // forms are fast, and we should use only the fast ones.
1487 // The defining instruction has a record form (or is already a record
1488 // form). It is possible, however, that we'll need to reverse the condition
1489 // code of the users.
1493 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1494 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1496 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1497 // needs to be updated to be based on SUB. Push the condition code
1498 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1499 // condition code of these operands will be modified.
1500 bool ShouldSwap = false;
1502 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1503 Sub->getOperand(2).getReg() == SrcReg;
1505 // The operands to subf are the opposite of sub, so only in the fixed-point
1506 // case, invert the order.
1507 ShouldSwap = !ShouldSwap;
1511 for (MachineRegisterInfo::use_instr_iterator
1512 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1514 MachineInstr *UseMI = &*I;
1515 if (UseMI->getOpcode() == PPC::BCC) {
1516 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1517 assert((!equalityOnly ||
1518 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1519 "Invalid predicate for equality-only optimization");
1520 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1521 PPC::getSwappedPredicate(Pred)));
1522 } else if (UseMI->getOpcode() == PPC::ISEL ||
1523 UseMI->getOpcode() == PPC::ISEL8) {
1524 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1525 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1526 "Invalid CR bit for equality-only optimization");
1528 if (NewSubReg == PPC::sub_lt)
1529 NewSubReg = PPC::sub_gt;
1530 else if (NewSubReg == PPC::sub_gt)
1531 NewSubReg = PPC::sub_lt;
1533 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1535 } else // We need to abort on a user we don't understand.
1539 // Create a new virtual register to hold the value of the CR set by the
1540 // record-form instruction. If the instruction was not previously in
1541 // record form, then set the kill flag on the CR.
1542 CmpInstr->eraseFromParent();
1544 MachineBasicBlock::iterator MII = MI;
1545 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1546 get(TargetOpcode::COPY), CRReg)
1547 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1549 if (MIOpC != NewOpC) {
1550 // We need to be careful here: we're replacing one instruction with
1551 // another, and we need to make sure that we get all of the right
1552 // implicit uses and defs. On the other hand, the caller may be holding
1553 // an iterator to this instruction, and so we can't delete it (this is
1554 // specifically the case if this is the instruction directly after the
1557 const MCInstrDesc &NewDesc = get(NewOpC);
1558 MI->setDesc(NewDesc);
1560 if (NewDesc.ImplicitDefs)
1561 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1562 *ImpDefs; ++ImpDefs)
1563 if (!MI->definesRegister(*ImpDefs))
1564 MI->addOperand(*MI->getParent()->getParent(),
1565 MachineOperand::CreateReg(*ImpDefs, true, true));
1566 if (NewDesc.ImplicitUses)
1567 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1568 *ImpUses; ++ImpUses)
1569 if (!MI->readsRegister(*ImpUses))
1570 MI->addOperand(*MI->getParent()->getParent(),
1571 MachineOperand::CreateReg(*ImpUses, false, true));
1574 // Modify the condition code of operands in OperandsToUpdate.
1575 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1576 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1577 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1578 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1580 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1581 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1586 /// GetInstSize - Return the number of bytes of code the specified
1587 /// instruction may be. This returns the maximum number of bytes.
1589 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1590 unsigned Opcode = MI->getOpcode();
1592 if (Opcode == PPC::INLINEASM) {
1593 const MachineFunction *MF = MI->getParent()->getParent();
1594 const char *AsmStr = MI->getOperand(0).getSymbolName();
1595 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1597 const MCInstrDesc &Desc = get(Opcode);
1598 return Desc.getSize();
1603 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1606 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1607 // (Altivec and scalar floating-point registers), we need to transform the
1608 // copies into subregister copies with other restrictions.
1609 struct PPCVSXFMAMutate : public MachineFunctionPass {
1611 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1612 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1617 const PPCTargetMachine *TM;
1618 const PPCInstrInfo *TII;
1621 bool processBlock(MachineBasicBlock &MBB) {
1622 bool Changed = false;
1624 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1625 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1627 MachineInstr *MI = I;
1629 // The default (A-type) VSX FMA form kills the addend (it is taken from
1630 // the target register, which is then updated to reflect the result of
1631 // the FMA). If the instruction, however, kills one of the registers
1632 // used for the product, then we can use the M-form instruction (which
1633 // will take that value from the to-be-defined register).
1635 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1639 // This pass is run after register coalescing, and so we're looking for
1640 // a situation like this:
1642 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1643 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1644 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1646 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1647 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1649 // Where we can eliminate the copy by changing from the A-type to the
1650 // M-type instruction. Specifically, for this example, this means:
1651 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1652 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1654 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1655 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1656 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1658 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1660 VNInfo *AddendValNo =
1661 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1662 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1664 // The addend and this instruction must be in the same block.
1666 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1669 // The addend must be a full copy within the same register class.
1671 if (!AddendMI->isFullCopy())
1674 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1675 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1676 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1677 MRI.getRegClass(AddendSrcReg))
1680 // If AddendSrcReg is a physical register, make sure the destination
1681 // register class contains it.
1682 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1683 ->contains(AddendSrcReg))
1687 // In theory, there could be other uses of the addend copy before this
1688 // fma. We could deal with this, but that would require additional
1689 // logic below and I suspect it will not occur in any relevant
1691 bool OtherUsers = false;
1692 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1694 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1702 // Find one of the product operands that is killed by this instruction.
1704 unsigned KilledProdOp = 0, OtherProdOp = 0;
1705 if (LIS->getInterval(MI->getOperand(2).getReg())
1706 .Query(FMAIdx).isKill()) {
1709 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1710 .Query(FMAIdx).isKill()) {
1715 // If there are no killed product operands, then this transformation is
1716 // likely not profitable.
1720 // In order to replace the addend here with the source of the copy,
1721 // it must still be live here.
1722 if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1725 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1727 unsigned AddReg = AddendMI->getOperand(1).getReg();
1728 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1729 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1731 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1732 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1733 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1735 bool AddRegKill = AddendMI->getOperand(1).isKill();
1736 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1737 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1739 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1740 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1741 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1743 unsigned OldFMAReg = MI->getOperand(0).getReg();
1745 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1746 "Addend copy not tied to old FMA output!");
1748 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1750 MI->getOperand(0).setReg(KilledProdReg);
1751 MI->getOperand(1).setReg(KilledProdReg);
1752 MI->getOperand(3).setReg(AddReg);
1753 MI->getOperand(2).setReg(OtherProdReg);
1755 MI->getOperand(0).setSubReg(KilledProdSubReg);
1756 MI->getOperand(1).setSubReg(KilledProdSubReg);
1757 MI->getOperand(3).setSubReg(AddSubReg);
1758 MI->getOperand(2).setSubReg(OtherProdSubReg);
1760 MI->getOperand(1).setIsKill(KilledProdRegKill);
1761 MI->getOperand(3).setIsKill(AddRegKill);
1762 MI->getOperand(2).setIsKill(OtherProdRegKill);
1764 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1765 MI->getOperand(3).setIsUndef(AddRegUndef);
1766 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1768 MI->setDesc(TII->get(AltOpc));
1770 DEBUG(dbgs() << " -> " << *MI);
1772 // The killed product operand was killed here, so we can reuse it now
1773 // for the result of the fma.
1775 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1776 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1777 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1779 MachineOperand &UseMO = *UI;
1780 MachineInstr *UseMI = UseMO.getParent();
1783 // Don't replace the result register of the copy we're about to erase.
1784 if (UseMI == AddendMI)
1787 UseMO.setReg(KilledProdReg);
1788 UseMO.setSubReg(KilledProdSubReg);
1791 // Extend the live intervals of the killed product operand to hold the
1794 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1795 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1797 // Don't add the segment that corresponds to the original copy.
1798 if (AI->valno == AddendValNo)
1801 VNInfo *NewFMAValNo =
1802 NewFMAInt.getNextValue(AI->start,
1803 LIS->getVNInfoAllocator());
1805 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1808 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1810 FMAInt.removeValNo(FMAValNo);
1811 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1813 // Remove the (now unused) copy.
1815 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1816 LIS->RemoveMachineInstrFromMaps(AddendMI);
1817 AddendMI->eraseFromParent();
1826 bool runOnMachineFunction(MachineFunction &MF) override {
1827 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1828 // If we don't have VSX then go ahead and return without doing
1830 if (!TM->getSubtargetImpl()->hasVSX())
1833 LIS = &getAnalysis<LiveIntervals>();
1835 TII = TM->getSubtargetImpl()->getInstrInfo();
1837 bool Changed = false;
1839 if (DisableVSXFMAMutate)
1842 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1843 MachineBasicBlock &B = *I++;
1844 if (processBlock(B))
1851 void getAnalysisUsage(AnalysisUsage &AU) const override {
1852 AU.addRequired<LiveIntervals>();
1853 AU.addPreserved<LiveIntervals>();
1854 AU.addRequired<SlotIndexes>();
1855 AU.addPreserved<SlotIndexes>();
1856 MachineFunctionPass::getAnalysisUsage(AU);
1861 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1862 "PowerPC VSX FMA Mutation", false, false)
1863 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1864 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1865 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1866 "PowerPC VSX FMA Mutation", false, false)
1868 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1870 char PPCVSXFMAMutate::ID = 0;
1872 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1875 #define DEBUG_TYPE "ppc-vsx-copy"
1878 void initializePPCVSXCopyPass(PassRegistry&);
1882 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1883 // (Altivec and scalar floating-point registers), we need to transform the
1884 // copies into subregister copies with other restrictions.
1885 struct PPCVSXCopy : public MachineFunctionPass {
1887 PPCVSXCopy() : MachineFunctionPass(ID) {
1888 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1891 const PPCTargetMachine *TM;
1892 const PPCInstrInfo *TII;
1894 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1895 MachineRegisterInfo &MRI) {
1896 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1897 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1898 } else if (RC->contains(Reg)) {
1905 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1906 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1909 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1910 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1913 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1914 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1918 bool processBlock(MachineBasicBlock &MBB) {
1919 bool Changed = false;
1921 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1922 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1924 MachineInstr *MI = I;
1925 if (!MI->isFullCopy())
1928 MachineOperand &DstMO = MI->getOperand(0);
1929 MachineOperand &SrcMO = MI->getOperand(1);
1931 if ( IsVSReg(DstMO.getReg(), MRI) &&
1932 !IsVSReg(SrcMO.getReg(), MRI)) {
1933 // This is a copy *to* a VSX register from a non-VSX register.
1936 const TargetRegisterClass *SrcRC =
1937 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1938 &PPC::VSLRCRegClass;
1939 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1940 IsVRReg(SrcMO.getReg(), MRI)) &&
1941 "Unknown source for a VSX copy");
1943 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1944 BuildMI(MBB, MI, MI->getDebugLoc(),
1945 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1946 .addImm(1) // add 1, not 0, because there is no implicit clearing
1947 // of the high bits.
1949 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1952 // The source of the original copy is now the new virtual register.
1953 SrcMO.setReg(NewVReg);
1954 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1955 IsVSReg(SrcMO.getReg(), MRI)) {
1956 // This is a copy *from* a VSX register to a non-VSX register.
1959 const TargetRegisterClass *DstRC =
1960 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1961 &PPC::VSLRCRegClass;
1962 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1963 IsVRReg(DstMO.getReg(), MRI)) &&
1964 "Unknown destination for a VSX copy");
1966 // Copy the VSX value into a new VSX register of the correct subclass.
1967 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1968 BuildMI(MBB, MI, MI->getDebugLoc(),
1969 TII->get(TargetOpcode::COPY), NewVReg)
1972 // Transform the original copy into a subregister extraction copy.
1973 SrcMO.setReg(NewVReg);
1974 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1983 bool runOnMachineFunction(MachineFunction &MF) override {
1984 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1985 // If we don't have VSX on the subtarget, don't do anything.
1986 if (!TM->getSubtargetImpl()->hasVSX())
1988 TII = TM->getSubtargetImpl()->getInstrInfo();
1990 bool Changed = false;
1992 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1993 MachineBasicBlock &B = *I++;
1994 if (processBlock(B))
2001 void getAnalysisUsage(AnalysisUsage &AU) const override {
2002 MachineFunctionPass::getAnalysisUsage(AU);
2007 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
2008 "PowerPC VSX Copy Legalization", false, false)
2010 char PPCVSXCopy::ID = 0;
2012 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
2015 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
2018 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2022 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2023 // registers (mostly because the ABI code still places all values into the
2024 // "traditional" floating-point and vector registers). Remove them here.
2025 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2027 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2028 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2031 const PPCTargetMachine *TM;
2032 const PPCInstrInfo *TII;
2035 bool processBlock(MachineBasicBlock &MBB) {
2036 bool Changed = false;
2038 SmallVector<MachineInstr *, 4> ToDelete;
2039 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2041 MachineInstr *MI = I;
2042 if (MI->getOpcode() == PPC::XXLOR &&
2043 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2044 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2045 ToDelete.push_back(MI);
2048 if (!ToDelete.empty())
2051 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2052 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2053 ToDelete[i]->eraseFromParent();
2060 bool runOnMachineFunction(MachineFunction &MF) override {
2061 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2062 // If we don't have VSX don't bother doing anything here.
2063 if (!TM->getSubtargetImpl()->hasVSX())
2065 TII = TM->getSubtargetImpl()->getInstrInfo();
2067 bool Changed = false;
2069 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2070 MachineBasicBlock &B = *I++;
2071 if (processBlock(B))
2078 void getAnalysisUsage(AnalysisUsage &AU) const override {
2079 MachineFunctionPass::getAnalysisUsage(AU);
2084 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2085 "PowerPC VSX Copy Cleanup", false, false)
2087 char PPCVSXCopyCleanup::ID = 0;
2089 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2092 #define DEBUG_TYPE "ppc-early-ret"
2093 STATISTIC(NumBCLR, "Number of early conditional returns");
2094 STATISTIC(NumBLR, "Number of early returns");
2097 void initializePPCEarlyReturnPass(PassRegistry&);
2101 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2102 // returns up, and create conditional returns, to avoid unnecessary
2103 // branch-to-blr sequences.
2104 struct PPCEarlyReturn : public MachineFunctionPass {
2106 PPCEarlyReturn() : MachineFunctionPass(ID) {
2107 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2110 const PPCTargetMachine *TM;
2111 const PPCInstrInfo *TII;
2114 bool processBlock(MachineBasicBlock &ReturnMBB) {
2115 bool Changed = false;
2117 MachineBasicBlock::iterator I = ReturnMBB.begin();
2118 I = ReturnMBB.SkipPHIsAndLabels(I);
2120 // The block must be essentially empty except for the blr.
2121 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2122 I != ReturnMBB.getLastNonDebugInstr())
2125 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2126 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2127 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2128 bool OtherReference = false, BlockChanged = false;
2129 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2130 if (J->getOpcode() == PPC::B) {
2131 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2132 // This is an unconditional branch to the return. Replace the
2133 // branch with a blr.
2134 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2135 MachineBasicBlock::iterator K = J--;
2136 K->eraseFromParent();
2137 BlockChanged = true;
2141 } else if (J->getOpcode() == PPC::BCC) {
2142 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2143 // This is a conditional branch to the return. Replace the branch
2145 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2146 .addImm(J->getOperand(0).getImm())
2147 .addReg(J->getOperand(1).getReg());
2148 MachineBasicBlock::iterator K = J--;
2149 K->eraseFromParent();
2150 BlockChanged = true;
2154 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2155 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2156 // This is a conditional branch to the return. Replace the branch
2158 BuildMI(**PI, J, J->getDebugLoc(),
2159 TII->get(J->getOpcode() == PPC::BC ?
2160 PPC::BCLR : PPC::BCLRn))
2161 .addReg(J->getOperand(0).getReg());
2162 MachineBasicBlock::iterator K = J--;
2163 K->eraseFromParent();
2164 BlockChanged = true;
2168 } else if (J->isBranch()) {
2169 if (J->isIndirectBranch()) {
2170 if (ReturnMBB.hasAddressTaken())
2171 OtherReference = true;
2173 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2174 if (J->getOperand(i).isMBB() &&
2175 J->getOperand(i).getMBB() == &ReturnMBB)
2176 OtherReference = true;
2177 } else if (!J->isTerminator() && !J->isDebugValue())
2180 if (J == (*PI)->begin())
2186 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2187 OtherReference = true;
2189 // Predecessors are stored in a vector and can't be removed here.
2190 if (!OtherReference && BlockChanged) {
2191 PredToRemove.push_back(*PI);
2198 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2199 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2201 if (Changed && !ReturnMBB.hasAddressTaken()) {
2202 // We now might be able to merge this blr-only block into its
2203 // by-layout predecessor.
2204 if (ReturnMBB.pred_size() == 1 &&
2205 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2206 // Move the blr into the preceding block.
2207 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2208 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2209 PrevMBB.removeSuccessor(&ReturnMBB);
2212 if (ReturnMBB.pred_empty())
2213 ReturnMBB.eraseFromParent();
2220 bool runOnMachineFunction(MachineFunction &MF) override {
2221 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2222 TII = TM->getSubtargetImpl()->getInstrInfo();
2224 bool Changed = false;
2226 // If the function does not have at least two blocks, then there is
2231 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2232 MachineBasicBlock &B = *I++;
2233 if (processBlock(B))
2240 void getAnalysisUsage(AnalysisUsage &AU) const override {
2241 MachineFunctionPass::getAnalysisUsage(AU);
2246 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2247 "PowerPC Early-Return Creation", false, false)
2249 char PPCEarlyReturn::ID = 0;
2251 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }