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
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 PPCInstrInfo::PPCInstrInfo(PPCTargetMachine &tm)
49 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
50 TM(tm), RI(*TM.getSubtargetImpl()) {}
52 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
53 /// this target when scheduling the DAG.
54 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetHazardRecognizer(
55 const TargetMachine *TM,
56 const ScheduleDAG *DAG) const {
57 unsigned Directive = TM->getSubtarget<PPCSubtarget>().getDarwinDirective();
58 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
59 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
60 const InstrItineraryData *II = TM->getInstrItineraryData();
61 return new PPCScoreboardHazardRecognizer(II, DAG);
64 return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
67 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
68 /// to use for this target when scheduling the DAG.
69 ScheduleHazardRecognizer *PPCInstrInfo::CreateTargetPostRAHazardRecognizer(
70 const InstrItineraryData *II,
71 const ScheduleDAG *DAG) const {
72 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
74 // Most subtargets use a PPC970 recognizer.
75 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
76 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
77 assert(TM.getInstrInfo() && "No InstrInfo?");
79 return new PPCHazardRecognizer970(TM);
82 return new PPCScoreboardHazardRecognizer(II, DAG);
85 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
86 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
87 unsigned &SrcReg, unsigned &DstReg,
88 unsigned &SubIdx) const {
89 switch (MI.getOpcode()) {
90 default: return false;
92 case PPC::EXTSW_32_64:
93 SrcReg = MI.getOperand(1).getReg();
94 DstReg = MI.getOperand(0).getReg();
100 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
101 int &FrameIndex) const {
102 // Note: This list must be kept consistent with LoadRegFromStackSlot.
103 switch (MI->getOpcode()) {
109 case PPC::RESTORE_CR:
111 case PPC::RESTORE_VRSAVE:
112 // Check for the operands added by addFrameReference (the immediate is the
113 // offset which defaults to 0).
114 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
115 MI->getOperand(2).isFI()) {
116 FrameIndex = MI->getOperand(2).getIndex();
117 return MI->getOperand(0).getReg();
124 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
125 int &FrameIndex) const {
126 // Note: This list must be kept consistent with StoreRegToStackSlot.
127 switch (MI->getOpcode()) {
135 case PPC::SPILL_VRSAVE:
136 // Check for the operands added by addFrameReference (the immediate is the
137 // offset which defaults to 0).
138 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
139 MI->getOperand(2).isFI()) {
140 FrameIndex = MI->getOperand(2).getIndex();
141 return MI->getOperand(0).getReg();
148 // commuteInstruction - We can commute rlwimi instructions, but only if the
149 // rotate amt is zero. We also have to munge the immediates a bit.
151 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
152 MachineFunction &MF = *MI->getParent()->getParent();
154 // Normal instructions can be commuted the obvious way.
155 if (MI->getOpcode() != PPC::RLWIMI &&
156 MI->getOpcode() != PPC::RLWIMIo)
157 return TargetInstrInfo::commuteInstruction(MI, NewMI);
159 // Cannot commute if it has a non-zero rotate count.
160 if (MI->getOperand(3).getImm() != 0)
163 // If we have a zero rotate count, we have:
165 // Op0 = (Op1 & ~M) | (Op2 & M)
167 // M = mask((ME+1)&31, (MB-1)&31)
168 // Op0 = (Op2 & ~M) | (Op1 & M)
171 unsigned Reg0 = MI->getOperand(0).getReg();
172 unsigned Reg1 = MI->getOperand(1).getReg();
173 unsigned Reg2 = MI->getOperand(2).getReg();
174 bool Reg1IsKill = MI->getOperand(1).isKill();
175 bool Reg2IsKill = MI->getOperand(2).isKill();
176 bool ChangeReg0 = false;
177 // If machine instrs are no longer in two-address forms, update
178 // destination register as well.
180 // Must be two address instruction!
181 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
182 "Expecting a two-address instruction!");
188 unsigned MB = MI->getOperand(4).getImm();
189 unsigned ME = MI->getOperand(5).getImm();
192 // Create a new instruction.
193 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
194 bool Reg0IsDead = MI->getOperand(0).isDead();
195 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
196 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
197 .addReg(Reg2, getKillRegState(Reg2IsKill))
198 .addReg(Reg1, getKillRegState(Reg1IsKill))
200 .addImm((MB-1) & 31);
204 MI->getOperand(0).setReg(Reg2);
205 MI->getOperand(2).setReg(Reg1);
206 MI->getOperand(1).setReg(Reg2);
207 MI->getOperand(2).setIsKill(Reg1IsKill);
208 MI->getOperand(1).setIsKill(Reg2IsKill);
210 // Swap the mask around.
211 MI->getOperand(4).setImm((ME+1) & 31);
212 MI->getOperand(5).setImm((MB-1) & 31);
216 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
217 MachineBasicBlock::iterator MI) const {
219 BuildMI(MBB, MI, DL, get(PPC::NOP));
224 // Note: If the condition register is set to CTR or CTR8 then this is a
225 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
226 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
227 MachineBasicBlock *&FBB,
228 SmallVectorImpl<MachineOperand> &Cond,
229 bool AllowModify) const {
230 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
232 // If the block has no terminators, it just falls into the block after it.
233 MachineBasicBlock::iterator I = MBB.end();
234 if (I == MBB.begin())
237 while (I->isDebugValue()) {
238 if (I == MBB.begin())
242 if (!isUnpredicatedTerminator(I))
245 // Get the last instruction in the block.
246 MachineInstr *LastInst = I;
248 // If there is only one terminator instruction, process it.
249 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
250 if (LastInst->getOpcode() == PPC::B) {
251 if (!LastInst->getOperand(0).isMBB())
253 TBB = LastInst->getOperand(0).getMBB();
255 } else if (LastInst->getOpcode() == PPC::BCC) {
256 if (!LastInst->getOperand(2).isMBB())
258 // Block ends with fall-through condbranch.
259 TBB = LastInst->getOperand(2).getMBB();
260 Cond.push_back(LastInst->getOperand(0));
261 Cond.push_back(LastInst->getOperand(1));
263 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
264 LastInst->getOpcode() == PPC::BDNZ) {
265 if (!LastInst->getOperand(0).isMBB())
267 if (DisableCTRLoopAnal)
269 TBB = LastInst->getOperand(0).getMBB();
270 Cond.push_back(MachineOperand::CreateImm(1));
271 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
274 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
275 LastInst->getOpcode() == PPC::BDZ) {
276 if (!LastInst->getOperand(0).isMBB())
278 if (DisableCTRLoopAnal)
280 TBB = LastInst->getOperand(0).getMBB();
281 Cond.push_back(MachineOperand::CreateImm(0));
282 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
287 // Otherwise, don't know what this is.
291 // Get the instruction before it if it's a terminator.
292 MachineInstr *SecondLastInst = I;
294 // If there are three terminators, we don't know what sort of block this is.
295 if (SecondLastInst && I != MBB.begin() &&
296 isUnpredicatedTerminator(--I))
299 // If the block ends with PPC::B and PPC:BCC, handle it.
300 if (SecondLastInst->getOpcode() == PPC::BCC &&
301 LastInst->getOpcode() == PPC::B) {
302 if (!SecondLastInst->getOperand(2).isMBB() ||
303 !LastInst->getOperand(0).isMBB())
305 TBB = SecondLastInst->getOperand(2).getMBB();
306 Cond.push_back(SecondLastInst->getOperand(0));
307 Cond.push_back(SecondLastInst->getOperand(1));
308 FBB = LastInst->getOperand(0).getMBB();
310 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
311 SecondLastInst->getOpcode() == PPC::BDNZ) &&
312 LastInst->getOpcode() == PPC::B) {
313 if (!SecondLastInst->getOperand(0).isMBB() ||
314 !LastInst->getOperand(0).isMBB())
316 if (DisableCTRLoopAnal)
318 TBB = SecondLastInst->getOperand(0).getMBB();
319 Cond.push_back(MachineOperand::CreateImm(1));
320 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
322 FBB = LastInst->getOperand(0).getMBB();
324 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
325 SecondLastInst->getOpcode() == PPC::BDZ) &&
326 LastInst->getOpcode() == PPC::B) {
327 if (!SecondLastInst->getOperand(0).isMBB() ||
328 !LastInst->getOperand(0).isMBB())
330 if (DisableCTRLoopAnal)
332 TBB = SecondLastInst->getOperand(0).getMBB();
333 Cond.push_back(MachineOperand::CreateImm(0));
334 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
336 FBB = LastInst->getOperand(0).getMBB();
340 // If the block ends with two PPC:Bs, handle it. The second one is not
341 // executed, so remove it.
342 if (SecondLastInst->getOpcode() == PPC::B &&
343 LastInst->getOpcode() == PPC::B) {
344 if (!SecondLastInst->getOperand(0).isMBB())
346 TBB = SecondLastInst->getOperand(0).getMBB();
349 I->eraseFromParent();
353 // Otherwise, can't handle this.
357 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
358 MachineBasicBlock::iterator I = MBB.end();
359 if (I == MBB.begin()) return 0;
361 while (I->isDebugValue()) {
362 if (I == MBB.begin())
366 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
367 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
368 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
371 // Remove the branch.
372 I->eraseFromParent();
376 if (I == MBB.begin()) return 1;
378 if (I->getOpcode() != PPC::BCC &&
379 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
380 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
383 // Remove the branch.
384 I->eraseFromParent();
389 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
390 MachineBasicBlock *FBB,
391 const SmallVectorImpl<MachineOperand> &Cond,
393 // Shouldn't be a fall through.
394 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
395 assert((Cond.size() == 2 || Cond.size() == 0) &&
396 "PPC branch conditions have two components!");
398 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
402 if (Cond.empty()) // Unconditional branch
403 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
404 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
405 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
406 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
407 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
408 else // Conditional branch
409 BuildMI(&MBB, DL, get(PPC::BCC))
410 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
414 // Two-way Conditional Branch.
415 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
416 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
417 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
418 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
420 BuildMI(&MBB, DL, get(PPC::BCC))
421 .addImm(Cond[0].getImm()).addReg(Cond[1].getReg()).addMBB(TBB);
422 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
427 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
428 const SmallVectorImpl<MachineOperand> &Cond,
429 unsigned TrueReg, unsigned FalseReg,
430 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
431 if (!TM.getSubtargetImpl()->hasISEL())
434 if (Cond.size() != 2)
437 // If this is really a bdnz-like condition, then it cannot be turned into a
439 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
442 // Check register classes.
443 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
444 const TargetRegisterClass *RC =
445 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
449 // isel is for regular integer GPRs only.
450 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
451 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
452 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
453 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
456 // FIXME: These numbers are for the A2, how well they work for other cores is
457 // an open question. On the A2, the isel instruction has a 2-cycle latency
458 // but single-cycle throughput. These numbers are used in combination with
459 // the MispredictPenalty setting from the active SchedMachineModel.
467 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
468 MachineBasicBlock::iterator MI, DebugLoc dl,
470 const SmallVectorImpl<MachineOperand> &Cond,
471 unsigned TrueReg, unsigned FalseReg) const {
472 assert(Cond.size() == 2 &&
473 "PPC branch conditions have two components!");
475 assert(TM.getSubtargetImpl()->hasISEL() &&
476 "Cannot insert select on target without ISEL support");
478 // Get the register classes.
479 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
480 const TargetRegisterClass *RC =
481 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
482 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
484 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
485 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
487 PPC::GPRCRegClass.hasSubClassEq(RC) ||
488 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
489 "isel is for regular integer GPRs only");
491 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
492 unsigned SelectPred = Cond[0].getImm();
496 switch (SelectPred) {
497 default: llvm_unreachable("invalid predicate for isel");
498 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
499 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
500 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
501 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
502 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
503 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
504 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
505 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
508 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
509 SecondReg = SwapOps ? TrueReg : FalseReg;
511 // The first input register of isel cannot be r0. If it is a member
512 // of a register class that can be r0, then copy it first (the
513 // register allocator should eliminate the copy).
514 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
515 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
516 const TargetRegisterClass *FirstRC =
517 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
518 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
519 unsigned OldFirstReg = FirstReg;
520 FirstReg = MRI.createVirtualRegister(FirstRC);
521 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
522 .addReg(OldFirstReg);
525 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
526 .addReg(FirstReg).addReg(SecondReg)
527 .addReg(Cond[1].getReg(), 0, SubIdx);
530 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
531 MachineBasicBlock::iterator I, DebugLoc DL,
532 unsigned DestReg, unsigned SrcReg,
533 bool KillSrc) const {
535 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
537 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
539 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
541 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
543 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
545 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
548 llvm_unreachable("Impossible reg-to-reg copy");
550 const MCInstrDesc &MCID = get(Opc);
551 if (MCID.getNumOperands() == 3)
552 BuildMI(MBB, I, DL, MCID, DestReg)
553 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
555 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
558 // This function returns true if a CR spill is necessary and false otherwise.
560 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
561 unsigned SrcReg, bool isKill,
563 const TargetRegisterClass *RC,
564 SmallVectorImpl<MachineInstr*> &NewMIs,
565 bool &NonRI, bool &SpillsVRS) const{
566 // Note: If additional store instructions are added here,
567 // update isStoreToStackSlot.
570 if (PPC::GPRCRegClass.hasSubClassEq(RC)) {
571 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
573 getKillRegState(isKill)),
575 } else if (PPC::G8RCRegClass.hasSubClassEq(RC)) {
576 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
578 getKillRegState(isKill)),
580 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
581 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
583 getKillRegState(isKill)),
585 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
586 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
588 getKillRegState(isKill)),
590 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
591 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
593 getKillRegState(isKill)),
596 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
597 // FIXME: We use CRi here because there is no mtcrf on a bit. Since the
598 // backend currently only uses CR1EQ as an individual bit, this should
599 // not cause any bug. If we need other uses of CR bits, the following
600 // code may be invalid.
602 if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR0GT ||
603 SrcReg == PPC::CR0EQ || SrcReg == PPC::CR0UN)
605 else if (SrcReg == PPC::CR1LT || SrcReg == PPC::CR1GT ||
606 SrcReg == PPC::CR1EQ || SrcReg == PPC::CR1UN)
608 else if (SrcReg == PPC::CR2LT || SrcReg == PPC::CR2GT ||
609 SrcReg == PPC::CR2EQ || SrcReg == PPC::CR2UN)
611 else if (SrcReg == PPC::CR3LT || SrcReg == PPC::CR3GT ||
612 SrcReg == PPC::CR3EQ || SrcReg == PPC::CR3UN)
614 else if (SrcReg == PPC::CR4LT || SrcReg == PPC::CR4GT ||
615 SrcReg == PPC::CR4EQ || SrcReg == PPC::CR4UN)
617 else if (SrcReg == PPC::CR5LT || SrcReg == PPC::CR5GT ||
618 SrcReg == PPC::CR5EQ || SrcReg == PPC::CR5UN)
620 else if (SrcReg == PPC::CR6LT || SrcReg == PPC::CR6GT ||
621 SrcReg == PPC::CR6EQ || SrcReg == PPC::CR6UN)
623 else if (SrcReg == PPC::CR7LT || SrcReg == PPC::CR7GT ||
624 SrcReg == PPC::CR7EQ || SrcReg == PPC::CR7UN)
627 return StoreRegToStackSlot(MF, Reg, isKill, FrameIdx,
628 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
630 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
631 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
633 getKillRegState(isKill)),
636 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
637 assert(TM.getSubtargetImpl()->isDarwin() &&
638 "VRSAVE only needs spill/restore on Darwin");
639 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
641 getKillRegState(isKill)),
645 llvm_unreachable("Unknown regclass!");
652 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
653 MachineBasicBlock::iterator MI,
654 unsigned SrcReg, bool isKill, int FrameIdx,
655 const TargetRegisterClass *RC,
656 const TargetRegisterInfo *TRI) const {
657 MachineFunction &MF = *MBB.getParent();
658 SmallVector<MachineInstr*, 4> NewMIs;
660 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
661 FuncInfo->setHasSpills();
663 bool NonRI = false, SpillsVRS = false;
664 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
666 FuncInfo->setSpillsCR();
669 FuncInfo->setSpillsVRSAVE();
672 FuncInfo->setHasNonRISpills();
674 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
675 MBB.insert(MI, NewMIs[i]);
677 const MachineFrameInfo &MFI = *MF.getFrameInfo();
678 MachineMemOperand *MMO =
679 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
680 MachineMemOperand::MOStore,
681 MFI.getObjectSize(FrameIdx),
682 MFI.getObjectAlignment(FrameIdx));
683 NewMIs.back()->addMemOperand(MF, MMO);
687 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
688 unsigned DestReg, int FrameIdx,
689 const TargetRegisterClass *RC,
690 SmallVectorImpl<MachineInstr*> &NewMIs,
691 bool &NonRI, bool &SpillsVRS) const{
692 // Note: If additional load instructions are added here,
693 // update isLoadFromStackSlot.
695 if (PPC::GPRCRegClass.hasSubClassEq(RC)) {
696 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
697 DestReg), FrameIdx));
698 } else if (PPC::G8RCRegClass.hasSubClassEq(RC)) {
699 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
701 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
702 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
704 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
705 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
707 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
708 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
709 get(PPC::RESTORE_CR), DestReg),
712 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
715 if (DestReg == PPC::CR0LT || DestReg == PPC::CR0GT ||
716 DestReg == PPC::CR0EQ || DestReg == PPC::CR0UN)
718 else if (DestReg == PPC::CR1LT || DestReg == PPC::CR1GT ||
719 DestReg == PPC::CR1EQ || DestReg == PPC::CR1UN)
721 else if (DestReg == PPC::CR2LT || DestReg == PPC::CR2GT ||
722 DestReg == PPC::CR2EQ || DestReg == PPC::CR2UN)
724 else if (DestReg == PPC::CR3LT || DestReg == PPC::CR3GT ||
725 DestReg == PPC::CR3EQ || DestReg == PPC::CR3UN)
727 else if (DestReg == PPC::CR4LT || DestReg == PPC::CR4GT ||
728 DestReg == PPC::CR4EQ || DestReg == PPC::CR4UN)
730 else if (DestReg == PPC::CR5LT || DestReg == PPC::CR5GT ||
731 DestReg == PPC::CR5EQ || DestReg == PPC::CR5UN)
733 else if (DestReg == PPC::CR6LT || DestReg == PPC::CR6GT ||
734 DestReg == PPC::CR6EQ || DestReg == PPC::CR6UN)
736 else if (DestReg == PPC::CR7LT || DestReg == PPC::CR7GT ||
737 DestReg == PPC::CR7EQ || DestReg == PPC::CR7UN)
740 return LoadRegFromStackSlot(MF, DL, Reg, FrameIdx,
741 &PPC::CRRCRegClass, NewMIs, NonRI, SpillsVRS);
743 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
744 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
747 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
748 assert(TM.getSubtargetImpl()->isDarwin() &&
749 "VRSAVE only needs spill/restore on Darwin");
750 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
751 get(PPC::RESTORE_VRSAVE),
756 llvm_unreachable("Unknown regclass!");
763 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
764 MachineBasicBlock::iterator MI,
765 unsigned DestReg, int FrameIdx,
766 const TargetRegisterClass *RC,
767 const TargetRegisterInfo *TRI) const {
768 MachineFunction &MF = *MBB.getParent();
769 SmallVector<MachineInstr*, 4> NewMIs;
771 if (MI != MBB.end()) DL = MI->getDebugLoc();
773 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
774 FuncInfo->setHasSpills();
776 bool NonRI = false, SpillsVRS = false;
777 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
779 FuncInfo->setSpillsCR();
782 FuncInfo->setSpillsVRSAVE();
785 FuncInfo->setHasNonRISpills();
787 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
788 MBB.insert(MI, NewMIs[i]);
790 const MachineFrameInfo &MFI = *MF.getFrameInfo();
791 MachineMemOperand *MMO =
792 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
793 MachineMemOperand::MOLoad,
794 MFI.getObjectSize(FrameIdx),
795 MFI.getObjectAlignment(FrameIdx));
796 NewMIs.back()->addMemOperand(MF, MMO);
800 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
801 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
802 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
803 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
805 // Leave the CR# the same, but invert the condition.
806 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
810 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
811 unsigned Reg, MachineRegisterInfo *MRI) const {
812 // For some instructions, it is legal to fold ZERO into the RA register field.
813 // A zero immediate should always be loaded with a single li.
814 unsigned DefOpc = DefMI->getOpcode();
815 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
817 if (!DefMI->getOperand(1).isImm())
819 if (DefMI->getOperand(1).getImm() != 0)
822 // Note that we cannot here invert the arguments of an isel in order to fold
823 // a ZERO into what is presented as the second argument. All we have here
824 // is the condition bit, and that might come from a CR-logical bit operation.
826 const MCInstrDesc &UseMCID = UseMI->getDesc();
828 // Only fold into real machine instructions.
829 if (UseMCID.isPseudo())
833 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
834 if (UseMI->getOperand(UseIdx).isReg() &&
835 UseMI->getOperand(UseIdx).getReg() == Reg)
838 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
839 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
841 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
843 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
844 // register (which might also be specified as a pointer class kind).
845 if (UseInfo->isLookupPtrRegClass()) {
846 if (UseInfo->RegClass /* Kind */ != 1)
849 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
850 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
854 // Make sure this is not tied to an output register (or otherwise
855 // constrained). This is true for ST?UX registers, for example, which
856 // are tied to their output registers.
857 if (UseInfo->Constraints != 0)
861 if (UseInfo->isLookupPtrRegClass()) {
862 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
863 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
865 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
866 PPC::ZERO8 : PPC::ZERO;
869 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
870 UseMI->getOperand(UseIdx).setReg(ZeroReg);
873 DefMI->eraseFromParent();
878 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
879 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
881 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
886 // We should make sure that, if we're going to predicate both sides of a
887 // condition (a diamond), that both sides don't define the counter register. We
888 // can predicate counter-decrement-based branches, but while that predicates
889 // the branching, it does not predicate the counter decrement. If we tried to
890 // merge the triangle into one predicated block, we'd decrement the counter
892 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
893 unsigned NumT, unsigned ExtraT,
894 MachineBasicBlock &FMBB,
895 unsigned NumF, unsigned ExtraF,
896 const BranchProbability &Probability) const {
897 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
901 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
902 // The predicated branches are identified by their type, not really by the
903 // explicit presence of a predicate. Furthermore, some of them can be
904 // predicated more than once. Because if conversion won't try to predicate
905 // any instruction which already claims to be predicated (by returning true
906 // here), always return false. In doing so, we let isPredicable() be the
907 // final word on whether not the instruction can be (further) predicated.
912 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
913 if (!MI->isTerminator())
916 // Conditional branch is a special case.
917 if (MI->isBranch() && !MI->isBarrier())
920 return !isPredicated(MI);
923 bool PPCInstrInfo::PredicateInstruction(
925 const SmallVectorImpl<MachineOperand> &Pred) const {
926 unsigned OpC = MI->getOpcode();
927 if (OpC == PPC::BLR) {
928 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
929 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
930 MI->setDesc(get(Pred[0].getImm() ?
931 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
932 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
934 MI->setDesc(get(PPC::BCLR));
935 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
936 .addImm(Pred[0].getImm())
937 .addReg(Pred[1].getReg());
941 } else if (OpC == PPC::B) {
942 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
943 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
944 MI->setDesc(get(Pred[0].getImm() ?
945 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
946 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
948 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
949 MI->RemoveOperand(0);
951 MI->setDesc(get(PPC::BCC));
952 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
953 .addImm(Pred[0].getImm())
954 .addReg(Pred[1].getReg())
959 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
960 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
961 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
962 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
964 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
965 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
966 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
967 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
968 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
969 .addImm(Pred[0].getImm())
970 .addReg(Pred[1].getReg());
977 bool PPCInstrInfo::SubsumesPredicate(
978 const SmallVectorImpl<MachineOperand> &Pred1,
979 const SmallVectorImpl<MachineOperand> &Pred2) const {
980 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
981 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
983 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
985 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
988 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
989 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
994 // Does P1 subsume P2, e.g. GE subsumes GT.
995 if (P1 == PPC::PRED_LE &&
996 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
998 if (P1 == PPC::PRED_GE &&
999 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1005 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1006 std::vector<MachineOperand> &Pred) const {
1007 // Note: At the present time, the contents of Pred from this function is
1008 // unused by IfConversion. This implementation follows ARM by pushing the
1009 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1010 // predicate, instructions defining CTR or CTR8 are also included as
1011 // predicate-defining instructions.
1013 const TargetRegisterClass *RCs[] =
1014 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1015 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1018 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1019 const MachineOperand &MO = MI->getOperand(i);
1020 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1021 const TargetRegisterClass *RC = RCs[c];
1023 if (MO.isDef() && RC->contains(MO.getReg())) {
1027 } else if (MO.isRegMask()) {
1028 for (TargetRegisterClass::iterator I = RC->begin(),
1029 IE = RC->end(); I != IE; ++I)
1030 if (MO.clobbersPhysReg(*I)) {
1041 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1042 unsigned OpC = MI->getOpcode();
1056 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1057 unsigned &SrcReg, unsigned &SrcReg2,
1058 int &Mask, int &Value) const {
1059 unsigned Opc = MI->getOpcode();
1062 default: return false;
1067 SrcReg = MI->getOperand(1).getReg();
1069 Value = MI->getOperand(2).getImm();
1078 SrcReg = MI->getOperand(1).getReg();
1079 SrcReg2 = MI->getOperand(2).getReg();
1084 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1085 unsigned SrcReg, unsigned SrcReg2,
1086 int Mask, int Value,
1087 const MachineRegisterInfo *MRI) const {
1091 int OpC = CmpInstr->getOpcode();
1092 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1094 // FP record forms set CR1 based on the execption status bits, not a
1095 // comparison with zero.
1096 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1099 // The record forms set the condition register based on a signed comparison
1100 // with zero (so says the ISA manual). This is not as straightforward as it
1101 // seems, however, because this is always a 64-bit comparison on PPC64, even
1102 // for instructions that are 32-bit in nature (like slw for example).
1103 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1104 // for equality checks (as those don't depend on the sign). On PPC64,
1105 // we are restricted to equality for unsigned 64-bit comparisons and for
1106 // signed 32-bit comparisons the applicability is more restricted.
1107 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1108 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1109 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1110 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1112 // Get the unique definition of SrcReg.
1113 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1114 if (!MI) return false;
1115 int MIOpC = MI->getOpcode();
1117 bool equalityOnly = false;
1120 if (is32BitSignedCompare) {
1121 // We can perform this optimization only if MI is sign-extending.
1122 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1123 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1124 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1125 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1126 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1130 } else if (is32BitUnsignedCompare) {
1131 // We can perform this optimization, equality only, if MI is
1133 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1134 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1135 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1137 equalityOnly = true;
1141 equalityOnly = is64BitUnsignedCompare;
1143 equalityOnly = is32BitUnsignedCompare;
1146 // We need to check the uses of the condition register in order to reject
1147 // non-equality comparisons.
1148 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1149 IE = MRI->use_end(); I != IE; ++I) {
1150 MachineInstr *UseMI = &*I;
1151 if (UseMI->getOpcode() == PPC::BCC) {
1152 unsigned Pred = UseMI->getOperand(0).getImm();
1153 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1155 } else if (UseMI->getOpcode() == PPC::ISEL ||
1156 UseMI->getOpcode() == PPC::ISEL8) {
1157 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1158 if (SubIdx != PPC::sub_eq)
1165 MachineBasicBlock::iterator I = CmpInstr;
1167 // Scan forward to find the first use of the compare.
1168 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1170 bool FoundUse = false;
1171 for (MachineRegisterInfo::use_iterator J = MRI->use_begin(CRReg),
1172 JE = MRI->use_end(); J != JE; ++J)
1182 // There are two possible candidates which can be changed to set CR[01].
1183 // One is MI, the other is a SUB instruction.
1184 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1185 MachineInstr *Sub = NULL;
1187 // MI is not a candidate for CMPrr.
1189 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1190 // same BB as the comparison. This is to allow the check below to avoid calls
1191 // (and other explicit clobbers); instead we should really check for these
1192 // more explicitly (in at least a few predecessors).
1193 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1194 // PPC does not have a record-form SUBri.
1199 const TargetRegisterInfo *TRI = &getRegisterInfo();
1202 // Get ready to iterate backward from CmpInstr.
1203 MachineBasicBlock::iterator E = MI,
1204 B = CmpInstr->getParent()->begin();
1206 for (; I != E && !noSub; --I) {
1207 const MachineInstr &Instr = *I;
1208 unsigned IOpC = Instr.getOpcode();
1210 if (&*I != CmpInstr && (
1211 Instr.modifiesRegister(PPC::CR0, TRI) ||
1212 Instr.readsRegister(PPC::CR0, TRI)))
1213 // This instruction modifies or uses the record condition register after
1214 // the one we want to change. While we could do this transformation, it
1215 // would likely not be profitable. This transformation removes one
1216 // instruction, and so even forcing RA to generate one move probably
1217 // makes it unprofitable.
1220 // Check whether CmpInstr can be made redundant by the current instruction.
1221 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1222 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1223 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1224 ((Instr.getOperand(1).getReg() == SrcReg &&
1225 Instr.getOperand(2).getReg() == SrcReg2) ||
1226 (Instr.getOperand(1).getReg() == SrcReg2 &&
1227 Instr.getOperand(2).getReg() == SrcReg))) {
1233 // The 'and' is below the comparison instruction.
1237 // Return false if no candidates exist.
1241 // The single candidate is called MI.
1245 MIOpC = MI->getOpcode();
1246 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1249 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1250 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1254 // FIXME: On the non-embedded POWER architectures, only some of the record
1255 // forms are fast, and we should use only the fast ones.
1257 // The defining instruction has a record form (or is already a record
1258 // form). It is possible, however, that we'll need to reverse the condition
1259 // code of the users.
1263 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1264 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1266 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1267 // needs to be updated to be based on SUB. Push the condition code
1268 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1269 // condition code of these operands will be modified.
1270 bool ShouldSwap = false;
1272 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1273 Sub->getOperand(2).getReg() == SrcReg;
1275 // The operands to subf are the opposite of sub, so only in the fixed-point
1276 // case, invert the order.
1277 ShouldSwap = !ShouldSwap;
1281 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1282 IE = MRI->use_end(); I != IE; ++I) {
1283 MachineInstr *UseMI = &*I;
1284 if (UseMI->getOpcode() == PPC::BCC) {
1285 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1286 assert((!equalityOnly ||
1287 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1288 "Invalid predicate for equality-only optimization");
1289 PredsToUpdate.push_back(std::make_pair(&((*I).getOperand(0)),
1290 PPC::getSwappedPredicate(Pred)));
1291 } else if (UseMI->getOpcode() == PPC::ISEL ||
1292 UseMI->getOpcode() == PPC::ISEL8) {
1293 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1294 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1295 "Invalid CR bit for equality-only optimization");
1297 if (NewSubReg == PPC::sub_lt)
1298 NewSubReg = PPC::sub_gt;
1299 else if (NewSubReg == PPC::sub_gt)
1300 NewSubReg = PPC::sub_lt;
1302 SubRegsToUpdate.push_back(std::make_pair(&((*I).getOperand(3)),
1304 } else // We need to abort on a user we don't understand.
1308 // Create a new virtual register to hold the value of the CR set by the
1309 // record-form instruction. If the instruction was not previously in
1310 // record form, then set the kill flag on the CR.
1311 CmpInstr->eraseFromParent();
1313 MachineBasicBlock::iterator MII = MI;
1314 BuildMI(*MI->getParent(), llvm::next(MII), MI->getDebugLoc(),
1315 get(TargetOpcode::COPY), CRReg)
1316 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1318 if (MIOpC != NewOpC) {
1319 // We need to be careful here: we're replacing one instruction with
1320 // another, and we need to make sure that we get all of the right
1321 // implicit uses and defs. On the other hand, the caller may be holding
1322 // an iterator to this instruction, and so we can't delete it (this is
1323 // specifically the case if this is the instruction directly after the
1326 const MCInstrDesc &NewDesc = get(NewOpC);
1327 MI->setDesc(NewDesc);
1329 if (NewDesc.ImplicitDefs)
1330 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1331 *ImpDefs; ++ImpDefs)
1332 if (!MI->definesRegister(*ImpDefs))
1333 MI->addOperand(*MI->getParent()->getParent(),
1334 MachineOperand::CreateReg(*ImpDefs, true, true));
1335 if (NewDesc.ImplicitUses)
1336 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1337 *ImpUses; ++ImpUses)
1338 if (!MI->readsRegister(*ImpUses))
1339 MI->addOperand(*MI->getParent()->getParent(),
1340 MachineOperand::CreateReg(*ImpUses, false, true));
1343 // Modify the condition code of operands in OperandsToUpdate.
1344 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1345 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1346 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1347 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1349 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1350 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1355 /// GetInstSize - Return the number of bytes of code the specified
1356 /// instruction may be. This returns the maximum number of bytes.
1358 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1359 switch (MI->getOpcode()) {
1360 case PPC::INLINEASM: { // Inline Asm: Variable size.
1361 const MachineFunction *MF = MI->getParent()->getParent();
1362 const char *AsmStr = MI->getOperand(0).getSymbolName();
1363 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1365 case PPC::PROLOG_LABEL:
1368 case PPC::DBG_VALUE:
1374 return 4; // PowerPC instructions are all 4 bytes
1379 #define DEBUG_TYPE "ppc-early-ret"
1380 STATISTIC(NumBCLR, "Number of early conditional returns");
1381 STATISTIC(NumBLR, "Number of early returns");
1384 void initializePPCEarlyReturnPass(PassRegistry&);
1388 // PPCEarlyReturn pass - For simple functions without epilogue code, move
1389 // returns up, and create conditional returns, to avoid unnecessary
1390 // branch-to-blr sequences.
1391 struct PPCEarlyReturn : public MachineFunctionPass {
1393 PPCEarlyReturn() : MachineFunctionPass(ID) {
1394 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1397 const PPCTargetMachine *TM;
1398 const PPCInstrInfo *TII;
1401 bool processBlock(MachineBasicBlock &ReturnMBB) {
1402 bool Changed = false;
1404 MachineBasicBlock::iterator I = ReturnMBB.begin();
1405 I = ReturnMBB.SkipPHIsAndLabels(I);
1407 // The block must be essentially empty except for the blr.
1408 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1409 I != ReturnMBB.getLastNonDebugInstr())
1412 SmallVector<MachineBasicBlock*, 8> PredToRemove;
1413 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1414 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1415 bool OtherReference = false, BlockChanged = false;
1416 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1417 if (J->getOpcode() == PPC::B) {
1418 if (J->getOperand(0).getMBB() == &ReturnMBB) {
1419 // This is an unconditional branch to the return. Replace the
1420 // branch with a blr.
1421 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1422 MachineBasicBlock::iterator K = J--;
1423 K->eraseFromParent();
1424 BlockChanged = true;
1428 } else if (J->getOpcode() == PPC::BCC) {
1429 if (J->getOperand(2).getMBB() == &ReturnMBB) {
1430 // This is a conditional branch to the return. Replace the branch
1432 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCLR))
1433 .addImm(J->getOperand(0).getImm())
1434 .addReg(J->getOperand(1).getReg());
1435 MachineBasicBlock::iterator K = J--;
1436 K->eraseFromParent();
1437 BlockChanged = true;
1441 } else if (J->isBranch()) {
1442 if (J->isIndirectBranch()) {
1443 if (ReturnMBB.hasAddressTaken())
1444 OtherReference = true;
1446 for (unsigned i = 0; i < J->getNumOperands(); ++i)
1447 if (J->getOperand(i).isMBB() &&
1448 J->getOperand(i).getMBB() == &ReturnMBB)
1449 OtherReference = true;
1450 } else if (!J->isTerminator() && !J->isDebugValue())
1453 if (J == (*PI)->begin())
1459 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1460 OtherReference = true;
1462 // Predecessors are stored in a vector and can't be removed here.
1463 if (!OtherReference && BlockChanged) {
1464 PredToRemove.push_back(*PI);
1471 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1472 PredToRemove[i]->removeSuccessor(&ReturnMBB);
1474 if (Changed && !ReturnMBB.hasAddressTaken()) {
1475 // We now might be able to merge this blr-only block into its
1476 // by-layout predecessor.
1477 if (ReturnMBB.pred_size() == 1 &&
1478 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1479 // Move the blr into the preceding block.
1480 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1481 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1482 PrevMBB.removeSuccessor(&ReturnMBB);
1485 if (ReturnMBB.pred_empty())
1486 ReturnMBB.eraseFromParent();
1493 virtual bool runOnMachineFunction(MachineFunction &MF) {
1494 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1495 TII = TM->getInstrInfo();
1497 bool Changed = false;
1499 // If the function does not have at least two blocks, then there is
1504 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1505 MachineBasicBlock &B = *I++;
1506 if (processBlock(B))
1513 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1514 MachineFunctionPass::getAnalysisUsage(AU);
1519 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1520 "PowerPC Early-Return Creation", false, false)
1522 char PPCEarlyReturn::ID = 0;
1524 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }