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/SlotIndexes.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/raw_ostream.h"
38 #define GET_INSTRMAP_INFO
39 #define GET_INSTRINFO_CTOR_DTOR
40 #include "PPCGenInstrInfo.inc"
45 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
46 cl::desc("Disable analysis for CTR loops"));
48 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
49 cl::desc("Disable compare instruction optimization"), cl::Hidden);
51 static cl::opt<bool> DisableVSXFMAMutate("disable-ppc-vsx-fma-mutation",
52 cl::desc("Disable VSX FMA instruction mutation"), cl::Hidden);
54 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
55 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
58 // Pin the vtable to this file.
59 void PPCInstrInfo::anchor() {}
61 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
62 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
63 TM(tm), RI(*TM.getSubtargetImpl()) {}
65 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
66 /// this target when scheduling the DAG.
67 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
68 const TargetMachine *TM,
69 const ScheduleDAG *DAG) const {
70 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
71 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
72 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
73 const InstrItineraryData *II = TM->getInstrItineraryData();
74 return new ScoreboardHazardRecognizer(II, DAG);
77 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
80 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
81 /// to use for this target when scheduling the DAG.
82 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
83 const InstrItineraryData *II,
84 const ScheduleDAG *DAG) const {
85 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
87 if (Directive == PPC::DIR_PWR7)
88 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
90 // Most subtargets use a PPC970 recognizer.
91 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
92 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
93 assert(TM.getInstrInfo() && "No InstrInfo?");
95 return new PPCHazardRecognizer970(TM);
98 return new ScoreboardHazardRecognizer(II, DAG);
102 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
103 const MachineInstr *DefMI, unsigned DefIdx,
104 const MachineInstr *UseMI,
105 unsigned UseIdx) const {
106 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
109 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
110 unsigned Reg = DefMO.getReg();
112 const TargetRegisterInfo *TRI = &getRegisterInfo();
114 if (TRI->isVirtualRegister(Reg)) {
115 const MachineRegisterInfo *MRI =
116 &DefMI->getParent()->getParent()->getRegInfo();
117 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
118 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
120 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
121 PPC::CRBITRCRegClass.contains(Reg);
124 if (UseMI->isBranch() && IsRegCR) {
126 Latency = getInstrLatency(ItinData, DefMI);
128 // On some cores, there is an additional delay between writing to a condition
129 // register, and using it from a branch.
130 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
151 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
152 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
153 unsigned &SrcReg, unsigned &DstReg,
154 unsigned &SubIdx) const {
155 switch (MI.getOpcode()) {
156 default: return false;
158 case PPC::EXTSW_32_64:
159 SrcReg = MI.getOperand(1).getReg();
160 DstReg = MI.getOperand(0).getReg();
161 SubIdx = PPC::sub_32;
166 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
167 int &FrameIndex) const {
168 // Note: This list must be kept consistent with LoadRegFromStackSlot.
169 switch (MI->getOpcode()) {
175 case PPC::RESTORE_CR:
176 case PPC::RESTORE_CRBIT:
179 case PPC::RESTORE_VRSAVE:
180 // Check for the operands added by addFrameReference (the immediate is the
181 // offset which defaults to 0).
182 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
183 MI->getOperand(2).isFI()) {
184 FrameIndex = MI->getOperand(2).getIndex();
185 return MI->getOperand(0).getReg();
192 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
193 int &FrameIndex) const {
194 // Note: This list must be kept consistent with StoreRegToStackSlot.
195 switch (MI->getOpcode()) {
202 case PPC::SPILL_CRBIT:
205 case PPC::SPILL_VRSAVE:
206 // Check for the operands added by addFrameReference (the immediate is the
207 // offset which defaults to 0).
208 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
209 MI->getOperand(2).isFI()) {
210 FrameIndex = MI->getOperand(2).getIndex();
211 return MI->getOperand(0).getReg();
218 // commuteInstruction - We can commute rlwimi instructions, but only if the
219 // rotate amt is zero. We also have to munge the immediates a bit.
221 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
222 MachineFunction &MF = *MI->getParent()->getParent();
224 // Normal instructions can be commuted the obvious way.
225 if (MI->getOpcode() != PPC::RLWIMI &&
226 MI->getOpcode() != PPC::RLWIMIo &&
227 MI->getOpcode() != PPC::RLWIMI8 &&
228 MI->getOpcode() != PPC::RLWIMI8o)
229 return TargetInstrInfo::commuteInstruction(MI, NewMI);
231 // Cannot commute if it has a non-zero rotate count.
232 if (MI->getOperand(3).getImm() != 0)
235 // If we have a zero rotate count, we have:
237 // Op0 = (Op1 & ~M) | (Op2 & M)
239 // M = mask((ME+1)&31, (MB-1)&31)
240 // Op0 = (Op2 & ~M) | (Op1 & M)
243 unsigned Reg0 = MI->getOperand(0).getReg();
244 unsigned Reg1 = MI->getOperand(1).getReg();
245 unsigned Reg2 = MI->getOperand(2).getReg();
246 unsigned SubReg1 = MI->getOperand(1).getSubReg();
247 unsigned SubReg2 = MI->getOperand(2).getSubReg();
248 bool Reg1IsKill = MI->getOperand(1).isKill();
249 bool Reg2IsKill = MI->getOperand(2).isKill();
250 bool ChangeReg0 = false;
251 // If machine instrs are no longer in two-address forms, update
252 // destination register as well.
254 // Must be two address instruction!
255 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
256 "Expecting a two-address instruction!");
257 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
263 unsigned MB = MI->getOperand(4).getImm();
264 unsigned ME = MI->getOperand(5).getImm();
267 // Create a new instruction.
268 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
269 bool Reg0IsDead = MI->getOperand(0).isDead();
270 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
271 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
272 .addReg(Reg2, getKillRegState(Reg2IsKill))
273 .addReg(Reg1, getKillRegState(Reg1IsKill))
275 .addImm((MB-1) & 31);
279 MI->getOperand(0).setReg(Reg2);
280 MI->getOperand(0).setSubReg(SubReg2);
282 MI->getOperand(2).setReg(Reg1);
283 MI->getOperand(1).setReg(Reg2);
284 MI->getOperand(2).setSubReg(SubReg1);
285 MI->getOperand(1).setSubReg(SubReg2);
286 MI->getOperand(2).setIsKill(Reg1IsKill);
287 MI->getOperand(1).setIsKill(Reg2IsKill);
289 // Swap the mask around.
290 MI->getOperand(4).setImm((ME+1) & 31);
291 MI->getOperand(5).setImm((MB-1) & 31);
295 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
296 unsigned &SrcOpIdx2) const {
297 // For VSX A-Type FMA instructions, it is the first two operands that can be
298 // commuted, however, because the non-encoded tied input operand is listed
299 // first, the operands to swap are actually the second and third.
301 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
303 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
310 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
311 MachineBasicBlock::iterator MI) const {
312 // This function is used for scheduling, and the nop wanted here is the type
313 // that terminates dispatch groups on the POWER cores.
314 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
317 default: Opcode = PPC::NOP; break;
318 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
319 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
323 BuildMI(MBB, MI, DL, get(Opcode));
327 // Note: If the condition register is set to CTR or CTR8 then this is a
328 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
329 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
330 MachineBasicBlock *&FBB,
331 SmallVectorImpl<MachineOperand> &Cond,
332 bool AllowModify) const {
333 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
335 // If the block has no terminators, it just falls into the block after it.
336 MachineBasicBlock::iterator I = MBB.end();
337 if (I == MBB.begin())
340 while (I->isDebugValue()) {
341 if (I == MBB.begin())
345 if (!isUnpredicatedTerminator(I))
348 // Get the last instruction in the block.
349 MachineInstr *LastInst = I;
351 // If there is only one terminator instruction, process it.
352 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
353 if (LastInst->getOpcode() == PPC::B) {
354 if (!LastInst->getOperand(0).isMBB())
356 TBB = LastInst->getOperand(0).getMBB();
358 } else if (LastInst->getOpcode() == PPC::BCC) {
359 if (!LastInst->getOperand(2).isMBB())
361 // Block ends with fall-through condbranch.
362 TBB = LastInst->getOperand(2).getMBB();
363 Cond.push_back(LastInst->getOperand(0));
364 Cond.push_back(LastInst->getOperand(1));
366 } else if (LastInst->getOpcode() == PPC::BC) {
367 if (!LastInst->getOperand(1).isMBB())
369 // Block ends with fall-through condbranch.
370 TBB = LastInst->getOperand(1).getMBB();
371 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
372 Cond.push_back(LastInst->getOperand(0));
374 } else if (LastInst->getOpcode() == PPC::BCn) {
375 if (!LastInst->getOperand(1).isMBB())
377 // Block ends with fall-through condbranch.
378 TBB = LastInst->getOperand(1).getMBB();
379 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
380 Cond.push_back(LastInst->getOperand(0));
382 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
383 LastInst->getOpcode() == PPC::BDNZ) {
384 if (!LastInst->getOperand(0).isMBB())
386 if (DisableCTRLoopAnal)
388 TBB = LastInst->getOperand(0).getMBB();
389 Cond.push_back(MachineOperand::CreateImm(1));
390 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
393 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
394 LastInst->getOpcode() == PPC::BDZ) {
395 if (!LastInst->getOperand(0).isMBB())
397 if (DisableCTRLoopAnal)
399 TBB = LastInst->getOperand(0).getMBB();
400 Cond.push_back(MachineOperand::CreateImm(0));
401 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
406 // Otherwise, don't know what this is.
410 // Get the instruction before it if it's a terminator.
411 MachineInstr *SecondLastInst = I;
413 // If there are three terminators, we don't know what sort of block this is.
414 if (SecondLastInst && I != MBB.begin() &&
415 isUnpredicatedTerminator(--I))
418 // If the block ends with PPC::B and PPC:BCC, handle it.
419 if (SecondLastInst->getOpcode() == PPC::BCC &&
420 LastInst->getOpcode() == PPC::B) {
421 if (!SecondLastInst->getOperand(2).isMBB() ||
422 !LastInst->getOperand(0).isMBB())
424 TBB = SecondLastInst->getOperand(2).getMBB();
425 Cond.push_back(SecondLastInst->getOperand(0));
426 Cond.push_back(SecondLastInst->getOperand(1));
427 FBB = LastInst->getOperand(0).getMBB();
429 } else if (SecondLastInst->getOpcode() == PPC::BC &&
430 LastInst->getOpcode() == PPC::B) {
431 if (!SecondLastInst->getOperand(1).isMBB() ||
432 !LastInst->getOperand(0).isMBB())
434 TBB = SecondLastInst->getOperand(1).getMBB();
435 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
436 Cond.push_back(SecondLastInst->getOperand(0));
437 FBB = LastInst->getOperand(0).getMBB();
439 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
440 LastInst->getOpcode() == PPC::B) {
441 if (!SecondLastInst->getOperand(1).isMBB() ||
442 !LastInst->getOperand(0).isMBB())
444 TBB = SecondLastInst->getOperand(1).getMBB();
445 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
446 Cond.push_back(SecondLastInst->getOperand(0));
447 FBB = LastInst->getOperand(0).getMBB();
449 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
450 SecondLastInst->getOpcode() == PPC::BDNZ) &&
451 LastInst->getOpcode() == PPC::B) {
452 if (!SecondLastInst->getOperand(0).isMBB() ||
453 !LastInst->getOperand(0).isMBB())
455 if (DisableCTRLoopAnal)
457 TBB = SecondLastInst->getOperand(0).getMBB();
458 Cond.push_back(MachineOperand::CreateImm(1));
459 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
461 FBB = LastInst->getOperand(0).getMBB();
463 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
464 SecondLastInst->getOpcode() == PPC::BDZ) &&
465 LastInst->getOpcode() == PPC::B) {
466 if (!SecondLastInst->getOperand(0).isMBB() ||
467 !LastInst->getOperand(0).isMBB())
469 if (DisableCTRLoopAnal)
471 TBB = SecondLastInst->getOperand(0).getMBB();
472 Cond.push_back(MachineOperand::CreateImm(0));
473 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
475 FBB = LastInst->getOperand(0).getMBB();
479 // If the block ends with two PPC:Bs, handle it. The second one is not
480 // executed, so remove it.
481 if (SecondLastInst->getOpcode() == PPC::B &&
482 LastInst->getOpcode() == PPC::B) {
483 if (!SecondLastInst->getOperand(0).isMBB())
485 TBB = SecondLastInst->getOperand(0).getMBB();
488 I->eraseFromParent();
492 // Otherwise, can't handle this.
496 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
497 MachineBasicBlock::iterator I = MBB.end();
498 if (I == MBB.begin()) return 0;
500 while (I->isDebugValue()) {
501 if (I == MBB.begin())
505 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
506 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
507 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
508 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
511 // Remove the branch.
512 I->eraseFromParent();
516 if (I == MBB.begin()) return 1;
518 if (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();
530 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
531 MachineBasicBlock *FBB,
532 const SmallVectorImpl<MachineOperand> &Cond,
534 // Shouldn't be a fall through.
535 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
536 assert((Cond.size() == 2 || Cond.size() == 0) &&
537 "PPC branch conditions have two components!");
539 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
543 if (Cond.empty()) // Unconditional branch
544 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
545 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
546 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
547 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
548 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
549 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
550 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
551 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
552 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
553 else // Conditional branch
554 BuildMI(&MBB, DL, get(PPC::BCC))
555 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
559 // Two-way Conditional Branch.
560 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
561 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
562 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
563 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
564 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
565 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
566 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
567 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
569 BuildMI(&MBB, DL, get(PPC::BCC))
570 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
571 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
576 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
577 const SmallVectorImpl<MachineOperand> &Cond,
578 unsigned TrueReg, unsigned FalseReg,
579 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
580 if (!TM.getSubtargetImpl()->hasISEL())
583 if (Cond.size() != 2)
586 // If this is really a bdnz-like condition, then it cannot be turned into a
588 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
591 // Check register classes.
592 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
593 const TargetRegisterClass *RC =
594 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
598 // isel is for regular integer GPRs only.
599 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
600 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
601 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
602 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
605 // FIXME: These numbers are for the A2, how well they work for other cores is
606 // an open question. On the A2, the isel instruction has a 2-cycle latency
607 // but single-cycle throughput. These numbers are used in combination with
608 // the MispredictPenalty setting from the active SchedMachineModel.
616 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
617 MachineBasicBlock::iterator MI, DebugLoc dl,
619 const SmallVectorImpl<MachineOperand> &Cond,
620 unsigned TrueReg, unsigned FalseReg) const {
621 assert(Cond.size() == 2 &&
622 "PPC branch conditions have two components!");
624 assert(TM.getSubtargetImpl()->hasISEL() &&
625 "Cannot insert select on target without ISEL support");
627 // Get the register classes.
628 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
629 const TargetRegisterClass *RC =
630 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
631 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
633 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
634 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
636 PPC::GPRCRegClass.hasSubClassEq(RC) ||
637 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
638 "isel is for regular integer GPRs only");
640 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
641 unsigned SelectPred = Cond[0].getImm();
645 switch (SelectPred) {
646 default: llvm_unreachable("invalid predicate for isel");
647 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
648 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
649 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
650 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
651 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
652 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
653 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
654 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
655 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
656 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
659 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
660 SecondReg = SwapOps ? TrueReg : FalseReg;
662 // The first input register of isel cannot be r0. If it is a member
663 // of a register class that can be r0, then copy it first (the
664 // register allocator should eliminate the copy).
665 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
666 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
667 const TargetRegisterClass *FirstRC =
668 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
669 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
670 unsigned OldFirstReg = FirstReg;
671 FirstReg = MRI.createVirtualRegister(FirstRC);
672 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
673 .addReg(OldFirstReg);
676 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
677 .addReg(FirstReg).addReg(SecondReg)
678 .addReg(Cond[1].getReg(), 0, SubIdx);
681 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
682 MachineBasicBlock::iterator I, DebugLoc DL,
683 unsigned DestReg, unsigned SrcReg,
684 bool KillSrc) const {
685 // We can end up with self copies and similar things as a result of VSX copy
686 // legalization. Promote them here.
687 const TargetRegisterInfo *TRI = &getRegisterInfo();
688 if (PPC::F8RCRegClass.contains(DestReg) &&
689 PPC::VSLRCRegClass.contains(SrcReg)) {
691 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
693 if (VSXSelfCopyCrash && SrcReg == SuperReg)
694 llvm_unreachable("nop VSX copy");
697 } else if (PPC::VRRCRegClass.contains(DestReg) &&
698 PPC::VSHRCRegClass.contains(SrcReg)) {
700 TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
702 if (VSXSelfCopyCrash && SrcReg == SuperReg)
703 llvm_unreachable("nop VSX copy");
706 } else if (PPC::F8RCRegClass.contains(SrcReg) &&
707 PPC::VSLRCRegClass.contains(DestReg)) {
709 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
711 if (VSXSelfCopyCrash && DestReg == SuperReg)
712 llvm_unreachable("nop VSX copy");
715 } else if (PPC::VRRCRegClass.contains(SrcReg) &&
716 PPC::VSHRCRegClass.contains(DestReg)) {
718 TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
720 if (VSXSelfCopyCrash && DestReg == SuperReg)
721 llvm_unreachable("nop VSX copy");
727 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
729 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
731 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
733 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
735 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
737 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
738 // There are two different ways this can be done:
739 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
740 // issue in VSU pipeline 0.
741 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
742 // can go to either pipeline.
743 // We'll always use xxlor here, because in practically all cases where
744 // copies are generated, they are close enough to some use that the
745 // lower-latency form is preferable.
747 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg))
749 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
752 llvm_unreachable("Impossible reg-to-reg copy");
754 const MCInstrDesc &MCID = get(Opc);
755 if (MCID.getNumOperands() == 3)
756 BuildMI(MBB, I, DL, MCID, DestReg)
757 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
759 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
762 // This function returns true if a CR spill is necessary and false otherwise.
764 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
765 unsigned SrcReg, bool isKill,
767 const TargetRegisterClass *RC,
768 SmallVectorImpl<MachineInstr*> &NewMIs,
769 bool &NonRI, bool &SpillsVRS) const{
770 // Note: If additional store instructions are added here,
771 // update isStoreToStackSlot.
774 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
775 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
776 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
778 getKillRegState(isKill)),
780 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
781 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
782 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
784 getKillRegState(isKill)),
786 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
787 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
789 getKillRegState(isKill)),
791 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
792 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
794 getKillRegState(isKill)),
796 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
797 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
799 getKillRegState(isKill)),
802 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
803 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
805 getKillRegState(isKill)),
808 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
809 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
811 getKillRegState(isKill)),
814 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
815 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
817 getKillRegState(isKill)),
820 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
821 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
823 getKillRegState(isKill)),
826 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
827 assert(TM.getSubtargetImpl()->isDarwin() &&
828 "VRSAVE only needs spill/restore on Darwin");
829 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
831 getKillRegState(isKill)),
835 llvm_unreachable("Unknown regclass!");
842 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
843 MachineBasicBlock::iterator MI,
844 unsigned SrcReg, bool isKill, int FrameIdx,
845 const TargetRegisterClass *RC,
846 const TargetRegisterInfo *TRI) const {
847 MachineFunction &MF = *MBB.getParent();
848 SmallVector<MachineInstr*, 4> NewMIs;
850 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
851 FuncInfo->setHasSpills();
853 bool NonRI = false, SpillsVRS = false;
854 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
856 FuncInfo->setSpillsCR();
859 FuncInfo->setSpillsVRSAVE();
862 FuncInfo->setHasNonRISpills();
864 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
865 MBB.insert(MI, NewMIs[i]);
867 const MachineFrameInfo &MFI = *MF.getFrameInfo();
868 MachineMemOperand *MMO =
869 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
870 MachineMemOperand::MOStore,
871 MFI.getObjectSize(FrameIdx),
872 MFI.getObjectAlignment(FrameIdx));
873 NewMIs.back()->addMemOperand(MF, MMO);
877 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
878 unsigned DestReg, int FrameIdx,
879 const TargetRegisterClass *RC,
880 SmallVectorImpl<MachineInstr*> &NewMIs,
881 bool &NonRI, bool &SpillsVRS) const{
882 // Note: If additional load instructions are added here,
883 // update isLoadFromStackSlot.
885 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
886 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
887 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
888 DestReg), FrameIdx));
889 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
890 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
891 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
893 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
894 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
896 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
897 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
899 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
900 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
901 get(PPC::RESTORE_CR), DestReg),
904 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
905 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
906 get(PPC::RESTORE_CRBIT), DestReg),
909 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
910 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
913 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
914 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
917 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
918 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
921 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
922 assert(TM.getSubtargetImpl()->isDarwin() &&
923 "VRSAVE only needs spill/restore on Darwin");
924 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
925 get(PPC::RESTORE_VRSAVE),
930 llvm_unreachable("Unknown regclass!");
937 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
938 MachineBasicBlock::iterator MI,
939 unsigned DestReg, int FrameIdx,
940 const TargetRegisterClass *RC,
941 const TargetRegisterInfo *TRI) const {
942 MachineFunction &MF = *MBB.getParent();
943 SmallVector<MachineInstr*, 4> NewMIs;
945 if (MI != MBB.end()) DL = MI->getDebugLoc();
947 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
948 FuncInfo->setHasSpills();
950 bool NonRI = false, SpillsVRS = false;
951 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
953 FuncInfo->setSpillsCR();
956 FuncInfo->setSpillsVRSAVE();
959 FuncInfo->setHasNonRISpills();
961 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
962 MBB.insert(MI, NewMIs[i]);
964 const MachineFrameInfo &MFI = *MF.getFrameInfo();
965 MachineMemOperand *MMO =
966 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
967 MachineMemOperand::MOLoad,
968 MFI.getObjectSize(FrameIdx),
969 MFI.getObjectAlignment(FrameIdx));
970 NewMIs.back()->addMemOperand(MF, MMO);
974 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
975 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
976 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
977 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
979 // Leave the CR# the same, but invert the condition.
980 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
984 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
985 unsigned Reg, MachineRegisterInfo *MRI) const {
986 // For some instructions, it is legal to fold ZERO into the RA register field.
987 // A zero immediate should always be loaded with a single li.
988 unsigned DefOpc = DefMI->getOpcode();
989 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
991 if (!DefMI->getOperand(1).isImm())
993 if (DefMI->getOperand(1).getImm() != 0)
996 // Note that we cannot here invert the arguments of an isel in order to fold
997 // a ZERO into what is presented as the second argument. All we have here
998 // is the condition bit, and that might come from a CR-logical bit operation.
1000 const MCInstrDesc &UseMCID = UseMI->getDesc();
1002 // Only fold into real machine instructions.
1003 if (UseMCID.isPseudo())
1007 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1008 if (UseMI->getOperand(UseIdx).isReg() &&
1009 UseMI->getOperand(UseIdx).getReg() == Reg)
1012 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1013 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1015 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1017 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1018 // register (which might also be specified as a pointer class kind).
1019 if (UseInfo->isLookupPtrRegClass()) {
1020 if (UseInfo->RegClass /* Kind */ != 1)
1023 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1024 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1028 // Make sure this is not tied to an output register (or otherwise
1029 // constrained). This is true for ST?UX registers, for example, which
1030 // are tied to their output registers.
1031 if (UseInfo->Constraints != 0)
1035 if (UseInfo->isLookupPtrRegClass()) {
1036 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1037 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1039 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1040 PPC::ZERO8 : PPC::ZERO;
1043 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1044 UseMI->getOperand(UseIdx).setReg(ZeroReg);
1047 DefMI->eraseFromParent();
1052 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1053 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1055 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1060 // We should make sure that, if we're going to predicate both sides of a
1061 // condition (a diamond), that both sides don't define the counter register. We
1062 // can predicate counter-decrement-based branches, but while that predicates
1063 // the branching, it does not predicate the counter decrement. If we tried to
1064 // merge the triangle into one predicated block, we'd decrement the counter
1066 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1067 unsigned NumT, unsigned ExtraT,
1068 MachineBasicBlock &FMBB,
1069 unsigned NumF, unsigned ExtraF,
1070 const BranchProbability &Probability) const {
1071 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1075 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1076 // The predicated branches are identified by their type, not really by the
1077 // explicit presence of a predicate. Furthermore, some of them can be
1078 // predicated more than once. Because if conversion won't try to predicate
1079 // any instruction which already claims to be predicated (by returning true
1080 // here), always return false. In doing so, we let isPredicable() be the
1081 // final word on whether not the instruction can be (further) predicated.
1086 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1087 if (!MI->isTerminator())
1090 // Conditional branch is a special case.
1091 if (MI->isBranch() && !MI->isBarrier())
1094 return !isPredicated(MI);
1097 bool PPCInstrInfo::PredicateInstruction(
1099 const SmallVectorImpl<MachineOperand> &Pred) const {
1100 unsigned OpC = MI->getOpcode();
1101 if (OpC == PPC::BLR) {
1102 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1103 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1104 MI->setDesc(get(Pred[0].getImm() ?
1105 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1106 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1107 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1108 MI->setDesc(get(PPC::BCLR));
1109 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1110 .addReg(Pred[1].getReg());
1111 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1112 MI->setDesc(get(PPC::BCLRn));
1113 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1114 .addReg(Pred[1].getReg());
1116 MI->setDesc(get(PPC::BCCLR));
1117 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1118 .addImm(Pred[0].getImm())
1119 .addReg(Pred[1].getReg());
1123 } else if (OpC == PPC::B) {
1124 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1125 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1126 MI->setDesc(get(Pred[0].getImm() ?
1127 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1128 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1129 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1130 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1131 MI->RemoveOperand(0);
1133 MI->setDesc(get(PPC::BC));
1134 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1135 .addReg(Pred[1].getReg())
1137 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1138 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1139 MI->RemoveOperand(0);
1141 MI->setDesc(get(PPC::BCn));
1142 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1143 .addReg(Pred[1].getReg())
1146 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1147 MI->RemoveOperand(0);
1149 MI->setDesc(get(PPC::BCC));
1150 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1151 .addImm(Pred[0].getImm())
1152 .addReg(Pred[1].getReg())
1157 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1158 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1159 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1160 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1162 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1163 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1165 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1166 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1167 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1168 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1169 .addReg(Pred[1].getReg());
1171 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1172 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1173 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1174 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1175 .addReg(Pred[1].getReg());
1179 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1180 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1181 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1182 .addImm(Pred[0].getImm())
1183 .addReg(Pred[1].getReg());
1190 bool PPCInstrInfo::SubsumesPredicate(
1191 const SmallVectorImpl<MachineOperand> &Pred1,
1192 const SmallVectorImpl<MachineOperand> &Pred2) const {
1193 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1194 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1196 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1198 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1201 // P1 can only subsume P2 if they test the same condition register.
1202 if (Pred1[1].getReg() != Pred2[1].getReg())
1205 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1206 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1211 // Does P1 subsume P2, e.g. GE subsumes GT.
1212 if (P1 == PPC::PRED_LE &&
1213 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1215 if (P1 == PPC::PRED_GE &&
1216 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1222 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1223 std::vector<MachineOperand> &Pred) const {
1224 // Note: At the present time, the contents of Pred from this function is
1225 // unused by IfConversion. This implementation follows ARM by pushing the
1226 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1227 // predicate, instructions defining CTR or CTR8 are also included as
1228 // predicate-defining instructions.
1230 const TargetRegisterClass *RCs[] =
1231 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1232 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1235 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1236 const MachineOperand &MO = MI->getOperand(i);
1237 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1238 const TargetRegisterClass *RC = RCs[c];
1240 if (MO.isDef() && RC->contains(MO.getReg())) {
1244 } else if (MO.isRegMask()) {
1245 for (TargetRegisterClass::iterator I = RC->begin(),
1246 IE = RC->end(); I != IE; ++I)
1247 if (MO.clobbersPhysReg(*I)) {
1258 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1259 unsigned OpC = MI->getOpcode();
1273 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1274 unsigned &SrcReg, unsigned &SrcReg2,
1275 int &Mask, int &Value) const {
1276 unsigned Opc = MI->getOpcode();
1279 default: return false;
1284 SrcReg = MI->getOperand(1).getReg();
1286 Value = MI->getOperand(2).getImm();
1295 SrcReg = MI->getOperand(1).getReg();
1296 SrcReg2 = MI->getOperand(2).getReg();
1301 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1302 unsigned SrcReg, unsigned SrcReg2,
1303 int Mask, int Value,
1304 const MachineRegisterInfo *MRI) const {
1308 int OpC = CmpInstr->getOpcode();
1309 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1311 // FP record forms set CR1 based on the execption status bits, not a
1312 // comparison with zero.
1313 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1316 // The record forms set the condition register based on a signed comparison
1317 // with zero (so says the ISA manual). This is not as straightforward as it
1318 // seems, however, because this is always a 64-bit comparison on PPC64, even
1319 // for instructions that are 32-bit in nature (like slw for example).
1320 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1321 // for equality checks (as those don't depend on the sign). On PPC64,
1322 // we are restricted to equality for unsigned 64-bit comparisons and for
1323 // signed 32-bit comparisons the applicability is more restricted.
1324 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1325 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1326 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1327 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1329 // Get the unique definition of SrcReg.
1330 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1331 if (!MI) return false;
1332 int MIOpC = MI->getOpcode();
1334 bool equalityOnly = false;
1337 if (is32BitSignedCompare) {
1338 // We can perform this optimization only if MI is sign-extending.
1339 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1340 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1341 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1342 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1343 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1347 } else if (is32BitUnsignedCompare) {
1348 // We can perform this optimization, equality only, if MI is
1350 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1351 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1352 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1354 equalityOnly = true;
1358 equalityOnly = is64BitUnsignedCompare;
1360 equalityOnly = is32BitUnsignedCompare;
1363 // We need to check the uses of the condition register in order to reject
1364 // non-equality comparisons.
1365 for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1366 IE = MRI->use_instr_end(); I != IE; ++I) {
1367 MachineInstr *UseMI = &*I;
1368 if (UseMI->getOpcode() == PPC::BCC) {
1369 unsigned Pred = UseMI->getOperand(0).getImm();
1370 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1372 } else if (UseMI->getOpcode() == PPC::ISEL ||
1373 UseMI->getOpcode() == PPC::ISEL8) {
1374 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1375 if (SubIdx != PPC::sub_eq)
1382 MachineBasicBlock::iterator I = CmpInstr;
1384 // Scan forward to find the first use of the compare.
1385 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1387 bool FoundUse = false;
1388 for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1389 JE = MRI->use_instr_end(); J != JE; ++J)
1399 // There are two possible candidates which can be changed to set CR[01].
1400 // One is MI, the other is a SUB instruction.
1401 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1402 MachineInstr *Sub = NULL;
1404 // MI is not a candidate for CMPrr.
1406 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1407 // same BB as the comparison. This is to allow the check below to avoid calls
1408 // (and other explicit clobbers); instead we should really check for these
1409 // more explicitly (in at least a few predecessors).
1410 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1411 // PPC does not have a record-form SUBri.
1416 const TargetRegisterInfo *TRI = &getRegisterInfo();
1419 // Get ready to iterate backward from CmpInstr.
1420 MachineBasicBlock::iterator E = MI,
1421 B = CmpInstr->getParent()->begin();
1423 for (; I != E && !noSub; --I) {
1424 const MachineInstr &Instr = *I;
1425 unsigned IOpC = Instr.getOpcode();
1427 if (&*I != CmpInstr && (
1428 Instr.modifiesRegister(PPC::CR0, TRI) ||
1429 Instr.readsRegister(PPC::CR0, TRI)))
1430 // This instruction modifies or uses the record condition register after
1431 // the one we want to change. While we could do this transformation, it
1432 // would likely not be profitable. This transformation removes one
1433 // instruction, and so even forcing RA to generate one move probably
1434 // makes it unprofitable.
1437 // Check whether CmpInstr can be made redundant by the current instruction.
1438 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1439 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1440 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1441 ((Instr.getOperand(1).getReg() == SrcReg &&
1442 Instr.getOperand(2).getReg() == SrcReg2) ||
1443 (Instr.getOperand(1).getReg() == SrcReg2 &&
1444 Instr.getOperand(2).getReg() == SrcReg))) {
1450 // The 'and' is below the comparison instruction.
1454 // Return false if no candidates exist.
1458 // The single candidate is called MI.
1462 MIOpC = MI->getOpcode();
1463 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1466 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1467 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1471 // FIXME: On the non-embedded POWER architectures, only some of the record
1472 // forms are fast, and we should use only the fast ones.
1474 // The defining instruction has a record form (or is already a record
1475 // form). It is possible, however, that we'll need to reverse the condition
1476 // code of the users.
1480 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1481 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1483 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1484 // needs to be updated to be based on SUB. Push the condition code
1485 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1486 // condition code of these operands will be modified.
1487 bool ShouldSwap = false;
1489 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1490 Sub->getOperand(2).getReg() == SrcReg;
1492 // The operands to subf are the opposite of sub, so only in the fixed-point
1493 // case, invert the order.
1494 ShouldSwap = !ShouldSwap;
1498 for (MachineRegisterInfo::use_instr_iterator
1499 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1501 MachineInstr *UseMI = &*I;
1502 if (UseMI->getOpcode() == PPC::BCC) {
1503 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1504 assert((!equalityOnly ||
1505 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1506 "Invalid predicate for equality-only optimization");
1507 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1508 PPC::getSwappedPredicate(Pred)));
1509 } else if (UseMI->getOpcode() == PPC::ISEL ||
1510 UseMI->getOpcode() == PPC::ISEL8) {
1511 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1512 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1513 "Invalid CR bit for equality-only optimization");
1515 if (NewSubReg == PPC::sub_lt)
1516 NewSubReg = PPC::sub_gt;
1517 else if (NewSubReg == PPC::sub_gt)
1518 NewSubReg = PPC::sub_lt;
1520 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1522 } else // We need to abort on a user we don't understand.
1526 // Create a new virtual register to hold the value of the CR set by the
1527 // record-form instruction. If the instruction was not previously in
1528 // record form, then set the kill flag on the CR.
1529 CmpInstr->eraseFromParent();
1531 MachineBasicBlock::iterator MII = MI;
1532 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1533 get(TargetOpcode::COPY), CRReg)
1534 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1536 if (MIOpC != NewOpC) {
1537 // We need to be careful here: we're replacing one instruction with
1538 // another, and we need to make sure that we get all of the right
1539 // implicit uses and defs. On the other hand, the caller may be holding
1540 // an iterator to this instruction, and so we can't delete it (this is
1541 // specifically the case if this is the instruction directly after the
1544 const MCInstrDesc &NewDesc = get(NewOpC);
1545 MI->setDesc(NewDesc);
1547 if (NewDesc.ImplicitDefs)
1548 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1549 *ImpDefs; ++ImpDefs)
1550 if (!MI->definesRegister(*ImpDefs))
1551 MI->addOperand(*MI->getParent()->getParent(),
1552 MachineOperand::CreateReg(*ImpDefs, true, true));
1553 if (NewDesc.ImplicitUses)
1554 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1555 *ImpUses; ++ImpUses)
1556 if (!MI->readsRegister(*ImpUses))
1557 MI->addOperand(*MI->getParent()->getParent(),
1558 MachineOperand::CreateReg(*ImpUses, false, true));
1561 // Modify the condition code of operands in OperandsToUpdate.
1562 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1563 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1564 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1565 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1567 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1568 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1573 /// GetInstSize - Return the number of bytes of code the specified
1574 /// instruction may be. This returns the maximum number of bytes.
1576 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1577 unsigned Opcode = MI->getOpcode();
1579 if (Opcode == PPC::INLINEASM) {
1580 const MachineFunction *MF = MI->getParent()->getParent();
1581 const char *AsmStr = MI->getOperand(0).getSymbolName();
1582 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1584 const MCInstrDesc &Desc = get(Opcode);
1585 return Desc.getSize();
1590 #define DEBUG_TYPE "ppc-vsx-fma-mutate"
1593 // PPCVSXFMAMutate pass - For copies between VSX registers and non-VSX registers
1594 // (Altivec and scalar floating-point registers), we need to transform the
1595 // copies into subregister copies with other restrictions.
1596 struct PPCVSXFMAMutate : public MachineFunctionPass {
1598 PPCVSXFMAMutate() : MachineFunctionPass(ID) {
1599 initializePPCVSXFMAMutatePass(*PassRegistry::getPassRegistry());
1604 const PPCTargetMachine *TM;
1605 const PPCInstrInfo *TII;
1608 bool processBlock(MachineBasicBlock &MBB) {
1609 bool Changed = false;
1611 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1612 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1614 MachineInstr *MI = I;
1616 // The default (A-type) VSX FMA form kills the addend (it is taken from
1617 // the target register, which is then updated to reflect the result of
1618 // the FMA). If the instruction, however, kills one of the registers
1619 // used for the product, then we can use the M-form instruction (which
1620 // will take that value from the to-be-defined register).
1622 int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
1626 // This pass is run after register coalescing, and so we're looking for
1627 // a situation like this:
1629 // %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1630 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1631 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1633 // %vreg9<def,tied1> = XSMADDADP %vreg9<tied0>, %vreg17, %vreg19,
1634 // %RM<imp-use>; VSLRC:%vreg9,%vreg17,%vreg19
1636 // Where we can eliminate the copy by changing from the A-type to the
1637 // M-type instruction. Specifically, for this example, this means:
1638 // %vreg5<def,tied1> = XSMADDADP %vreg5<tied0>, %vreg17, %vreg16,
1639 // %RM<imp-use>; VSLRC:%vreg5,%vreg17,%vreg16
1641 // %vreg16<def,tied1> = XSMADDMDP %vreg16<tied0>, %vreg18, %vreg9,
1642 // %RM<imp-use>; VSLRC:%vreg16,%vreg18,%vreg9
1643 // and we remove: %vreg5<def> = COPY %vreg9; VSLRC:%vreg5,%vreg9
1645 SlotIndex FMAIdx = LIS->getInstructionIndex(MI);
1647 VNInfo *AddendValNo =
1648 LIS->getInterval(MI->getOperand(1).getReg()).Query(FMAIdx).valueIn();
1649 MachineInstr *AddendMI = LIS->getInstructionFromIndex(AddendValNo->def);
1651 // The addend and this instruction must be in the same block.
1653 if (!AddendMI || AddendMI->getParent() != MI->getParent())
1656 // The addend must be a full copy within the same register class.
1658 if (!AddendMI->isFullCopy())
1661 unsigned AddendSrcReg = AddendMI->getOperand(1).getReg();
1662 if (TargetRegisterInfo::isVirtualRegister(AddendSrcReg)) {
1663 if (MRI.getRegClass(AddendMI->getOperand(0).getReg()) !=
1664 MRI.getRegClass(AddendSrcReg))
1667 // If AddendSrcReg is a physical register, make sure the destination
1668 // register class contains it.
1669 if (!MRI.getRegClass(AddendMI->getOperand(0).getReg())
1670 ->contains(AddendSrcReg))
1674 // In theory, there could be other uses of the addend copy before this
1675 // fma. We could deal with this, but that would require additional
1676 // logic below and I suspect it will not occur in any relevant
1678 bool OtherUsers = false;
1679 for (auto J = std::prev(I), JE = MachineBasicBlock::iterator(AddendMI);
1681 if (J->readsVirtualRegister(AddendMI->getOperand(0).getReg())) {
1689 // Find one of the product operands that is killed by this instruction.
1691 unsigned KilledProdOp = 0, OtherProdOp = 0;
1692 if (LIS->getInterval(MI->getOperand(2).getReg())
1693 .Query(FMAIdx).isKill()) {
1696 } else if (LIS->getInterval(MI->getOperand(3).getReg())
1697 .Query(FMAIdx).isKill()) {
1702 // If there are no killed product operands, then this transformation is
1703 // likely not profitable.
1707 // In order to replace the addend here with the source of the copy,
1708 // it must still be live here.
1709 if (!LIS->getInterval(AddendMI->getOperand(1).getReg()).liveAt(FMAIdx))
1712 // Transform: (O2 * O3) + O1 -> (O2 * O1) + O3.
1714 unsigned AddReg = AddendMI->getOperand(1).getReg();
1715 unsigned KilledProdReg = MI->getOperand(KilledProdOp).getReg();
1716 unsigned OtherProdReg = MI->getOperand(OtherProdOp).getReg();
1718 unsigned AddSubReg = AddendMI->getOperand(1).getSubReg();
1719 unsigned KilledProdSubReg = MI->getOperand(KilledProdOp).getSubReg();
1720 unsigned OtherProdSubReg = MI->getOperand(OtherProdOp).getSubReg();
1722 bool AddRegKill = AddendMI->getOperand(1).isKill();
1723 bool KilledProdRegKill = MI->getOperand(KilledProdOp).isKill();
1724 bool OtherProdRegKill = MI->getOperand(OtherProdOp).isKill();
1726 bool AddRegUndef = AddendMI->getOperand(1).isUndef();
1727 bool KilledProdRegUndef = MI->getOperand(KilledProdOp).isUndef();
1728 bool OtherProdRegUndef = MI->getOperand(OtherProdOp).isUndef();
1730 unsigned OldFMAReg = MI->getOperand(0).getReg();
1732 assert(OldFMAReg == AddendMI->getOperand(0).getReg() &&
1733 "Addend copy not tied to old FMA output!");
1735 DEBUG(dbgs() << "VSX FMA Mutation:\n " << *MI;);
1737 MI->getOperand(0).setReg(KilledProdReg);
1738 MI->getOperand(1).setReg(KilledProdReg);
1739 MI->getOperand(3).setReg(AddReg);
1740 MI->getOperand(2).setReg(OtherProdReg);
1742 MI->getOperand(0).setSubReg(KilledProdSubReg);
1743 MI->getOperand(1).setSubReg(KilledProdSubReg);
1744 MI->getOperand(3).setSubReg(AddSubReg);
1745 MI->getOperand(2).setSubReg(OtherProdSubReg);
1747 MI->getOperand(1).setIsKill(KilledProdRegKill);
1748 MI->getOperand(3).setIsKill(AddRegKill);
1749 MI->getOperand(2).setIsKill(OtherProdRegKill);
1751 MI->getOperand(1).setIsUndef(KilledProdRegUndef);
1752 MI->getOperand(3).setIsUndef(AddRegUndef);
1753 MI->getOperand(2).setIsUndef(OtherProdRegUndef);
1755 MI->setDesc(TII->get(AltOpc));
1757 DEBUG(dbgs() << " -> " << *MI);
1759 // The killed product operand was killed here, so we can reuse it now
1760 // for the result of the fma.
1762 LiveInterval &FMAInt = LIS->getInterval(OldFMAReg);
1763 VNInfo *FMAValNo = FMAInt.getVNInfoAt(FMAIdx.getRegSlot());
1764 for (auto UI = MRI.reg_nodbg_begin(OldFMAReg), UE = MRI.reg_nodbg_end();
1766 MachineOperand &UseMO = *UI;
1767 MachineInstr *UseMI = UseMO.getParent();
1770 // Don't replace the result register of the copy we're about to erase.
1771 if (UseMI == AddendMI)
1774 UseMO.setReg(KilledProdReg);
1775 UseMO.setSubReg(KilledProdSubReg);
1778 // Extend the live intervals of the killed product operand to hold the
1781 LiveInterval &NewFMAInt = LIS->getInterval(KilledProdReg);
1782 for (LiveInterval::iterator AI = FMAInt.begin(), AE = FMAInt.end();
1784 // Don't add the segment that corresponds to the original copy.
1785 if (AI->valno == AddendValNo)
1788 VNInfo *NewFMAValNo =
1789 NewFMAInt.getNextValue(AI->start,
1790 LIS->getVNInfoAllocator());
1792 NewFMAInt.addSegment(LiveInterval::Segment(AI->start, AI->end,
1795 DEBUG(dbgs() << " extended: " << NewFMAInt << '\n');
1797 FMAInt.removeValNo(FMAValNo);
1798 DEBUG(dbgs() << " trimmed: " << FMAInt << '\n');
1800 // Remove the (now unused) copy.
1802 DEBUG(dbgs() << " removing: " << *AddendMI << '\n');
1803 LIS->RemoveMachineInstrFromMaps(AddendMI);
1804 AddendMI->eraseFromParent();
1813 virtual bool runOnMachineFunction(MachineFunction &MF) {
1814 LIS = &getAnalysis<LiveIntervals>();
1816 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1817 TII = TM->getInstrInfo();
1819 bool Changed = false;
1821 if (DisableVSXFMAMutate)
1824 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1825 MachineBasicBlock &B = *I++;
1826 if (processBlock(B))
1833 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1834 AU.addRequired<LiveIntervals>();
1835 AU.addPreserved<LiveIntervals>();
1836 AU.addRequired<SlotIndexes>();
1837 AU.addPreserved<SlotIndexes>();
1838 MachineFunctionPass::getAnalysisUsage(AU);
1843 INITIALIZE_PASS_BEGIN(PPCVSXFMAMutate, DEBUG_TYPE,
1844 "PowerPC VSX FMA Mutation", false, false)
1845 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
1846 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
1847 INITIALIZE_PASS_END(PPCVSXFMAMutate, DEBUG_TYPE,
1848 "PowerPC VSX FMA Mutation", false, false)
1850 char &llvm::PPCVSXFMAMutateID = PPCVSXFMAMutate::ID;
1852 char PPCVSXFMAMutate::ID = 0;
1854 llvm::createPPCVSXFMAMutatePass() { return new PPCVSXFMAMutate(); }
1857 #define DEBUG_TYPE "ppc-vsx-copy"
1860 void initializePPCVSXCopyPass(PassRegistry&);
1864 // PPCVSXCopy pass - For copies between VSX registers and non-VSX registers
1865 // (Altivec and scalar floating-point registers), we need to transform the
1866 // copies into subregister copies with other restrictions.
1867 struct PPCVSXCopy : public MachineFunctionPass {
1869 PPCVSXCopy() : MachineFunctionPass(ID) {
1870 initializePPCVSXCopyPass(*PassRegistry::getPassRegistry());
1873 const PPCTargetMachine *TM;
1874 const PPCInstrInfo *TII;
1876 bool IsRegInClass(unsigned Reg, const TargetRegisterClass *RC,
1877 MachineRegisterInfo &MRI) {
1878 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1879 return RC->hasSubClassEq(MRI.getRegClass(Reg));
1880 } else if (RC->contains(Reg)) {
1887 bool IsVSReg(unsigned Reg, MachineRegisterInfo &MRI) {
1888 return IsRegInClass(Reg, &PPC::VSRCRegClass, MRI);
1891 bool IsVRReg(unsigned Reg, MachineRegisterInfo &MRI) {
1892 return IsRegInClass(Reg, &PPC::VRRCRegClass, MRI);
1895 bool IsF8Reg(unsigned Reg, MachineRegisterInfo &MRI) {
1896 return IsRegInClass(Reg, &PPC::F8RCRegClass, MRI);
1900 bool processBlock(MachineBasicBlock &MBB) {
1901 bool Changed = false;
1903 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
1904 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1906 MachineInstr *MI = I;
1907 if (!MI->isFullCopy())
1910 MachineOperand &DstMO = MI->getOperand(0);
1911 MachineOperand &SrcMO = MI->getOperand(1);
1913 if ( IsVSReg(DstMO.getReg(), MRI) &&
1914 !IsVSReg(SrcMO.getReg(), MRI)) {
1915 // This is a copy *to* a VSX register from a non-VSX register.
1918 const TargetRegisterClass *SrcRC =
1919 IsVRReg(SrcMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1920 &PPC::VSLRCRegClass;
1921 assert((IsF8Reg(SrcMO.getReg(), MRI) ||
1922 IsVRReg(SrcMO.getReg(), MRI)) &&
1923 "Unknown source for a VSX copy");
1925 unsigned NewVReg = MRI.createVirtualRegister(SrcRC);
1926 BuildMI(MBB, MI, MI->getDebugLoc(),
1927 TII->get(TargetOpcode::SUBREG_TO_REG), NewVReg)
1928 .addImm(1) // add 1, not 0, because there is no implicit clearing
1929 // of the high bits.
1931 .addImm(IsVRReg(SrcMO.getReg(), MRI) ? PPC::sub_128 :
1934 // The source of the original copy is now the new virtual register.
1935 SrcMO.setReg(NewVReg);
1936 } else if (!IsVSReg(DstMO.getReg(), MRI) &&
1937 IsVSReg(SrcMO.getReg(), MRI)) {
1938 // This is a copy *from* a VSX register to a non-VSX register.
1941 const TargetRegisterClass *DstRC =
1942 IsVRReg(DstMO.getReg(), MRI) ? &PPC::VSHRCRegClass :
1943 &PPC::VSLRCRegClass;
1944 assert((IsF8Reg(DstMO.getReg(), MRI) ||
1945 IsVRReg(DstMO.getReg(), MRI)) &&
1946 "Unknown destination for a VSX copy");
1948 // Copy the VSX value into a new VSX register of the correct subclass.
1949 unsigned NewVReg = MRI.createVirtualRegister(DstRC);
1950 BuildMI(MBB, MI, MI->getDebugLoc(),
1951 TII->get(TargetOpcode::COPY), NewVReg)
1954 // Transform the original copy into a subregister extraction copy.
1955 SrcMO.setReg(NewVReg);
1956 SrcMO.setSubReg(IsVRReg(DstMO.getReg(), MRI) ? PPC::sub_128 :
1965 virtual bool runOnMachineFunction(MachineFunction &MF) {
1966 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1967 TII = TM->getInstrInfo();
1969 bool Changed = false;
1971 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1972 MachineBasicBlock &B = *I++;
1973 if (processBlock(B))
1980 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1981 MachineFunctionPass::getAnalysisUsage(AU);
1986 INITIALIZE_PASS(PPCVSXCopy, DEBUG_TYPE,
1987 "PowerPC VSX Copy Legalization", false, false)
1989 char PPCVSXCopy::ID = 0;
1991 llvm::createPPCVSXCopyPass() { return new PPCVSXCopy(); }
1994 #define DEBUG_TYPE "ppc-vsx-copy-cleanup"
1997 void initializePPCVSXCopyCleanupPass(PassRegistry&);
2001 // PPCVSXCopyCleanup pass - We sometimes end up generating self copies of VSX
2002 // registers (mostly because the ABI code still places all values into the
2003 // "traditional" floating-point and vector registers). Remove them here.
2004 struct PPCVSXCopyCleanup : public MachineFunctionPass {
2006 PPCVSXCopyCleanup() : MachineFunctionPass(ID) {
2007 initializePPCVSXCopyCleanupPass(*PassRegistry::getPassRegistry());
2010 const PPCTargetMachine *TM;
2011 const PPCInstrInfo *TII;
2014 bool processBlock(MachineBasicBlock &MBB) {
2015 bool Changed = false;
2017 SmallVector<MachineInstr *, 4> ToDelete;
2018 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
2020 MachineInstr *MI = I;
2021 if (MI->getOpcode() == PPC::XXLOR &&
2022 MI->getOperand(0).getReg() == MI->getOperand(1).getReg() &&
2023 MI->getOperand(0).getReg() == MI->getOperand(2).getReg())
2024 ToDelete.push_back(MI);
2027 if (!ToDelete.empty())
2030 for (unsigned i = 0, ie = ToDelete.size(); i != ie; ++i) {
2031 DEBUG(dbgs() << "Removing VSX self-copy: " << *ToDelete[i]);
2032 ToDelete[i]->eraseFromParent();
2039 virtual bool runOnMachineFunction(MachineFunction &MF) {
2040 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2041 TII = TM->getInstrInfo();
2043 bool Changed = false;
2045 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2046 MachineBasicBlock &B = *I++;
2047 if (processBlock(B))
2054 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2055 MachineFunctionPass::getAnalysisUsage(AU);
2060 INITIALIZE_PASS(PPCVSXCopyCleanup, DEBUG_TYPE,
2061 "PowerPC VSX Copy Cleanup", false, false)
2063 char PPCVSXCopyCleanup::ID = 0;
2065 llvm::createPPCVSXCopyCleanupPass() { return new PPCVSXCopyCleanup(); }
2068 #define DEBUG_TYPE "ppc-early-ret"
2069 STATISTIC(NumBCLR, "Number of early conditional returns");
2070 STATISTIC(NumBLR, "Number of early returns");
2073 void initializePPCEarlyReturnPass(PassRegistry&);
2077 // PPCEarlyReturn pass - For simple functions without epilogue code, move
2078 // returns up, and create conditional returns, to avoid unnecessary
2079 // branch-to-blr sequences.
2080 struct PPCEarlyReturn : public MachineFunctionPass {
2082 PPCEarlyReturn() : MachineFunctionPass(ID) {
2083 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
2086 const PPCTargetMachine *TM;
2087 const PPCInstrInfo *TII;
2090 bool processBlock(MachineBasicBlock &ReturnMBB) {
2091 bool Changed = false;
2093 MachineBasicBlock::iterator I = ReturnMBB.begin();
2094 I = ReturnMBB.SkipPHIsAndLabels(I);
2096 // The block must be essentially empty except for the blr.
2097 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
2098 I != ReturnMBB.getLastNonDebugInstr())
2101 SmallVector<MachineBasicBlock*, 8> PredToRemove;
2102 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
2103 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
2104 bool OtherReference = false, BlockChanged = false;
2105 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
2106 if (J->getOpcode() == PPC::B) {
2107 if (J->getOperand(0).getMBB() == &ReturnMBB) {
2108 // This is an unconditional branch to the return. Replace the
2109 // branch with a blr.
2110 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
2111 MachineBasicBlock::iterator K = J--;
2112 K->eraseFromParent();
2113 BlockChanged = true;
2117 } else if (J->getOpcode() == PPC::BCC) {
2118 if (J->getOperand(2).getMBB() == &ReturnMBB) {
2119 // This is a conditional branch to the return. Replace the branch
2121 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
2122 .addImm(J->getOperand(0).getImm())
2123 .addReg(J->getOperand(1).getReg());
2124 MachineBasicBlock::iterator K = J--;
2125 K->eraseFromParent();
2126 BlockChanged = true;
2130 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
2131 if (J->getOperand(1).getMBB() == &ReturnMBB) {
2132 // This is a conditional branch to the return. Replace the branch
2134 BuildMI(**PI, J, J->getDebugLoc(),
2135 TII->get(J->getOpcode() == PPC::BC ?
2136 PPC::BCLR : PPC::BCLRn))
2137 .addReg(J->getOperand(0).getReg());
2138 MachineBasicBlock::iterator K = J--;
2139 K->eraseFromParent();
2140 BlockChanged = true;
2144 } else if (J->isBranch()) {
2145 if (J->isIndirectBranch()) {
2146 if (ReturnMBB.hasAddressTaken())
2147 OtherReference = true;
2149 for (unsigned i = 0; i < J->getNumOperands(); ++i)
2150 if (J->getOperand(i).isMBB() &&
2151 J->getOperand(i).getMBB() == &ReturnMBB)
2152 OtherReference = true;
2153 } else if (!J->isTerminator() && !J->isDebugValue())
2156 if (J == (*PI)->begin())
2162 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
2163 OtherReference = true;
2165 // Predecessors are stored in a vector and can't be removed here.
2166 if (!OtherReference && BlockChanged) {
2167 PredToRemove.push_back(*PI);
2174 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
2175 PredToRemove[i]->removeSuccessor(&ReturnMBB);
2177 if (Changed && !ReturnMBB.hasAddressTaken()) {
2178 // We now might be able to merge this blr-only block into its
2179 // by-layout predecessor.
2180 if (ReturnMBB.pred_size() == 1 &&
2181 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
2182 // Move the blr into the preceding block.
2183 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
2184 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
2185 PrevMBB.removeSuccessor(&ReturnMBB);
2188 if (ReturnMBB.pred_empty())
2189 ReturnMBB.eraseFromParent();
2196 virtual bool runOnMachineFunction(MachineFunction &MF) {
2197 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
2198 TII = TM->getInstrInfo();
2200 bool Changed = false;
2202 // If the function does not have at least two blocks, then there is
2207 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
2208 MachineBasicBlock &B = *I++;
2209 if (processBlock(B))
2216 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
2217 MachineFunctionPass::getAnalysisUsage(AU);
2222 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
2223 "PowerPC Early-Return Creation", false, false)
2225 char PPCEarlyReturn::ID = 0;
2227 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }