1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the PowerPC implementation of the TargetInstrInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCHazardRecognizers.h"
18 #include "PPCInstrBuilder.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/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:
166 case PPC::RESTORE_CRBIT:
168 case PPC::RESTORE_VRSAVE:
169 // Check for the operands added by addFrameReference (the immediate is the
170 // offset which defaults to 0).
171 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
172 MI->getOperand(2).isFI()) {
173 FrameIndex = MI->getOperand(2).getIndex();
174 return MI->getOperand(0).getReg();
181 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
182 int &FrameIndex) const {
183 // Note: This list must be kept consistent with StoreRegToStackSlot.
184 switch (MI->getOpcode()) {
191 case PPC::SPILL_CRBIT:
193 case PPC::SPILL_VRSAVE:
194 // Check for the operands added by addFrameReference (the immediate is the
195 // offset which defaults to 0).
196 if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
197 MI->getOperand(2).isFI()) {
198 FrameIndex = MI->getOperand(2).getIndex();
199 return MI->getOperand(0).getReg();
206 // commuteInstruction - We can commute rlwimi instructions, but only if the
207 // rotate amt is zero. We also have to munge the immediates a bit.
209 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
210 MachineFunction &MF = *MI->getParent()->getParent();
212 // Normal instructions can be commuted the obvious way.
213 if (MI->getOpcode() != PPC::RLWIMI &&
214 MI->getOpcode() != PPC::RLWIMIo &&
215 MI->getOpcode() != PPC::RLWIMI8 &&
216 MI->getOpcode() != PPC::RLWIMI8o)
217 return TargetInstrInfo::commuteInstruction(MI, NewMI);
219 // Cannot commute if it has a non-zero rotate count.
220 if (MI->getOperand(3).getImm() != 0)
223 // If we have a zero rotate count, we have:
225 // Op0 = (Op1 & ~M) | (Op2 & M)
227 // M = mask((ME+1)&31, (MB-1)&31)
228 // Op0 = (Op2 & ~M) | (Op1 & M)
231 unsigned Reg0 = MI->getOperand(0).getReg();
232 unsigned Reg1 = MI->getOperand(1).getReg();
233 unsigned Reg2 = MI->getOperand(2).getReg();
234 unsigned SubReg1 = MI->getOperand(1).getSubReg();
235 unsigned SubReg2 = MI->getOperand(2).getSubReg();
236 bool Reg1IsKill = MI->getOperand(1).isKill();
237 bool Reg2IsKill = MI->getOperand(2).isKill();
238 bool ChangeReg0 = false;
239 // If machine instrs are no longer in two-address forms, update
240 // destination register as well.
242 // Must be two address instruction!
243 assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
244 "Expecting a two-address instruction!");
245 assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
251 unsigned MB = MI->getOperand(4).getImm();
252 unsigned ME = MI->getOperand(5).getImm();
255 // Create a new instruction.
256 unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
257 bool Reg0IsDead = MI->getOperand(0).isDead();
258 return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
259 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
260 .addReg(Reg2, getKillRegState(Reg2IsKill))
261 .addReg(Reg1, getKillRegState(Reg1IsKill))
263 .addImm((MB-1) & 31);
267 MI->getOperand(0).setReg(Reg2);
268 MI->getOperand(0).setSubReg(SubReg2);
270 MI->getOperand(2).setReg(Reg1);
271 MI->getOperand(1).setReg(Reg2);
272 MI->getOperand(2).setSubReg(SubReg1);
273 MI->getOperand(1).setSubReg(SubReg2);
274 MI->getOperand(2).setIsKill(Reg1IsKill);
275 MI->getOperand(1).setIsKill(Reg2IsKill);
277 // Swap the mask around.
278 MI->getOperand(4).setImm((ME+1) & 31);
279 MI->getOperand(5).setImm((MB-1) & 31);
283 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
284 MachineBasicBlock::iterator MI) const {
285 // This function is used for scheduling, and the nop wanted here is the type
286 // that terminates dispatch groups on the POWER cores.
287 unsigned Directive = TM.getSubtarget<PPCSubtarget>().getDarwinDirective();
290 default: Opcode = PPC::NOP; break;
291 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
292 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
296 BuildMI(MBB, MI, DL, get(Opcode));
300 // Note: If the condition register is set to CTR or CTR8 then this is a
301 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
302 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
303 MachineBasicBlock *&FBB,
304 SmallVectorImpl<MachineOperand> &Cond,
305 bool AllowModify) const {
306 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
308 // If the block has no terminators, it just falls into the block after it.
309 MachineBasicBlock::iterator I = MBB.end();
310 if (I == MBB.begin())
313 while (I->isDebugValue()) {
314 if (I == MBB.begin())
318 if (!isUnpredicatedTerminator(I))
321 // Get the last instruction in the block.
322 MachineInstr *LastInst = I;
324 // If there is only one terminator instruction, process it.
325 if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
326 if (LastInst->getOpcode() == PPC::B) {
327 if (!LastInst->getOperand(0).isMBB())
329 TBB = LastInst->getOperand(0).getMBB();
331 } else if (LastInst->getOpcode() == PPC::BCC) {
332 if (!LastInst->getOperand(2).isMBB())
334 // Block ends with fall-through condbranch.
335 TBB = LastInst->getOperand(2).getMBB();
336 Cond.push_back(LastInst->getOperand(0));
337 Cond.push_back(LastInst->getOperand(1));
339 } else if (LastInst->getOpcode() == PPC::BC) {
340 if (!LastInst->getOperand(1).isMBB())
342 // Block ends with fall-through condbranch.
343 TBB = LastInst->getOperand(1).getMBB();
344 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
345 Cond.push_back(LastInst->getOperand(0));
347 } else if (LastInst->getOpcode() == PPC::BCn) {
348 if (!LastInst->getOperand(1).isMBB())
350 // Block ends with fall-through condbranch.
351 TBB = LastInst->getOperand(1).getMBB();
352 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
353 Cond.push_back(LastInst->getOperand(0));
355 } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
356 LastInst->getOpcode() == PPC::BDNZ) {
357 if (!LastInst->getOperand(0).isMBB())
359 if (DisableCTRLoopAnal)
361 TBB = LastInst->getOperand(0).getMBB();
362 Cond.push_back(MachineOperand::CreateImm(1));
363 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
366 } else if (LastInst->getOpcode() == PPC::BDZ8 ||
367 LastInst->getOpcode() == PPC::BDZ) {
368 if (!LastInst->getOperand(0).isMBB())
370 if (DisableCTRLoopAnal)
372 TBB = LastInst->getOperand(0).getMBB();
373 Cond.push_back(MachineOperand::CreateImm(0));
374 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
379 // Otherwise, don't know what this is.
383 // Get the instruction before it if it's a terminator.
384 MachineInstr *SecondLastInst = I;
386 // If there are three terminators, we don't know what sort of block this is.
387 if (SecondLastInst && I != MBB.begin() &&
388 isUnpredicatedTerminator(--I))
391 // If the block ends with PPC::B and PPC:BCC, handle it.
392 if (SecondLastInst->getOpcode() == PPC::BCC &&
393 LastInst->getOpcode() == PPC::B) {
394 if (!SecondLastInst->getOperand(2).isMBB() ||
395 !LastInst->getOperand(0).isMBB())
397 TBB = SecondLastInst->getOperand(2).getMBB();
398 Cond.push_back(SecondLastInst->getOperand(0));
399 Cond.push_back(SecondLastInst->getOperand(1));
400 FBB = LastInst->getOperand(0).getMBB();
402 } else if (SecondLastInst->getOpcode() == PPC::BC &&
403 LastInst->getOpcode() == PPC::B) {
404 if (!SecondLastInst->getOperand(1).isMBB() ||
405 !LastInst->getOperand(0).isMBB())
407 TBB = SecondLastInst->getOperand(1).getMBB();
408 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
409 Cond.push_back(SecondLastInst->getOperand(0));
410 FBB = LastInst->getOperand(0).getMBB();
412 } else if (SecondLastInst->getOpcode() == PPC::BCn &&
413 LastInst->getOpcode() == PPC::B) {
414 if (!SecondLastInst->getOperand(1).isMBB() ||
415 !LastInst->getOperand(0).isMBB())
417 TBB = SecondLastInst->getOperand(1).getMBB();
418 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
419 Cond.push_back(SecondLastInst->getOperand(0));
420 FBB = LastInst->getOperand(0).getMBB();
422 } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
423 SecondLastInst->getOpcode() == PPC::BDNZ) &&
424 LastInst->getOpcode() == PPC::B) {
425 if (!SecondLastInst->getOperand(0).isMBB() ||
426 !LastInst->getOperand(0).isMBB())
428 if (DisableCTRLoopAnal)
430 TBB = SecondLastInst->getOperand(0).getMBB();
431 Cond.push_back(MachineOperand::CreateImm(1));
432 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
434 FBB = LastInst->getOperand(0).getMBB();
436 } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
437 SecondLastInst->getOpcode() == PPC::BDZ) &&
438 LastInst->getOpcode() == PPC::B) {
439 if (!SecondLastInst->getOperand(0).isMBB() ||
440 !LastInst->getOperand(0).isMBB())
442 if (DisableCTRLoopAnal)
444 TBB = SecondLastInst->getOperand(0).getMBB();
445 Cond.push_back(MachineOperand::CreateImm(0));
446 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
448 FBB = LastInst->getOperand(0).getMBB();
452 // If the block ends with two PPC:Bs, handle it. The second one is not
453 // executed, so remove it.
454 if (SecondLastInst->getOpcode() == PPC::B &&
455 LastInst->getOpcode() == PPC::B) {
456 if (!SecondLastInst->getOperand(0).isMBB())
458 TBB = SecondLastInst->getOperand(0).getMBB();
461 I->eraseFromParent();
465 // Otherwise, can't handle this.
469 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
470 MachineBasicBlock::iterator I = MBB.end();
471 if (I == MBB.begin()) return 0;
473 while (I->isDebugValue()) {
474 if (I == MBB.begin())
478 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
479 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
480 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
481 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
484 // Remove the branch.
485 I->eraseFromParent();
489 if (I == MBB.begin()) return 1;
491 if (I->getOpcode() != PPC::BCC &&
492 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
493 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
494 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ)
497 // Remove the branch.
498 I->eraseFromParent();
503 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
504 MachineBasicBlock *FBB,
505 const SmallVectorImpl<MachineOperand> &Cond,
507 // Shouldn't be a fall through.
508 assert(TBB && "InsertBranch must not be told to insert a fallthrough");
509 assert((Cond.size() == 2 || Cond.size() == 0) &&
510 "PPC branch conditions have two components!");
512 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
516 if (Cond.empty()) // Unconditional branch
517 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
518 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
519 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
520 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
521 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
522 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
523 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
524 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
525 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
526 else // Conditional branch
527 BuildMI(&MBB, DL, get(PPC::BCC))
528 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
532 // Two-way Conditional Branch.
533 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
534 BuildMI(&MBB, DL, get(Cond[0].getImm() ?
535 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
536 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB);
537 else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
538 BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
539 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
540 BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
542 BuildMI(&MBB, DL, get(PPC::BCC))
543 .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
544 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
549 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
550 const SmallVectorImpl<MachineOperand> &Cond,
551 unsigned TrueReg, unsigned FalseReg,
552 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
553 if (!TM.getSubtargetImpl()->hasISEL())
556 if (Cond.size() != 2)
559 // If this is really a bdnz-like condition, then it cannot be turned into a
561 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
564 // Check register classes.
565 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
566 const TargetRegisterClass *RC =
567 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
571 // isel is for regular integer GPRs only.
572 if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
573 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
574 !PPC::G8RCRegClass.hasSubClassEq(RC) &&
575 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
578 // FIXME: These numbers are for the A2, how well they work for other cores is
579 // an open question. On the A2, the isel instruction has a 2-cycle latency
580 // but single-cycle throughput. These numbers are used in combination with
581 // the MispredictPenalty setting from the active SchedMachineModel.
589 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
590 MachineBasicBlock::iterator MI, DebugLoc dl,
592 const SmallVectorImpl<MachineOperand> &Cond,
593 unsigned TrueReg, unsigned FalseReg) const {
594 assert(Cond.size() == 2 &&
595 "PPC branch conditions have two components!");
597 assert(TM.getSubtargetImpl()->hasISEL() &&
598 "Cannot insert select on target without ISEL support");
600 // Get the register classes.
601 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
602 const TargetRegisterClass *RC =
603 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
604 assert(RC && "TrueReg and FalseReg must have overlapping register classes");
606 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
607 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
609 PPC::GPRCRegClass.hasSubClassEq(RC) ||
610 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
611 "isel is for regular integer GPRs only");
613 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
614 unsigned SelectPred = Cond[0].getImm();
618 switch (SelectPred) {
619 default: llvm_unreachable("invalid predicate for isel");
620 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
621 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
622 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
623 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
624 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
625 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
626 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
627 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
628 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break;
629 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
632 unsigned FirstReg = SwapOps ? FalseReg : TrueReg,
633 SecondReg = SwapOps ? TrueReg : FalseReg;
635 // The first input register of isel cannot be r0. If it is a member
636 // of a register class that can be r0, then copy it first (the
637 // register allocator should eliminate the copy).
638 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
639 MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
640 const TargetRegisterClass *FirstRC =
641 MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
642 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
643 unsigned OldFirstReg = FirstReg;
644 FirstReg = MRI.createVirtualRegister(FirstRC);
645 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
646 .addReg(OldFirstReg);
649 BuildMI(MBB, MI, dl, get(OpCode), DestReg)
650 .addReg(FirstReg).addReg(SecondReg)
651 .addReg(Cond[1].getReg(), 0, SubIdx);
654 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
655 MachineBasicBlock::iterator I, DebugLoc DL,
656 unsigned DestReg, unsigned SrcReg,
657 bool KillSrc) const {
659 if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
661 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
663 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
665 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
667 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
669 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
672 llvm_unreachable("Impossible reg-to-reg copy");
674 const MCInstrDesc &MCID = get(Opc);
675 if (MCID.getNumOperands() == 3)
676 BuildMI(MBB, I, DL, MCID, DestReg)
677 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
679 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
682 // This function returns true if a CR spill is necessary and false otherwise.
684 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
685 unsigned SrcReg, bool isKill,
687 const TargetRegisterClass *RC,
688 SmallVectorImpl<MachineInstr*> &NewMIs,
689 bool &NonRI, bool &SpillsVRS) const{
690 // Note: If additional store instructions are added here,
691 // update isStoreToStackSlot.
694 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
695 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
696 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
698 getKillRegState(isKill)),
700 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
701 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
702 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
704 getKillRegState(isKill)),
706 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
707 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
709 getKillRegState(isKill)),
711 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
712 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
714 getKillRegState(isKill)),
716 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
717 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
719 getKillRegState(isKill)),
722 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
723 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
725 getKillRegState(isKill)),
728 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
729 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
731 getKillRegState(isKill)),
734 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
735 assert(TM.getSubtargetImpl()->isDarwin() &&
736 "VRSAVE only needs spill/restore on Darwin");
737 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
739 getKillRegState(isKill)),
743 llvm_unreachable("Unknown regclass!");
750 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
751 MachineBasicBlock::iterator MI,
752 unsigned SrcReg, bool isKill, int FrameIdx,
753 const TargetRegisterClass *RC,
754 const TargetRegisterInfo *TRI) const {
755 MachineFunction &MF = *MBB.getParent();
756 SmallVector<MachineInstr*, 4> NewMIs;
758 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
759 FuncInfo->setHasSpills();
761 bool NonRI = false, SpillsVRS = false;
762 if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
764 FuncInfo->setSpillsCR();
767 FuncInfo->setSpillsVRSAVE();
770 FuncInfo->setHasNonRISpills();
772 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
773 MBB.insert(MI, NewMIs[i]);
775 const MachineFrameInfo &MFI = *MF.getFrameInfo();
776 MachineMemOperand *MMO =
777 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
778 MachineMemOperand::MOStore,
779 MFI.getObjectSize(FrameIdx),
780 MFI.getObjectAlignment(FrameIdx));
781 NewMIs.back()->addMemOperand(MF, MMO);
785 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
786 unsigned DestReg, int FrameIdx,
787 const TargetRegisterClass *RC,
788 SmallVectorImpl<MachineInstr*> &NewMIs,
789 bool &NonRI, bool &SpillsVRS) const{
790 // Note: If additional load instructions are added here,
791 // update isLoadFromStackSlot.
793 if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
794 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
795 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
796 DestReg), FrameIdx));
797 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
798 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
799 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
801 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
802 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
804 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
805 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
807 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
808 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
809 get(PPC::RESTORE_CR), DestReg),
812 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
813 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
814 get(PPC::RESTORE_CRBIT), DestReg),
817 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
818 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
821 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
822 assert(TM.getSubtargetImpl()->isDarwin() &&
823 "VRSAVE only needs spill/restore on Darwin");
824 NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
825 get(PPC::RESTORE_VRSAVE),
830 llvm_unreachable("Unknown regclass!");
837 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
838 MachineBasicBlock::iterator MI,
839 unsigned DestReg, int FrameIdx,
840 const TargetRegisterClass *RC,
841 const TargetRegisterInfo *TRI) const {
842 MachineFunction &MF = *MBB.getParent();
843 SmallVector<MachineInstr*, 4> NewMIs;
845 if (MI != MBB.end()) DL = MI->getDebugLoc();
847 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
848 FuncInfo->setHasSpills();
850 bool NonRI = false, SpillsVRS = false;
851 if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
853 FuncInfo->setSpillsCR();
856 FuncInfo->setSpillsVRSAVE();
859 FuncInfo->setHasNonRISpills();
861 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
862 MBB.insert(MI, NewMIs[i]);
864 const MachineFrameInfo &MFI = *MF.getFrameInfo();
865 MachineMemOperand *MMO =
866 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
867 MachineMemOperand::MOLoad,
868 MFI.getObjectSize(FrameIdx),
869 MFI.getObjectAlignment(FrameIdx));
870 NewMIs.back()->addMemOperand(MF, MMO);
874 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
875 assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
876 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
877 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
879 // Leave the CR# the same, but invert the condition.
880 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
884 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
885 unsigned Reg, MachineRegisterInfo *MRI) const {
886 // For some instructions, it is legal to fold ZERO into the RA register field.
887 // A zero immediate should always be loaded with a single li.
888 unsigned DefOpc = DefMI->getOpcode();
889 if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
891 if (!DefMI->getOperand(1).isImm())
893 if (DefMI->getOperand(1).getImm() != 0)
896 // Note that we cannot here invert the arguments of an isel in order to fold
897 // a ZERO into what is presented as the second argument. All we have here
898 // is the condition bit, and that might come from a CR-logical bit operation.
900 const MCInstrDesc &UseMCID = UseMI->getDesc();
902 // Only fold into real machine instructions.
903 if (UseMCID.isPseudo())
907 for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
908 if (UseMI->getOperand(UseIdx).isReg() &&
909 UseMI->getOperand(UseIdx).getReg() == Reg)
912 assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
913 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
915 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
917 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
918 // register (which might also be specified as a pointer class kind).
919 if (UseInfo->isLookupPtrRegClass()) {
920 if (UseInfo->RegClass /* Kind */ != 1)
923 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
924 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
928 // Make sure this is not tied to an output register (or otherwise
929 // constrained). This is true for ST?UX registers, for example, which
930 // are tied to their output registers.
931 if (UseInfo->Constraints != 0)
935 if (UseInfo->isLookupPtrRegClass()) {
936 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
937 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
939 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
940 PPC::ZERO8 : PPC::ZERO;
943 bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
944 UseMI->getOperand(UseIdx).setReg(ZeroReg);
947 DefMI->eraseFromParent();
952 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
953 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
955 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
960 // We should make sure that, if we're going to predicate both sides of a
961 // condition (a diamond), that both sides don't define the counter register. We
962 // can predicate counter-decrement-based branches, but while that predicates
963 // the branching, it does not predicate the counter decrement. If we tried to
964 // merge the triangle into one predicated block, we'd decrement the counter
966 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
967 unsigned NumT, unsigned ExtraT,
968 MachineBasicBlock &FMBB,
969 unsigned NumF, unsigned ExtraF,
970 const BranchProbability &Probability) const {
971 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
975 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
976 // The predicated branches are identified by their type, not really by the
977 // explicit presence of a predicate. Furthermore, some of them can be
978 // predicated more than once. Because if conversion won't try to predicate
979 // any instruction which already claims to be predicated (by returning true
980 // here), always return false. In doing so, we let isPredicable() be the
981 // final word on whether not the instruction can be (further) predicated.
986 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
987 if (!MI->isTerminator())
990 // Conditional branch is a special case.
991 if (MI->isBranch() && !MI->isBarrier())
994 return !isPredicated(MI);
997 bool PPCInstrInfo::PredicateInstruction(
999 const SmallVectorImpl<MachineOperand> &Pred) const {
1000 unsigned OpC = MI->getOpcode();
1001 if (OpC == PPC::BLR) {
1002 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1003 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1004 MI->setDesc(get(Pred[0].getImm() ?
1005 (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1006 (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR)));
1007 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1008 MI->setDesc(get(PPC::BCLR));
1009 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1010 .addReg(Pred[1].getReg());
1011 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1012 MI->setDesc(get(PPC::BCLRn));
1013 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1014 .addReg(Pred[1].getReg());
1016 MI->setDesc(get(PPC::BCCLR));
1017 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1018 .addImm(Pred[0].getImm())
1019 .addReg(Pred[1].getReg());
1023 } else if (OpC == PPC::B) {
1024 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1025 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1026 MI->setDesc(get(Pred[0].getImm() ?
1027 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1028 (isPPC64 ? PPC::BDZ8 : PPC::BDZ)));
1029 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1030 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1031 MI->RemoveOperand(0);
1033 MI->setDesc(get(PPC::BC));
1034 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1035 .addReg(Pred[1].getReg())
1037 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1038 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1039 MI->RemoveOperand(0);
1041 MI->setDesc(get(PPC::BCn));
1042 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1043 .addReg(Pred[1].getReg())
1046 MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1047 MI->RemoveOperand(0);
1049 MI->setDesc(get(PPC::BCC));
1050 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1051 .addImm(Pred[0].getImm())
1052 .addReg(Pred[1].getReg())
1057 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 ||
1058 OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1059 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1060 llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1062 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1063 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1065 if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1066 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1067 (setLR ? PPC::BCCTRL : PPC::BCCTR)));
1068 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1069 .addReg(Pred[1].getReg());
1071 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1072 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1073 (setLR ? PPC::BCCTRLn : PPC::BCCTRn)));
1074 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1075 .addReg(Pred[1].getReg());
1079 MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1080 (setLR ? PPC::BCCCTRL : PPC::BCCCTR)));
1081 MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1082 .addImm(Pred[0].getImm())
1083 .addReg(Pred[1].getReg());
1090 bool PPCInstrInfo::SubsumesPredicate(
1091 const SmallVectorImpl<MachineOperand> &Pred1,
1092 const SmallVectorImpl<MachineOperand> &Pred2) const {
1093 assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1094 assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1096 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1098 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1101 // P1 can only subsume P2 if they test the same condition register.
1102 if (Pred1[1].getReg() != Pred2[1].getReg())
1105 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1106 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1111 // Does P1 subsume P2, e.g. GE subsumes GT.
1112 if (P1 == PPC::PRED_LE &&
1113 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1115 if (P1 == PPC::PRED_GE &&
1116 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1122 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1123 std::vector<MachineOperand> &Pred) const {
1124 // Note: At the present time, the contents of Pred from this function is
1125 // unused by IfConversion. This implementation follows ARM by pushing the
1126 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1127 // predicate, instructions defining CTR or CTR8 are also included as
1128 // predicate-defining instructions.
1130 const TargetRegisterClass *RCs[] =
1131 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1132 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1135 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1136 const MachineOperand &MO = MI->getOperand(i);
1137 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1138 const TargetRegisterClass *RC = RCs[c];
1140 if (MO.isDef() && RC->contains(MO.getReg())) {
1144 } else if (MO.isRegMask()) {
1145 for (TargetRegisterClass::iterator I = RC->begin(),
1146 IE = RC->end(); I != IE; ++I)
1147 if (MO.clobbersPhysReg(*I)) {
1158 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1159 unsigned OpC = MI->getOpcode();
1173 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1174 unsigned &SrcReg, unsigned &SrcReg2,
1175 int &Mask, int &Value) const {
1176 unsigned Opc = MI->getOpcode();
1179 default: return false;
1184 SrcReg = MI->getOperand(1).getReg();
1186 Value = MI->getOperand(2).getImm();
1195 SrcReg = MI->getOperand(1).getReg();
1196 SrcReg2 = MI->getOperand(2).getReg();
1201 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1202 unsigned SrcReg, unsigned SrcReg2,
1203 int Mask, int Value,
1204 const MachineRegisterInfo *MRI) const {
1208 int OpC = CmpInstr->getOpcode();
1209 unsigned CRReg = CmpInstr->getOperand(0).getReg();
1211 // FP record forms set CR1 based on the execption status bits, not a
1212 // comparison with zero.
1213 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1216 // The record forms set the condition register based on a signed comparison
1217 // with zero (so says the ISA manual). This is not as straightforward as it
1218 // seems, however, because this is always a 64-bit comparison on PPC64, even
1219 // for instructions that are 32-bit in nature (like slw for example).
1220 // So, on PPC32, for unsigned comparisons, we can use the record forms only
1221 // for equality checks (as those don't depend on the sign). On PPC64,
1222 // we are restricted to equality for unsigned 64-bit comparisons and for
1223 // signed 32-bit comparisons the applicability is more restricted.
1224 bool isPPC64 = TM.getSubtargetImpl()->isPPC64();
1225 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW;
1226 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1227 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1229 // Get the unique definition of SrcReg.
1230 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1231 if (!MI) return false;
1232 int MIOpC = MI->getOpcode();
1234 bool equalityOnly = false;
1237 if (is32BitSignedCompare) {
1238 // We can perform this optimization only if MI is sign-extending.
1239 if (MIOpC == PPC::SRAW || MIOpC == PPC::SRAWo ||
1240 MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1241 MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1242 MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1243 MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1247 } else if (is32BitUnsignedCompare) {
1248 // We can perform this optimization, equality only, if MI is
1250 if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1251 MIOpC == PPC::SLW || MIOpC == PPC::SLWo ||
1252 MIOpC == PPC::SRW || MIOpC == PPC::SRWo) {
1254 equalityOnly = true;
1258 equalityOnly = is64BitUnsignedCompare;
1260 equalityOnly = is32BitUnsignedCompare;
1263 // We need to check the uses of the condition register in order to reject
1264 // non-equality comparisons.
1265 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1266 IE = MRI->use_end(); I != IE; ++I) {
1267 MachineInstr *UseMI = &*I;
1268 if (UseMI->getOpcode() == PPC::BCC) {
1269 unsigned Pred = UseMI->getOperand(0).getImm();
1270 if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1272 } else if (UseMI->getOpcode() == PPC::ISEL ||
1273 UseMI->getOpcode() == PPC::ISEL8) {
1274 unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1275 if (SubIdx != PPC::sub_eq)
1282 MachineBasicBlock::iterator I = CmpInstr;
1284 // Scan forward to find the first use of the compare.
1285 for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1287 bool FoundUse = false;
1288 for (MachineRegisterInfo::use_iterator J = MRI->use_begin(CRReg),
1289 JE = MRI->use_end(); J != JE; ++J)
1299 // There are two possible candidates which can be changed to set CR[01].
1300 // One is MI, the other is a SUB instruction.
1301 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1302 MachineInstr *Sub = NULL;
1304 // MI is not a candidate for CMPrr.
1306 // FIXME: Conservatively refuse to convert an instruction which isn't in the
1307 // same BB as the comparison. This is to allow the check below to avoid calls
1308 // (and other explicit clobbers); instead we should really check for these
1309 // more explicitly (in at least a few predecessors).
1310 else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1311 // PPC does not have a record-form SUBri.
1316 const TargetRegisterInfo *TRI = &getRegisterInfo();
1319 // Get ready to iterate backward from CmpInstr.
1320 MachineBasicBlock::iterator E = MI,
1321 B = CmpInstr->getParent()->begin();
1323 for (; I != E && !noSub; --I) {
1324 const MachineInstr &Instr = *I;
1325 unsigned IOpC = Instr.getOpcode();
1327 if (&*I != CmpInstr && (
1328 Instr.modifiesRegister(PPC::CR0, TRI) ||
1329 Instr.readsRegister(PPC::CR0, TRI)))
1330 // This instruction modifies or uses the record condition register after
1331 // the one we want to change. While we could do this transformation, it
1332 // would likely not be profitable. This transformation removes one
1333 // instruction, and so even forcing RA to generate one move probably
1334 // makes it unprofitable.
1337 // Check whether CmpInstr can be made redundant by the current instruction.
1338 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1339 OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1340 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1341 ((Instr.getOperand(1).getReg() == SrcReg &&
1342 Instr.getOperand(2).getReg() == SrcReg2) ||
1343 (Instr.getOperand(1).getReg() == SrcReg2 &&
1344 Instr.getOperand(2).getReg() == SrcReg))) {
1350 // The 'and' is below the comparison instruction.
1354 // Return false if no candidates exist.
1358 // The single candidate is called MI.
1362 MIOpC = MI->getOpcode();
1363 if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1366 NewOpC = PPC::getRecordFormOpcode(MIOpC);
1367 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1371 // FIXME: On the non-embedded POWER architectures, only some of the record
1372 // forms are fast, and we should use only the fast ones.
1374 // The defining instruction has a record form (or is already a record
1375 // form). It is possible, however, that we'll need to reverse the condition
1376 // code of the users.
1380 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1381 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1383 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1384 // needs to be updated to be based on SUB. Push the condition code
1385 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the
1386 // condition code of these operands will be modified.
1387 bool ShouldSwap = false;
1389 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1390 Sub->getOperand(2).getReg() == SrcReg;
1392 // The operands to subf are the opposite of sub, so only in the fixed-point
1393 // case, invert the order.
1394 ShouldSwap = !ShouldSwap;
1398 for (MachineRegisterInfo::use_iterator I = MRI->use_begin(CRReg),
1399 IE = MRI->use_end(); I != IE; ++I) {
1400 MachineInstr *UseMI = &*I;
1401 if (UseMI->getOpcode() == PPC::BCC) {
1402 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1403 assert((!equalityOnly ||
1404 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1405 "Invalid predicate for equality-only optimization");
1406 PredsToUpdate.push_back(std::make_pair(&((*I).getOperand(0)),
1407 PPC::getSwappedPredicate(Pred)));
1408 } else if (UseMI->getOpcode() == PPC::ISEL ||
1409 UseMI->getOpcode() == PPC::ISEL8) {
1410 unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1411 assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1412 "Invalid CR bit for equality-only optimization");
1414 if (NewSubReg == PPC::sub_lt)
1415 NewSubReg = PPC::sub_gt;
1416 else if (NewSubReg == PPC::sub_gt)
1417 NewSubReg = PPC::sub_lt;
1419 SubRegsToUpdate.push_back(std::make_pair(&((*I).getOperand(3)),
1421 } else // We need to abort on a user we don't understand.
1425 // Create a new virtual register to hold the value of the CR set by the
1426 // record-form instruction. If the instruction was not previously in
1427 // record form, then set the kill flag on the CR.
1428 CmpInstr->eraseFromParent();
1430 MachineBasicBlock::iterator MII = MI;
1431 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1432 get(TargetOpcode::COPY), CRReg)
1433 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1435 if (MIOpC != NewOpC) {
1436 // We need to be careful here: we're replacing one instruction with
1437 // another, and we need to make sure that we get all of the right
1438 // implicit uses and defs. On the other hand, the caller may be holding
1439 // an iterator to this instruction, and so we can't delete it (this is
1440 // specifically the case if this is the instruction directly after the
1443 const MCInstrDesc &NewDesc = get(NewOpC);
1444 MI->setDesc(NewDesc);
1446 if (NewDesc.ImplicitDefs)
1447 for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1448 *ImpDefs; ++ImpDefs)
1449 if (!MI->definesRegister(*ImpDefs))
1450 MI->addOperand(*MI->getParent()->getParent(),
1451 MachineOperand::CreateReg(*ImpDefs, true, true));
1452 if (NewDesc.ImplicitUses)
1453 for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1454 *ImpUses; ++ImpUses)
1455 if (!MI->readsRegister(*ImpUses))
1456 MI->addOperand(*MI->getParent()->getParent(),
1457 MachineOperand::CreateReg(*ImpUses, false, true));
1460 // Modify the condition code of operands in OperandsToUpdate.
1461 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1462 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1463 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1464 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1466 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1467 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1472 /// GetInstSize - Return the number of bytes of code the specified
1473 /// instruction may be. This returns the maximum number of bytes.
1475 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1476 unsigned Opcode = MI->getOpcode();
1478 if (Opcode == PPC::INLINEASM) {
1479 const MachineFunction *MF = MI->getParent()->getParent();
1480 const char *AsmStr = MI->getOperand(0).getSymbolName();
1481 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1483 const MCInstrDesc &Desc = get(Opcode);
1484 return Desc.getSize();
1489 #define DEBUG_TYPE "ppc-early-ret"
1490 STATISTIC(NumBCLR, "Number of early conditional returns");
1491 STATISTIC(NumBLR, "Number of early returns");
1494 void initializePPCEarlyReturnPass(PassRegistry&);
1498 // PPCEarlyReturn pass - For simple functions without epilogue code, move
1499 // returns up, and create conditional returns, to avoid unnecessary
1500 // branch-to-blr sequences.
1501 struct PPCEarlyReturn : public MachineFunctionPass {
1503 PPCEarlyReturn() : MachineFunctionPass(ID) {
1504 initializePPCEarlyReturnPass(*PassRegistry::getPassRegistry());
1507 const PPCTargetMachine *TM;
1508 const PPCInstrInfo *TII;
1511 bool processBlock(MachineBasicBlock &ReturnMBB) {
1512 bool Changed = false;
1514 MachineBasicBlock::iterator I = ReturnMBB.begin();
1515 I = ReturnMBB.SkipPHIsAndLabels(I);
1517 // The block must be essentially empty except for the blr.
1518 if (I == ReturnMBB.end() || I->getOpcode() != PPC::BLR ||
1519 I != ReturnMBB.getLastNonDebugInstr())
1522 SmallVector<MachineBasicBlock*, 8> PredToRemove;
1523 for (MachineBasicBlock::pred_iterator PI = ReturnMBB.pred_begin(),
1524 PIE = ReturnMBB.pred_end(); PI != PIE; ++PI) {
1525 bool OtherReference = false, BlockChanged = false;
1526 for (MachineBasicBlock::iterator J = (*PI)->getLastNonDebugInstr();;) {
1527 if (J->getOpcode() == PPC::B) {
1528 if (J->getOperand(0).getMBB() == &ReturnMBB) {
1529 // This is an unconditional branch to the return. Replace the
1530 // branch with a blr.
1531 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BLR));
1532 MachineBasicBlock::iterator K = J--;
1533 K->eraseFromParent();
1534 BlockChanged = true;
1538 } else if (J->getOpcode() == PPC::BCC) {
1539 if (J->getOperand(2).getMBB() == &ReturnMBB) {
1540 // This is a conditional branch to the return. Replace the branch
1542 BuildMI(**PI, J, J->getDebugLoc(), TII->get(PPC::BCCLR))
1543 .addImm(J->getOperand(0).getImm())
1544 .addReg(J->getOperand(1).getReg());
1545 MachineBasicBlock::iterator K = J--;
1546 K->eraseFromParent();
1547 BlockChanged = true;
1551 } else if (J->getOpcode() == PPC::BC || J->getOpcode() == PPC::BCn) {
1552 if (J->getOperand(1).getMBB() == &ReturnMBB) {
1553 // This is a conditional branch to the return. Replace the branch
1555 BuildMI(**PI, J, J->getDebugLoc(),
1556 TII->get(J->getOpcode() == PPC::BC ?
1557 PPC::BCLR : PPC::BCLRn))
1558 .addReg(J->getOperand(0).getReg());
1559 MachineBasicBlock::iterator K = J--;
1560 K->eraseFromParent();
1561 BlockChanged = true;
1565 } else if (J->isBranch()) {
1566 if (J->isIndirectBranch()) {
1567 if (ReturnMBB.hasAddressTaken())
1568 OtherReference = true;
1570 for (unsigned i = 0; i < J->getNumOperands(); ++i)
1571 if (J->getOperand(i).isMBB() &&
1572 J->getOperand(i).getMBB() == &ReturnMBB)
1573 OtherReference = true;
1574 } else if (!J->isTerminator() && !J->isDebugValue())
1577 if (J == (*PI)->begin())
1583 if ((*PI)->canFallThrough() && (*PI)->isLayoutSuccessor(&ReturnMBB))
1584 OtherReference = true;
1586 // Predecessors are stored in a vector and can't be removed here.
1587 if (!OtherReference && BlockChanged) {
1588 PredToRemove.push_back(*PI);
1595 for (unsigned i = 0, ie = PredToRemove.size(); i != ie; ++i)
1596 PredToRemove[i]->removeSuccessor(&ReturnMBB);
1598 if (Changed && !ReturnMBB.hasAddressTaken()) {
1599 // We now might be able to merge this blr-only block into its
1600 // by-layout predecessor.
1601 if (ReturnMBB.pred_size() == 1 &&
1602 (*ReturnMBB.pred_begin())->isLayoutSuccessor(&ReturnMBB)) {
1603 // Move the blr into the preceding block.
1604 MachineBasicBlock &PrevMBB = **ReturnMBB.pred_begin();
1605 PrevMBB.splice(PrevMBB.end(), &ReturnMBB, I);
1606 PrevMBB.removeSuccessor(&ReturnMBB);
1609 if (ReturnMBB.pred_empty())
1610 ReturnMBB.eraseFromParent();
1617 virtual bool runOnMachineFunction(MachineFunction &MF) {
1618 TM = static_cast<const PPCTargetMachine *>(&MF.getTarget());
1619 TII = TM->getInstrInfo();
1621 bool Changed = false;
1623 // If the function does not have at least two blocks, then there is
1628 for (MachineFunction::iterator I = MF.begin(); I != MF.end();) {
1629 MachineBasicBlock &B = *I++;
1630 if (processBlock(B))
1637 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1638 MachineFunctionPass::getAnalysisUsage(AU);
1643 INITIALIZE_PASS(PPCEarlyReturn, DEBUG_TYPE,
1644 "PowerPC Early-Return Creation", false, false)
1646 char PPCEarlyReturn::ID = 0;
1648 llvm::createPPCEarlyReturnPass() { return new PPCEarlyReturn(); }