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/Statistic.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/PseudoSourceValue.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/TargetRegistry.h"
33 #include "llvm/Support/raw_ostream.h"
35 #define GET_INSTRMAP_INFO
36 #define GET_INSTRINFO_CTOR_DTOR
37 #include "PPCGenInstrInfo.inc"
42 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
43 cl::desc("Disable analysis for CTR loops"));
45 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
46 cl::desc("Disable compare instruction optimization"), cl::Hidden);
48 // Pin the vtable to this file.
49 void PPCInstrInfo::anchor() {}
51 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
52 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
53 TM(tm), RI(*TM.getSubtargetImpl()) {}
55 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
56 /// this target when scheduling the DAG.
57 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
58 const TargetMachine *TM,
59 const ScheduleDAG *DAG) const {
60 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
61 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
62 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
63 const InstrItineraryData *II = TM->getInstrItineraryData();
64 return new ScoreboardHazardRecognizer(II, DAG);
67 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
70 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
71 /// to use for this target when scheduling the DAG.
72 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
73 const InstrItineraryData *II,
74 const ScheduleDAG *DAG) const {
75 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
77 if (Directive == PPC::DIR_PWR7)
78 return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
80 // Most subtargets use a PPC970 recognizer.
81 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
82 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
83 assert(TM.getInstrInfo() && "No InstrInfo?");
85 return new PPCHazardRecognizer970(TM);
88 return new ScoreboardHazardRecognizer(II, DAG);
92 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
93 const MachineInstr *DefMI, unsigned DefIdx,
94 const MachineInstr *UseMI,
95 unsigned UseIdx) const {
96 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
99 const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
100 unsigned Reg = DefMO.getReg();
102 const TargetRegisterInfo *TRI = &getRegisterInfo();
104 if (TRI->isVirtualRegister(Reg)) {
105 const MachineRegisterInfo *MRI =
106 &DefMI->getParent()->getParent()->getRegInfo();
107 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
108 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
110 IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
111 PPC::CRBITRCRegClass.contains(Reg);
114 if (UseMI->isBranch() && IsRegCR) {
116 Latency = getInstrLatency(ItinData, DefMI);
118 // On some cores, there is an additional delay between writing to a condition
119 // register, and using it from a branch.
120 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
141 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
142 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
143 unsigned &SrcReg, unsigned &DstReg,
144 unsigned &SubIdx) const {
145 switch (MI.getOpcode()) {
146 default: return false;
148 case PPC::EXTSW_32_64:
149 SrcReg = MI.getOperand(1).getReg();
150 DstReg = MI.getOperand(0).getReg();
151 SubIdx = PPC::sub_32;
156 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
157 int &FrameIndex) const {
158 // Note: This list must be kept consistent with LoadRegFromStackSlot.
159 switch (MI->getOpcode()) {
165 case PPC::RESTORE_CR:
167 case PPC::RESTORE_VRSAVE:
168 // Check for the operands added by addFrameReference (the immediate is the
169 // offset which defaults to 0).
170 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
171 MI->getOperand(2).isFI()) {
172 FrameIndex = MI->getOperand(2).getIndex();
173 return MI->getOperand(0).getReg();
180 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
181 int &FrameIndex) const {
182 // Note: This list must be kept consistent with StoreRegToStackSlot.
183 switch (MI->getOpcode()) {
191 case PPC::SPILL_VRSAVE:
192 // Check for the operands added by addFrameReference (the immediate is the
193 // offset which defaults to 0).
194 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
195 MI->getOperand(2).isFI()) {
196 FrameIndex = MI->getOperand(2).getIndex();
197 return MI->getOperand(0).getReg();
204 // commuteInstruction - We can commute rlwimi instructions, but only if the
205 // rotate amt is zero. We also have to munge the immediates a bit.
207 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
208 MachineFunction &MF = *MI->getParent()->getParent();
210 // Normal instructions can be commuted the obvious way.
211 if (MI->getOpcode() != PPC::RLWIMI &&
212 MI->getOpcode() != PPC::RLWIMIo)
213 return TargetInstrInfo::commuteInstruction(MI, NewMI);
215 // Cannot commute if it has a non-zero rotate count.
216 if (MI->getOperand(3).getImm() != 0)
219 // If we have a zero rotate count, we have:
221 // Op0 = (Op1 & ~M) | (Op2 & M)
223 // M = mask((ME+1)&31, (MB-1)&31)
224 // Op0 = (Op2 & ~M) | (Op1 & M)
227 unsigned Reg0 = MI->getOperand(0).getReg();
228 unsigned Reg1 = MI->getOperand(1).getReg();
229 unsigned Reg2 = MI->getOperand(2).getReg();
230 bool Reg1IsKill = MI->getOperand(1).isKill();
231 bool Reg2IsKill = MI->getOperand(2).isKill();
232 bool ChangeReg0 = false;
233 // If machine instrs are no longer in two-address forms, update
234 // destination register as well.
236 // Must be two address instruction!
237 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
238 "Expecting a two-address instruction!");
244 unsigned MB = MI->getOperand(4).getImm();
245 unsigned ME = MI->getOperand(5).getImm();
248 // Create a new instruction.
249 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
250 bool Reg0IsDead = MI->getOperand(0).isDead();
251 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
252 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
253 .addReg(Reg2, getKillRegState(Reg2IsKill))
254 .addReg(Reg1, getKillRegState(Reg1IsKill))
256 .addImm((MB-1) & 31);
260 MI->getOperand(0).setReg(Reg2);
261 MI->getOperand(2).setReg(Reg1);
262 MI->getOperand(1).setReg(Reg2);
263 MI->getOperand(2).setIsKill(Reg1IsKill);
264 MI->getOperand(1).setIsKill(Reg2IsKill);
266 // Swap the mask around.
267 MI->getOperand(4).setImm((ME+1) & 31);
268 MI->getOperand(5).setImm((MB-1) & 31);
272 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
273 MachineBasicBlock::iterator MI) const {
274 // This function is used for scheduling, and the nop wanted here is the type
275 // that terminates dispatch groups on the POWER cores.
276 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
279 default: Opcode = PPC::NOP; break;
280 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
281 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
285 BuildMI(MBB, MI, DL, get(Opcode));
289 // Note: If the condition register is set to CTR or CTR8 then this is a
290 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
291 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
292 MachineBasicBlock *&FBB,
293 SmallVectorImpl<MachineOperand> &Cond,
294 bool AllowModify) const {
295 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
297 // If the block has no terminators, it just falls into the block after it.
298 MachineBasicBlock::iterator I = MBB.end();
299 if (I == MBB.begin())
302 while (I->isDebugValue()) {
303 if (I == MBB.begin())
307 if (!isUnpredicatedTerminator(I))
310 // Get the last instruction in the block.
311 MachineInstr *LastInst = I;
313 // If there is only one terminator instruction, process it.
314 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
315 if (LastInst->getOpcode() == PPC::B) {
316 if (!LastInst->getOperand(0).isMBB())
318 TBB = LastInst->getOperand(0).getMBB();
320 } else if (LastInst->getOpcode() == PPC::BCC) {
321 if (!LastInst->getOperand(2).isMBB())
323 // Block ends with fall-through condbranch.
324 TBB = LastInst->getOperand(2).getMBB();
325 Cond.push_back(LastInst->getOperand(0));
326 Cond.push_back(LastInst->getOperand(1));
328 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
329 LastInst->getOpcode() == PPC::BDNZ) {
330 if (!LastInst->getOperand(0).isMBB())
332 if (DisableCTRLoopAnal)
334 TBB = LastInst->getOperand(0).getMBB();
335 Cond.push_back(MachineOperand::CreateImm(1));
336 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
339 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
340 LastInst->getOpcode() == PPC::BDZ) {
341 if (!LastInst->getOperand(0).isMBB())
343 if (DisableCTRLoopAnal)
345 TBB = LastInst->getOperand(0).getMBB();
346 Cond.push_back(MachineOperand::CreateImm(0));
347 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
352 // Otherwise, don't know what this is.
356 // Get the instruction before it if it's a terminator.
357 MachineInstr *SecondLastInst = I;
359 // If there are three terminators, we don't know what sort of block this is.
360 if (SecondLastInst && I != MBB.begin() &&
361 isUnpredicatedTerminator(--I))
364 // If the block ends with PPC::B and PPC:BCC, handle it.
365 if (SecondLastInst->getOpcode() == PPC::BCC &&
366 LastInst->getOpcode() == PPC::B) {
367 if (!SecondLastInst->getOperand(2).isMBB() ||
368 !LastInst->getOperand(0).isMBB())
370 TBB = SecondLastInst->getOperand(2).getMBB();
371 Cond.push_back(SecondLastInst->getOperand(0));
372 Cond.push_back(SecondLastInst->getOperand(1));
373 FBB = LastInst->getOperand(0).getMBB();
375 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
376 SecondLastInst->getOpcode() == PPC::BDNZ) &&
377 LastInst->getOpcode() == PPC::B) {
378 if (!SecondLastInst->getOperand(0).isMBB() ||
379 !LastInst->getOperand(0).isMBB())
381 if (DisableCTRLoopAnal)
383 TBB = SecondLastInst->getOperand(0).getMBB();
384 Cond.push_back(MachineOperand::CreateImm(1));
385 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
387 FBB = LastInst->getOperand(0).getMBB();
389 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
390 SecondLastInst->getOpcode() == PPC::BDZ) &&
391 LastInst->getOpcode() == PPC::B) {
392 if (!SecondLastInst->getOperand(0).isMBB() ||
393 !LastInst->getOperand(0).isMBB())
395 if (DisableCTRLoopAnal)
397 TBB = SecondLastInst->getOperand(0).getMBB();
398 Cond.push_back(MachineOperand::CreateImm(0));
399 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
401 FBB = LastInst->getOperand(0).getMBB();
405 // If the block ends with two PPC:Bs, handle it. The second one is not
406 // executed, so remove it.
407 if (SecondLastInst->getOpcode() == PPC::B &&
408 LastInst->getOpcode() == PPC::B) {
409 if (!SecondLastInst->getOperand(0).isMBB())
411 TBB = SecondLastInst->getOperand(0).getMBB();
414 I->eraseFromParent();
418 // Otherwise, can't handle this.
422 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
423 MachineBasicBlock::iterator I = MBB.end();
424 if (I == MBB.begin()) return 0;
426 while (I->isDebugValue()) {
427 if (I == MBB.begin())
431 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
432 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
433 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
436 // Remove the branch.
437 I->eraseFromParent();
441 if (I == MBB.begin()) return 1;
443 if (I->getOpcode() != PPC::BCC &&
444 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
445 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
448 // Remove the branch.
449 I->eraseFromParent();
454 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
455 MachineBasicBlock *FBB,
456 const SmallVectorImpl<MachineOperand> &Cond,
458 // Shouldn't be a fall through.
459 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
460 assert((Cond.size() == 2 || Cond.size() == 0) &&
461 "PPC branch conditions have two components!");
463 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
467 if (Cond.empty()) // Unconditional branch
468 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
469 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
470 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
471 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
472 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
473 else // Conditional branch
474 BuildMI(&MBB, DL, get(PPC::BCC))
475 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
479 // Two-way Conditional Branch.
480 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
481 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
482 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
483 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
485 BuildMI(&MBB, DL, get(PPC::BCC))
486 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
487 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
492 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
493 const SmallVectorImpl<MachineOperand> &Cond,
494 unsigned TrueReg, unsigned FalseReg,
495 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
496 if (!TM.getSubtargetImpl()->hasISEL())
499 if (Cond.size() != 2)
502 // If this is really a bdnz-like condition, then it cannot be turned into a
504 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
507 // Check register classes.
508 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
509 const TargetRegisterClass *RC =
510 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
514 // isel is for regular integer GPRs only.
515 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
516 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
517 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
518 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
521 // FIXME: These numbers are for the A2, how well they work for other cores is
522 // an open question. On the A2, the isel instruction has a 2-cycle latency
523 // but single-cycle throughput. These numbers are used in combination with
524 // the MispredictPenalty setting from the active SchedMachineModel.
532 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
533 MachineBasicBlock::iterator MI, DebugLoc dl,
535 const SmallVectorImpl<MachineOperand> &Cond,
536 unsigned TrueReg, unsigned FalseReg) const {
537 assert(Cond.size() == 2 &&
538 "PPC branch conditions have two components!");
540 assert(TM.getSubtargetImpl()->hasISEL() &&
541 "Cannot insert select on target without ISEL support");
543 // Get the register classes.
544 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
545 const TargetRegisterClass *RC =
546 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
547 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
549 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
550 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
552 PPC::GPRCRegClass.hasSubClassEq(RC) ||
553 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
554 "isel is for regular integer GPRs only");
556 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
557 unsigned SelectPred = Cond[0].getImm();
561 switch (SelectPred) {
562 default: llvm_unreachable("invalid predicate for isel");
563 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
564 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
565 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
566 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
567 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
568 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
569 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
570 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
573 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
574 SecondReg = SwapOps ? TrueReg : FalseReg;
576 // The first input register of isel cannot be r0. If it is a member
577 // of a register class that can be r0, then copy it first (the
578 // register allocator should eliminate the copy).
579 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
580 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
581 const TargetRegisterClass *FirstRC =
582 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
583 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
584 unsigned OldFirstReg = FirstReg;
585 FirstReg = MRI.createVirtualRegister(FirstRC);
586 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
587 .addReg(OldFirstReg);
590 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
591 .addReg(FirstReg).addReg(SecondReg)
592 .addReg(Cond[1].getReg(), 0, SubIdx);
595 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
596 MachineBasicBlock::iterator I, DebugLoc DL,
597 unsigned DestReg, unsigned SrcReg,
598 bool KillSrc) const {
600 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
602 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
604 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
606 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
608 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
610 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
613 llvm_unreachable("Impossible reg-to-reg copy");
615 const MCInstrDesc &MCID = get(Opc);
616 if (MCID.getNumOperands() == 3)
617 BuildMI(MBB, I, DL, MCID, DestReg)
618 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
620 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
623 // This function returns true if a CR spill is necessary and false otherwise.
625 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
626 unsigned SrcReg, bool isKill,
628 const TargetRegisterClass *RC,
629 SmallVectorImpl<MachineInstr*> &NewMIs,
630 bool &NonRI, bool &SpillsVRS) const{
631 // Note: If additional store instructions are added here,
632 // update isStoreToStackSlot.
635 if (PPC::GPRCRegClass.hasSubClassEq(RC)) {
636 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
638 getKillRegState(isKill)),
640 } else if (PPC::G8RCRegClass.hasSubClassEq(RC)) {
641 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
643 getKillRegState(isKill)),
645 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
646 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
648 getKillRegState(isKill)),
650 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
651 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
653 getKillRegState(isKill)),
655 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
656 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
658 getKillRegState(isKill)),
661 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
662 // FIXME: We use CRi here because there is no mtcrf on a bit. Since the
663 // backend currently only uses CR1EQ as an individual bit, this should
664 // not cause any bug. If we need other uses of CR bits, the following
665 // code may be invalid.
667 if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR0GT ||
668 SrcReg == PPC::CR0EQ || SrcReg == PPC::CR0UN)
670 else if (SrcReg == PPC::CR1LT || SrcReg == PPC::CR1GT ||
671 SrcReg == PPC::CR1EQ || SrcReg == PPC::CR1UN)
673 else if (SrcReg == PPC::CR2LT || SrcReg == PPC::CR2GT ||
674 SrcReg == PPC::CR2EQ || SrcReg == PPC::CR2UN)
676 else if (SrcReg == PPC::CR3LT || SrcReg == PPC::CR3GT ||
677 SrcReg == PPC::CR3EQ || SrcReg == PPC::CR3UN)
679 else if (SrcReg == PPC::CR4LT || SrcReg == PPC::CR4GT ||
680 SrcReg == PPC::CR4EQ || SrcReg == PPC::CR4UN)
682 else if (SrcReg == PPC::CR5LT || SrcReg == PPC::CR5GT ||
683 SrcReg == PPC::CR5EQ || SrcReg == PPC::CR5UN)
685 else if (SrcReg == PPC::CR6LT || SrcReg == PPC::CR6GT ||
686 SrcReg == PPC::CR6EQ || SrcReg == PPC::CR6UN)
688 else if (SrcReg == PPC::CR7LT || SrcReg == PPC::CR7GT ||
689 SrcReg == PPC::CR7EQ || SrcReg == PPC::CR7UN)
692 return StoreRegToStackSlot(MF, Reg, isKill, FrameIdx,
693 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
695 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
696 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
698 getKillRegState(isKill)),
701 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
702 assert(TM.getSubtargetImpl()->isDarwin() &&
703 "VRSAVE only needs spill/restore on Darwin");
704 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
706 getKillRegState(isKill)),
710 llvm_unreachable("Unknown regclass!");
717 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
718 MachineBasicBlock::iterator MI,
719 unsigned SrcReg, bool isKill, int FrameIdx,
720 const TargetRegisterClass *RC,
721 const TargetRegisterInfo *TRI) const {
722 MachineFunction &MF = *MBB.getParent();
723 SmallVector<MachineInstr*, 4> NewMIs;
725 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
726 FuncInfo->setHasSpills();
728 bool NonRI = false, SpillsVRS = false;
729 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
731 FuncInfo->setSpillsCR();
734 FuncInfo->setSpillsVRSAVE();
737 FuncInfo->setHasNonRISpills();
739 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
740 MBB.insert(MI, NewMIs[i]);
742 const MachineFrameInfo &MFI = *MF.getFrameInfo();
743 MachineMemOperand *MMO =
744 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
745 MachineMemOperand::MOStore,
746 MFI.getObjectSize(FrameIdx),
747 MFI.getObjectAlignment(FrameIdx));
748 NewMIs.back()->addMemOperand(MF, MMO);
752 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
753 unsigned DestReg, int FrameIdx,
754 const TargetRegisterClass *RC,
755 SmallVectorImpl<MachineInstr*> &NewMIs,
756 bool &NonRI, bool &SpillsVRS) const{
757 // Note: If additional load instructions are added here,
758 // update isLoadFromStackSlot.
760 if (PPC::GPRCRegClass.hasSubClassEq(RC)) {
761 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
762 DestReg), FrameIdx));
763 } else if (PPC::G8RCRegClass.hasSubClassEq(RC)) {
764 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
766 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
767 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
769 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
770 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
772 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
773 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
774 get(PPC::RESTORE_CR), DestReg),
777 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
780 if (DestReg == PPC::CR0LT || DestReg == PPC::CR0GT ||
781 DestReg == PPC::CR0EQ || DestReg == PPC::CR0UN)
783 else if (DestReg == PPC::CR1LT || DestReg == PPC::CR1GT ||
784 DestReg == PPC::CR1EQ || DestReg == PPC::CR1UN)
786 else if (DestReg == PPC::CR2LT || DestReg == PPC::CR2GT ||
787 DestReg == PPC::CR2EQ || DestReg == PPC::CR2UN)
789 else if (DestReg == PPC::CR3LT || DestReg == PPC::CR3GT ||
790 DestReg == PPC::CR3EQ || DestReg == PPC::CR3UN)
792 else if (DestReg == PPC::CR4LT || DestReg == PPC::CR4GT ||
793 DestReg == PPC::CR4EQ || DestReg == PPC::CR4UN)
795 else if (DestReg == PPC::CR5LT || DestReg == PPC::CR5GT ||
796 DestReg == PPC::CR5EQ || DestReg == PPC::CR5UN)
798 else if (DestReg == PPC::CR6LT || DestReg == PPC::CR6GT ||
799 DestReg == PPC::CR6EQ || DestReg == PPC::CR6UN)
801 else if (DestReg == PPC::CR7LT || DestReg == PPC::CR7GT ||
802 DestReg == PPC::CR7EQ || DestReg == PPC::CR7UN)
805 return LoadRegFromStackSlot(MF, DL, Reg, FrameIdx,
806 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
808 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
809 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
812 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
813 assert(TM.getSubtargetImpl()->isDarwin() &&
814 "VRSAVE only needs spill/restore on Darwin");
815 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
816 get(PPC::RESTORE_VRSAVE),
821 llvm_unreachable("Unknown regclass!");
828 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
829 MachineBasicBlock::iterator MI,
830 unsigned DestReg, int FrameIdx,
831 const TargetRegisterClass *RC,
832 const TargetRegisterInfo *TRI) const {
833 MachineFunction &MF = *MBB.getParent();
834 SmallVector<MachineInstr*, 4> NewMIs;
836 if (MI != MBB.end()) DL = MI->getDebugLoc();
838 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
839 FuncInfo->setHasSpills();
841 bool NonRI = false, SpillsVRS = false;
842 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
844 FuncInfo->setSpillsCR();
847 FuncInfo->setSpillsVRSAVE();
850 FuncInfo->setHasNonRISpills();
852 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
853 MBB.insert(MI, NewMIs[i]);
855 const MachineFrameInfo &MFI = *MF.getFrameInfo();
856 MachineMemOperand *MMO =
857 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
858 MachineMemOperand::MOLoad,
859 MFI.getObjectSize(FrameIdx),
860 MFI.getObjectAlignment(FrameIdx));
861 NewMIs.back()->addMemOperand(MF, MMO);
865 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
866 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
867 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
868 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
870 // Leave the CR# the same, but invert the condition.
871 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
875 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
876 unsigned Reg, MachineRegisterInfo *MRI) const {
877 // For some instructions, it is legal to fold ZERO into the RA register field.
878 // A zero immediate should always be loaded with a single li.
879 unsigned DefOpc = DefMI->getOpcode();
880 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
882 if (!DefMI->getOperand(1).isImm())
884 if (DefMI->getOperand(1).getImm() != 0)
887 // Note that we cannot here invert the arguments of an isel in order to fold
888 // a ZERO into what is presented as the second argument. All we have here
889 // is the condition bit, and that might come from a CR-logical bit operation.
891 const MCInstrDesc &UseMCID = UseMI->getDesc();
893 // Only fold into real machine instructions.
894 if (UseMCID.isPseudo())
898 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
899 if (UseMI->getOperand(UseIdx).isReg() &&
900 UseMI->getOperand(UseIdx).getReg() == Reg)
903 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
904 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
906 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
908 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
909 // register (which might also be specified as a pointer class kind).
910 if (UseInfo->isLookupPtrRegClass()) {
911 if (UseInfo->RegClass /* Kind */ != 1)
914 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
915 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
919 // Make sure this is not tied to an output register (or otherwise
920 // constrained). This is true for ST?UX registers, for example, which
921 // are tied to their output registers.
922 if (UseInfo->Constraints != 0)
926 if (UseInfo->isLookupPtrRegClass()) {
927 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
928 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
930 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
931 PPC::ZERO8 : PPC::ZERO;
934 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
935 UseMI->getOperand(UseIdx).setReg(ZeroReg);
938 DefMI->eraseFromParent();
943 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
944 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
946 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
951 // We should make sure that, if we're going to predicate both sides of a
952 // condition (a diamond), that both sides don't define the counter register. We
953 // can predicate counter-decrement-based branches, but while that predicates
954 // the branching, it does not predicate the counter decrement. If we tried to
955 // merge the triangle into one predicated block, we'd decrement the counter
957 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
958 unsigned NumT, unsigned ExtraT,
959 MachineBasicBlock &FMBB,
960 unsigned NumF, unsigned ExtraF,
961 const BranchProbability &Probability) const {
962 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
966 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
967 // The predicated branches are identified by their type, not really by the
968 // explicit presence of a predicate. Furthermore, some of them can be
969 // predicated more than once. Because if conversion won't try to predicate
970 // any instruction which already claims to be predicated (by returning true
971 // here), always return false. In doing so, we let isPredicable() be the
972 // final word on whether not the instruction can be (further) predicated.
977 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
978 if (!MI->isTerminator())
981 // Conditional branch is a special case.
982 if (MI->isBranch() && !MI->isBarrier())
985 return !isPredicated(MI);
988 bool PPCInstrInfo::PredicateInstruction(
990 const SmallVectorImpl<MachineOperand> &Pred) const {
991 unsigned OpC = MI->getOpcode();
992 if (OpC == PPC::BLR) {
993 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
994 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
995 MI->setDesc(get(Pred[0].getImm() ?
996 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
997 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
999 MI->setDesc(get(PPC::BCLR));
1000 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1001 .addImm(Pred[0].getImm())
1002 .addReg(Pred[1].getReg());
1006 } else if (OpC == PPC::B) {
1007 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1008 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1009 MI->setDesc(get(Pred[0].getImm() ?
1010 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1011 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1013 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1014 MI->RemoveOperand(0);
1016 MI->setDesc(get(PPC::BCC));
1017 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1018 .addImm(Pred[0].getImm())
1019 .addReg(Pred[1].getReg())
1024 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1025 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1026 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1027 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1029 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1030 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1031 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1032 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1033 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1034 .addImm(Pred[0].getImm())
1035 .addReg(Pred[1].getReg());
1042 bool PPCInstrInfo::SubsumesPredicate(
1043 const SmallVectorImpl<MachineOperand> &Pred1,
1044 const SmallVectorImpl<MachineOperand> &Pred2) const {
1045 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1046 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1048 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1050 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1053 // P1 can only subsume P2 if they test the same condition register.
1054 if (Pred1[1].getReg() != Pred2[1].getReg())
1057 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1058 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1063 // Does P1 subsume P2, e.g. GE subsumes GT.
1064 if (P1 == PPC::PRED_LE &&
1065 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1067 if (P1 == PPC::PRED_GE &&
1068 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1074 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1075 std::vector<MachineOperand> &Pred) const {
1076 // Note: At the present time, the contents of Pred from this function is
1077 // unused by IfConversion. This implementation follows ARM by pushing the
1078 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1079 // predicate, instructions defining CTR or CTR8 are also included as
1080 // predicate-defining instructions.
1082 const TargetRegisterClass *RCs[] =
1083 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1084 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1087 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1088 const MachineOperand &MO = MI->getOperand(i);
1089 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1090 const TargetRegisterClass *RC = RCs[c];
1092 if (MO.isDef() && RC->contains(MO.getReg())) {
1096 } else if (MO.isRegMask()) {
1097 for (TargetRegisterClass::iterator I = RC->begin(),
1098 IE = RC->end(); I != IE; ++I)
1099 if (MO.clobbersPhysReg(*I)) {
1110 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1111 unsigned OpC = MI->getOpcode();
1125 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1126 unsigned &SrcReg, unsigned &SrcReg2,
1127 int &Mask, int &Value) const {
1128 unsigned Opc = MI->getOpcode();
1131 default: return false;
1136 SrcReg = MI->getOperand(1).getReg();
1138 Value = MI->getOperand(2).getImm();
1147 SrcReg = MI->getOperand(1).getReg();
1148 SrcReg2 = MI->getOperand(2).getReg();
1153 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1154 unsigned SrcReg, unsigned SrcReg2,
1155 int Mask, int Value,
1156 const MachineRegisterInfo *MRI) const {
1160 int OpC = CmpInstr->getOpcode();
1161 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1163 // FP record forms set CR1 based on the execption status bits, not a
1164 // comparison with zero.
1165 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1168 // The record forms set the condition register based on a signed comparison
1169 // with zero (so says the ISA manual). This is not as straightforward as it
1170 // seems, however, because this is always a 64-bit comparison on PPC64, even
1171 // for instructions that are 32-bit in nature (like slw for example).
1172 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1173 // for equality checks (as those don't depend on the sign). On PPC64,
1174 // we are restricted to equality for unsigned 64-bit comparisons and for
1175 // signed 32-bit comparisons the applicability is more restricted.
1176 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1177 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1178 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1179 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1181 // Get the unique definition of SrcReg.
1182 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1183 if (!MI) return false;
1184 int MIOpC = MI->getOpcode();
1186 bool equalityOnly = false;
1189 if (is32BitSignedCompare) {
1190 // We can perform this optimization only if MI is sign-extending.
1191 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1192 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1193 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1194 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1195 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1199 } else if (is32BitUnsignedCompare) {
1200 // We can perform this optimization, equality only, if MI is
1202 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1203 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1204 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1206 equalityOnly = true;
1210 equalityOnly = is64BitUnsignedCompare;
1212 equalityOnly = is32BitUnsignedCompare;
1215 // We need to check the uses of the condition register in order to reject
1216 // non-equality comparisons.
1217 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1218 IE = MRI->use_end(); I != IE; ++I) {
1219 MachineInstr *UseMI = &*I;
1220 if (UseMI->getOpcode() == PPC::BCC) {
1221 unsigned Pred = UseMI->getOperand(0).getImm();
1222 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1224 } else if (UseMI->getOpcode() == PPC::ISEL ||
1225 UseMI->getOpcode() == PPC::ISEL8) {
1226 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1227 if (SubIdx != PPC::sub_eq)
1234 MachineBasicBlock::iterator I = CmpInstr;
1236 // Scan forward to find the first use of the compare.
1237 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1239 bool FoundUse = false;
1240 for (MachineRegisterInfo::use_iterator J = MRI->use_begin(CRReg),
1241 JE = MRI->use_end(); J != JE; ++J)
1251 // There are two possible candidates which can be changed to set CR[01].
1252 // One is MI, the other is a SUB instruction.
1253 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1254 MachineInstr *Sub = NULL;
1256 // MI is not a candidate for CMPrr.
1258 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1259 // same BB as the comparison. This is to allow the check below to avoid calls
1260 // (and other explicit clobbers); instead we should really check for these
1261 // more explicitly (in at least a few predecessors).
1262 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1263 // PPC does not have a record-form SUBri.
1268 const TargetRegisterInfo *TRI = &getRegisterInfo();
1271 // Get ready to iterate backward from CmpInstr.
1272 MachineBasicBlock::iterator E = MI,
1273 B = CmpInstr->getParent()->begin();
1275 for (; I != E && !noSub; --I) {
1276 const MachineInstr &Instr = *I;
1277 unsigned IOpC = Instr.getOpcode();
1279 if (&*I != CmpInstr && (
1280 Instr.modifiesRegister(PPC::CR0, TRI) ||
1281 Instr.readsRegister(PPC::CR0, TRI)))
1282 // This instruction modifies or uses the record condition register after
1283 // the one we want to change. While we could do this transformation, it
1284 // would likely not be profitable. This transformation removes one
1285 // instruction, and so even forcing RA to generate one move probably
1286 // makes it unprofitable.
1289 // Check whether CmpInstr can be made redundant by the current instruction.
1290 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1291 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1292 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1293 ((Instr.getOperand(1).getReg() == SrcReg &&
1294 Instr.getOperand(2).getReg() == SrcReg2) ||
1295 (Instr.getOperand(1).getReg() == SrcReg2 &&
1296 Instr.getOperand(2).getReg() == SrcReg))) {
1302 // The 'and' is below the comparison instruction.
1306 // Return false if no candidates exist.
1310 // The single candidate is called MI.
1314 MIOpC = MI->getOpcode();
1315 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1318 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1319 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1323 // FIXME: On the non-embedded POWER architectures, only some of the record
1324 // forms are fast, and we should use only the fast ones.
1326 // The defining instruction has a record form (or is already a record
1327 // form). It is possible, however, that we'll need to reverse the condition
1328 // code of the users.
1332 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1333 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1335 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1336 // needs to be updated to be based on SUB. Push the condition code
1337 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1338 // condition code of these operands will be modified.
1339 bool ShouldSwap = false;
1341 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1342 Sub->getOperand(2).getReg() == SrcReg;
1344 // The operands to subf are the opposite of sub, so only in the fixed-point
1345 // case, invert the order.
1346 ShouldSwap = !ShouldSwap;
1350 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1351 IE = MRI->use_end(); I != IE; ++I) {
1352 MachineInstr *UseMI = &*I;
1353 if (UseMI->getOpcode() == PPC::BCC) {
1354 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1355 assert((!equalityOnly ||
1356 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1357 "Invalid predicate for equality-only optimization");
1358 PredsToUpdate.push_back(std::make_pair(&((*I).getOperand(0)),
1359 PPC::getSwappedPredicate(Pred)));
1360 } else if (UseMI->getOpcode() == PPC::ISEL ||
1361 UseMI->getOpcode() == PPC::ISEL8) {
1362 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1363 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1364 "Invalid CR bit for equality-only optimization");
1366 if (NewSubReg == PPC::sub_lt)
1367 NewSubReg = PPC::sub_gt;
1368 else if (NewSubReg == PPC::sub_gt)
1369 NewSubReg = PPC::sub_lt;
1371 SubRegsToUpdate.push_back(std::make_pair(&((*I).getOperand(3)),
1373 } else // We need to abort on a user we don't understand.
1377 // Create a new virtual register to hold the value of the CR set by the
1378 // record-form instruction. If the instruction was not previously in
1379 // record form, then set the kill flag on the CR.
1380 CmpInstr->eraseFromParent();
1382 MachineBasicBlock::iterator MII = MI;
1383 BuildMI(*MI->getParent(), llvm::next(MII), MI->getDebugLoc(),
1384 get(TargetOpcode::COPY), CRReg)
1385 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1387 if (MIOpC != NewOpC) {
1388 // We need to be careful here: we're replacing one instruction with
1389 // another, and we need to make sure that we get all of the right
1390 // implicit uses and defs. On the other hand, the caller may be holding
1391 // an iterator to this instruction, and so we can't delete it (this is
1392 // specifically the case if this is the instruction directly after the
1395 const MCInstrDesc &NewDesc = get(NewOpC);
1396 MI->setDesc(NewDesc);
1398 if (NewDesc.ImplicitDefs)
1399 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1400 *ImpDefs; ++ImpDefs)
1401 if (!MI->definesRegister(*ImpDefs))
1402 MI->addOperand(*MI->getParent()->getParent(),
1403 MachineOperand::CreateReg(*ImpDefs, true, true));
1404 if (NewDesc.ImplicitUses)
1405 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1406 *ImpUses; ++ImpUses)
1407 if (!MI->readsRegister(*ImpUses))
1408 MI->addOperand(*MI->getParent()->getParent(),
1409 MachineOperand::CreateReg(*ImpUses, false, true));
1412 // Modify the condition code of operands in OperandsToUpdate.
1413 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1414 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1415 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1416 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1418 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1419 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1424 /// GetInstSize - Return the number of bytes of code the specified
1425 /// instruction may be. This returns the maximum number of bytes.
1427 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1428 switch (MI->getOpcode()) {
1429 case PPC::INLINEASM: { // Inline Asm: Variable size.
1430 const MachineFunction *MF = MI->getParent()->getParent();
1431 const char *AsmStr = MI->getOperand(0).getSymbolName();
1432 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1434 case PPC::PROLOG_LABEL:
1437 case PPC::DBG_VALUE:
1443 return 4; // PowerPC instructions are all 4 bytes
1448 #define DEBUG_TYPE "ppc-early-ret"
1449 STATISTIC(NumBCLR, "Number of early conditional returns");
1450 STATISTIC(NumBLR, "Number of early returns");
1453 void initializePPCEarlyReturnPass(PassRegistry&);
1457 // PPCEarlyReturn pass - For simple functions without epilogue code, move
1458 // returns up, and create conditional returns, to avoid unnecessary
1459 // branch-to-blr sequences.
1460 struct PPCEarlyReturn : public MachineFunctionPass {
1462 PPCEarlyReturn() : MachineFunctionPass(ID) {
1463 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1466 const PPCTargetMachine *TM;
1467 const PPCInstrInfo *TII;
1470 bool processBlock(MachineBasicBlock &ReturnMBB) {
1471 bool Changed = false;
1473 MachineBasicBlock::iterator I = ReturnMBB.begin();
1474 I = ReturnMBB.SkipPHIsAndLabels(I);
1476 // The block must be essentially empty except for the blr.
1477 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1478 I != ReturnMBB.getLastNonDebugInstr())
1481 SmallVector<MachineBasicBlock*, 8> PredToRemove;
1482 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1483 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1484 bool OtherReference = false, BlockChanged = false;
1485 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1486 if (J->getOpcode() == PPC::B) {
1487 if (J->getOperand(0).getMBB() == &ReturnMBB) {
1488 // This is an unconditional branch to the return. Replace the
1489 // branch with a blr.
1490 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1491 MachineBasicBlock::iterator K = J--;
1492 K->eraseFromParent();
1493 BlockChanged = true;
1497 } else if (J->getOpcode() == PPC::BCC) {
1498 if (J->getOperand(2).getMBB() == &ReturnMBB) {
1499 // This is a conditional branch to the return. Replace the branch
1501 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCLR))
1502 .addImm(J->getOperand(0).getImm())
1503 .addReg(J->getOperand(1).getReg());
1504 MachineBasicBlock::iterator K = J--;
1505 K->eraseFromParent();
1506 BlockChanged = true;
1510 } else if (J->isBranch()) {
1511 if (J->isIndirectBranch()) {
1512 if (ReturnMBB.hasAddressTaken())
1513 OtherReference = true;
1515 for (unsigned i = 0; i < J->getNumOperands(); ++i)
1516 if (J->getOperand(i).isMBB() &&
1517 J->getOperand(i).getMBB() == &ReturnMBB)
1518 OtherReference = true;
1519 } else if (!J->isTerminator() && !J->isDebugValue())
1522 if (J == (*PI)->begin())
1528 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1529 OtherReference = true;
1531 // Predecessors are stored in a vector and can't be removed here.
1532 if (!OtherReference && BlockChanged) {
1533 PredToRemove.push_back(*PI);
1540 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1541 PredToRemove[i]->removeSuccessor(&ReturnMBB);
1543 if (Changed && !ReturnMBB.hasAddressTaken()) {
1544 // We now might be able to merge this blr-only block into its
1545 // by-layout predecessor.
1546 if (ReturnMBB.pred_size() == 1 &&
1547 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1548 // Move the blr into the preceding block.
1549 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1550 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1551 PrevMBB.removeSuccessor(&ReturnMBB);
1554 if (ReturnMBB.pred_empty())
1555 ReturnMBB.eraseFromParent();
1562 virtual bool runOnMachineFunction(MachineFunction &MF) {
1563 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1564 TII = TM->getInstrInfo();
1566 bool Changed = false;
1568 // If the function does not have at least two blocks, then there is
1573 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1574 MachineBasicBlock &B = *I++;
1575 if (processBlock(B))
1582 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1583 MachineFunctionPass::getAnalysisUsage(AU);
1588 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1589 "PowerPC Early-Return Creation", false, false)
1591 char PPCEarlyReturn::ID = 0;
1593 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }