[CodeGen] ArrayRef'ize cond/pred in various TII APIs. NFC.
[oota-llvm.git] / lib / Target / PowerPC / PPCInstrInfo.cpp
1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the PowerPC implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCInstrInfo.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCHazardRecognizers.h"
18 #include "PPCInstrBuilder.h"
19 #include "PPCMachineFunctionInfo.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineMemOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/PseudoSourceValue.h"
30 #include "llvm/CodeGen/ScheduleDAG.h"
31 #include "llvm/CodeGen/SlotIndexes.h"
32 #include "llvm/CodeGen/StackMaps.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCInst.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/TargetRegistry.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 #define DEBUG_TYPE "ppc-instr-info"
44
45 #define GET_INSTRMAP_INFO
46 #define GET_INSTRINFO_CTOR_DTOR
47 #include "PPCGenInstrInfo.inc"
48
49 static cl::
50 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden,
51             cl::desc("Disable analysis for CTR loops"));
52
53 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt",
54 cl::desc("Disable compare instruction optimization"), cl::Hidden);
55
56 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy",
57 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"),
58 cl::Hidden);
59
60 // Pin the vtable to this file.
61 void PPCInstrInfo::anchor() {}
62
63 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI)
64     : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
65       Subtarget(STI), RI(STI.getTargetMachine()) {}
66
67 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for
68 /// this target when scheduling the DAG.
69 ScheduleHazardRecognizer *
70 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI,
71                                            const ScheduleDAG *DAG) const {
72   unsigned Directive =
73       static_cast<const PPCSubtarget *>(STI)->getDarwinDirective();
74   if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 ||
75       Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) {
76     const InstrItineraryData *II =
77         static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData();
78     return new ScoreboardHazardRecognizer(II, DAG);
79   }
80
81   return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG);
82 }
83
84 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer
85 /// to use for this target when scheduling the DAG.
86 ScheduleHazardRecognizer *
87 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
88                                                  const ScheduleDAG *DAG) const {
89   unsigned Directive =
90       DAG->MF.getSubtarget<PPCSubtarget>().getDarwinDirective();
91
92   if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8)
93     return new PPCDispatchGroupSBHazardRecognizer(II, DAG);
94
95   // Most subtargets use a PPC970 recognizer.
96   if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 &&
97       Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) {
98     assert(DAG->TII && "No InstrInfo?");
99
100     return new PPCHazardRecognizer970(*DAG);
101   }
102
103   return new ScoreboardHazardRecognizer(II, DAG);
104 }
105
106
107 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
108                                     const MachineInstr *DefMI, unsigned DefIdx,
109                                     const MachineInstr *UseMI,
110                                     unsigned UseIdx) const {
111   int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx,
112                                                    UseMI, UseIdx);
113
114   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
115   unsigned Reg = DefMO.getReg();
116
117   bool IsRegCR;
118   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
119     const MachineRegisterInfo *MRI =
120       &DefMI->getParent()->getParent()->getRegInfo();
121     IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) ||
122               MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass);
123   } else {
124     IsRegCR = PPC::CRRCRegClass.contains(Reg) ||
125               PPC::CRBITRCRegClass.contains(Reg);
126   }
127
128   if (UseMI->isBranch() && IsRegCR) {
129     if (Latency < 0)
130       Latency = getInstrLatency(ItinData, DefMI);
131
132     // On some cores, there is an additional delay between writing to a condition
133     // register, and using it from a branch.
134     unsigned Directive = Subtarget.getDarwinDirective();
135     switch (Directive) {
136     default: break;
137     case PPC::DIR_7400:
138     case PPC::DIR_750:
139     case PPC::DIR_970:
140     case PPC::DIR_E5500:
141     case PPC::DIR_PWR4:
142     case PPC::DIR_PWR5:
143     case PPC::DIR_PWR5X:
144     case PPC::DIR_PWR6:
145     case PPC::DIR_PWR6X:
146     case PPC::DIR_PWR7:
147     case PPC::DIR_PWR8:
148       Latency += 2;
149       break;
150     }
151   }
152
153   return Latency;
154 }
155
156 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register.
157 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
158                                          unsigned &SrcReg, unsigned &DstReg,
159                                          unsigned &SubIdx) const {
160   switch (MI.getOpcode()) {
161   default: return false;
162   case PPC::EXTSW:
163   case PPC::EXTSW_32_64:
164     SrcReg = MI.getOperand(1).getReg();
165     DstReg = MI.getOperand(0).getReg();
166     SubIdx = PPC::sub_32;
167     return true;
168   }
169 }
170
171 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
172                                            int &FrameIndex) const {
173   // Note: This list must be kept consistent with LoadRegFromStackSlot.
174   switch (MI->getOpcode()) {
175   default: break;
176   case PPC::LD:
177   case PPC::LWZ:
178   case PPC::LFS:
179   case PPC::LFD:
180   case PPC::RESTORE_CR:
181   case PPC::RESTORE_CRBIT:
182   case PPC::LVX:
183   case PPC::LXVD2X:
184   case PPC::QVLFDX:
185   case PPC::QVLFSXs:
186   case PPC::QVLFDXb:
187   case PPC::RESTORE_VRSAVE:
188     // Check for the operands added by addFrameReference (the immediate is the
189     // offset which defaults to 0).
190     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
191         MI->getOperand(2).isFI()) {
192       FrameIndex = MI->getOperand(2).getIndex();
193       return MI->getOperand(0).getReg();
194     }
195     break;
196   }
197   return 0;
198 }
199
200 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
201                                           int &FrameIndex) const {
202   // Note: This list must be kept consistent with StoreRegToStackSlot.
203   switch (MI->getOpcode()) {
204   default: break;
205   case PPC::STD:
206   case PPC::STW:
207   case PPC::STFS:
208   case PPC::STFD:
209   case PPC::SPILL_CR:
210   case PPC::SPILL_CRBIT:
211   case PPC::STVX:
212   case PPC::STXVD2X:
213   case PPC::QVSTFDX:
214   case PPC::QVSTFSXs:
215   case PPC::QVSTFDXb:
216   case PPC::SPILL_VRSAVE:
217     // Check for the operands added by addFrameReference (the immediate is the
218     // offset which defaults to 0).
219     if (MI->getOperand(1).isImm() && !MI->getOperand(1).getImm() &&
220         MI->getOperand(2).isFI()) {
221       FrameIndex = MI->getOperand(2).getIndex();
222       return MI->getOperand(0).getReg();
223     }
224     break;
225   }
226   return 0;
227 }
228
229 // commuteInstruction - We can commute rlwimi instructions, but only if the
230 // rotate amt is zero.  We also have to munge the immediates a bit.
231 MachineInstr *
232 PPCInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
233   MachineFunction &MF = *MI->getParent()->getParent();
234
235   // Normal instructions can be commuted the obvious way.
236   if (MI->getOpcode() != PPC::RLWIMI &&
237       MI->getOpcode() != PPC::RLWIMIo)
238     return TargetInstrInfo::commuteInstruction(MI, NewMI);
239   // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a
240   // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because
241   // changing the relative order of the mask operands might change what happens
242   // to the high-bits of the mask (and, thus, the result).
243
244   // Cannot commute if it has a non-zero rotate count.
245   if (MI->getOperand(3).getImm() != 0)
246     return nullptr;
247
248   // If we have a zero rotate count, we have:
249   //   M = mask(MB,ME)
250   //   Op0 = (Op1 & ~M) | (Op2 & M)
251   // Change this to:
252   //   M = mask((ME+1)&31, (MB-1)&31)
253   //   Op0 = (Op2 & ~M) | (Op1 & M)
254
255   // Swap op1/op2
256   unsigned Reg0 = MI->getOperand(0).getReg();
257   unsigned Reg1 = MI->getOperand(1).getReg();
258   unsigned Reg2 = MI->getOperand(2).getReg();
259   unsigned SubReg1 = MI->getOperand(1).getSubReg();
260   unsigned SubReg2 = MI->getOperand(2).getSubReg();
261   bool Reg1IsKill = MI->getOperand(1).isKill();
262   bool Reg2IsKill = MI->getOperand(2).isKill();
263   bool ChangeReg0 = false;
264   // If machine instrs are no longer in two-address forms, update
265   // destination register as well.
266   if (Reg0 == Reg1) {
267     // Must be two address instruction!
268     assert(MI->getDesc().getOperandConstraint(0, MCOI::TIED_TO) &&
269            "Expecting a two-address instruction!");
270     assert(MI->getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch");
271     Reg2IsKill = false;
272     ChangeReg0 = true;
273   }
274
275   // Masks.
276   unsigned MB = MI->getOperand(4).getImm();
277   unsigned ME = MI->getOperand(5).getImm();
278
279   if (NewMI) {
280     // Create a new instruction.
281     unsigned Reg0 = ChangeReg0 ? Reg2 : MI->getOperand(0).getReg();
282     bool Reg0IsDead = MI->getOperand(0).isDead();
283     return BuildMI(MF, MI->getDebugLoc(), MI->getDesc())
284       .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead))
285       .addReg(Reg2, getKillRegState(Reg2IsKill))
286       .addReg(Reg1, getKillRegState(Reg1IsKill))
287       .addImm((ME+1) & 31)
288       .addImm((MB-1) & 31);
289   }
290
291   if (ChangeReg0) {
292     MI->getOperand(0).setReg(Reg2);
293     MI->getOperand(0).setSubReg(SubReg2);
294   }
295   MI->getOperand(2).setReg(Reg1);
296   MI->getOperand(1).setReg(Reg2);
297   MI->getOperand(2).setSubReg(SubReg1);
298   MI->getOperand(1).setSubReg(SubReg2);
299   MI->getOperand(2).setIsKill(Reg1IsKill);
300   MI->getOperand(1).setIsKill(Reg2IsKill);
301
302   // Swap the mask around.
303   MI->getOperand(4).setImm((ME+1) & 31);
304   MI->getOperand(5).setImm((MB-1) & 31);
305   return MI;
306 }
307
308 bool PPCInstrInfo::findCommutedOpIndices(MachineInstr *MI, unsigned &SrcOpIdx1,
309                                          unsigned &SrcOpIdx2) const {
310   // For VSX A-Type FMA instructions, it is the first two operands that can be
311   // commuted, however, because the non-encoded tied input operand is listed
312   // first, the operands to swap are actually the second and third.
313
314   int AltOpc = PPC::getAltVSXFMAOpcode(MI->getOpcode());
315   if (AltOpc == -1)
316     return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
317
318   SrcOpIdx1 = 2;
319   SrcOpIdx2 = 3;
320   return true;
321 }
322
323 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB,
324                               MachineBasicBlock::iterator MI) const {
325   // This function is used for scheduling, and the nop wanted here is the type
326   // that terminates dispatch groups on the POWER cores.
327   unsigned Directive = Subtarget.getDarwinDirective();
328   unsigned Opcode;
329   switch (Directive) {
330   default:            Opcode = PPC::NOP; break;
331   case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break;
332   case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break;
333   case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */
334   }
335
336   DebugLoc DL;
337   BuildMI(MBB, MI, DL, get(Opcode));
338 }
339
340 /// getNoopForMachoTarget - Return the noop instruction to use for a noop.
341 void PPCInstrInfo::getNoopForMachoTarget(MCInst &NopInst) const {
342   NopInst.setOpcode(PPC::NOP);
343 }
344
345 // Branch analysis.
346 // Note: If the condition register is set to CTR or CTR8 then this is a
347 // BDNZ (imm == 1) or BDZ (imm == 0) branch.
348 bool PPCInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
349                                  MachineBasicBlock *&FBB,
350                                  SmallVectorImpl<MachineOperand> &Cond,
351                                  bool AllowModify) const {
352   bool isPPC64 = Subtarget.isPPC64();
353
354   // If the block has no terminators, it just falls into the block after it.
355   MachineBasicBlock::iterator I = MBB.end();
356   if (I == MBB.begin())
357     return false;
358   --I;
359   while (I->isDebugValue()) {
360     if (I == MBB.begin())
361       return false;
362     --I;
363   }
364   if (!isUnpredicatedTerminator(I))
365     return false;
366
367   // Get the last instruction in the block.
368   MachineInstr *LastInst = I;
369
370   // If there is only one terminator instruction, process it.
371   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
372     if (LastInst->getOpcode() == PPC::B) {
373       if (!LastInst->getOperand(0).isMBB())
374         return true;
375       TBB = LastInst->getOperand(0).getMBB();
376       return false;
377     } else if (LastInst->getOpcode() == PPC::BCC) {
378       if (!LastInst->getOperand(2).isMBB())
379         return true;
380       // Block ends with fall-through condbranch.
381       TBB = LastInst->getOperand(2).getMBB();
382       Cond.push_back(LastInst->getOperand(0));
383       Cond.push_back(LastInst->getOperand(1));
384       return false;
385     } else if (LastInst->getOpcode() == PPC::BC) {
386       if (!LastInst->getOperand(1).isMBB())
387         return true;
388       // Block ends with fall-through condbranch.
389       TBB = LastInst->getOperand(1).getMBB();
390       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
391       Cond.push_back(LastInst->getOperand(0));
392       return false;
393     } else if (LastInst->getOpcode() == PPC::BCn) {
394       if (!LastInst->getOperand(1).isMBB())
395         return true;
396       // Block ends with fall-through condbranch.
397       TBB = LastInst->getOperand(1).getMBB();
398       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
399       Cond.push_back(LastInst->getOperand(0));
400       return false;
401     } else if (LastInst->getOpcode() == PPC::BDNZ8 ||
402                LastInst->getOpcode() == PPC::BDNZ) {
403       if (!LastInst->getOperand(0).isMBB())
404         return true;
405       if (DisableCTRLoopAnal)
406         return true;
407       TBB = LastInst->getOperand(0).getMBB();
408       Cond.push_back(MachineOperand::CreateImm(1));
409       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
410                                                true));
411       return false;
412     } else if (LastInst->getOpcode() == PPC::BDZ8 ||
413                LastInst->getOpcode() == PPC::BDZ) {
414       if (!LastInst->getOperand(0).isMBB())
415         return true;
416       if (DisableCTRLoopAnal)
417         return true;
418       TBB = LastInst->getOperand(0).getMBB();
419       Cond.push_back(MachineOperand::CreateImm(0));
420       Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
421                                                true));
422       return false;
423     }
424
425     // Otherwise, don't know what this is.
426     return true;
427   }
428
429   // Get the instruction before it if it's a terminator.
430   MachineInstr *SecondLastInst = I;
431
432   // If there are three terminators, we don't know what sort of block this is.
433   if (SecondLastInst && I != MBB.begin() &&
434       isUnpredicatedTerminator(--I))
435     return true;
436
437   // If the block ends with PPC::B and PPC:BCC, handle it.
438   if (SecondLastInst->getOpcode() == PPC::BCC &&
439       LastInst->getOpcode() == PPC::B) {
440     if (!SecondLastInst->getOperand(2).isMBB() ||
441         !LastInst->getOperand(0).isMBB())
442       return true;
443     TBB =  SecondLastInst->getOperand(2).getMBB();
444     Cond.push_back(SecondLastInst->getOperand(0));
445     Cond.push_back(SecondLastInst->getOperand(1));
446     FBB = LastInst->getOperand(0).getMBB();
447     return false;
448   } else if (SecondLastInst->getOpcode() == PPC::BC &&
449       LastInst->getOpcode() == PPC::B) {
450     if (!SecondLastInst->getOperand(1).isMBB() ||
451         !LastInst->getOperand(0).isMBB())
452       return true;
453     TBB =  SecondLastInst->getOperand(1).getMBB();
454     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
455     Cond.push_back(SecondLastInst->getOperand(0));
456     FBB = LastInst->getOperand(0).getMBB();
457     return false;
458   } else if (SecondLastInst->getOpcode() == PPC::BCn &&
459       LastInst->getOpcode() == PPC::B) {
460     if (!SecondLastInst->getOperand(1).isMBB() ||
461         !LastInst->getOperand(0).isMBB())
462       return true;
463     TBB =  SecondLastInst->getOperand(1).getMBB();
464     Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET));
465     Cond.push_back(SecondLastInst->getOperand(0));
466     FBB = LastInst->getOperand(0).getMBB();
467     return false;
468   } else if ((SecondLastInst->getOpcode() == PPC::BDNZ8 ||
469               SecondLastInst->getOpcode() == PPC::BDNZ) &&
470       LastInst->getOpcode() == PPC::B) {
471     if (!SecondLastInst->getOperand(0).isMBB() ||
472         !LastInst->getOperand(0).isMBB())
473       return true;
474     if (DisableCTRLoopAnal)
475       return true;
476     TBB = SecondLastInst->getOperand(0).getMBB();
477     Cond.push_back(MachineOperand::CreateImm(1));
478     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
479                                              true));
480     FBB = LastInst->getOperand(0).getMBB();
481     return false;
482   } else if ((SecondLastInst->getOpcode() == PPC::BDZ8 ||
483               SecondLastInst->getOpcode() == PPC::BDZ) &&
484       LastInst->getOpcode() == PPC::B) {
485     if (!SecondLastInst->getOperand(0).isMBB() ||
486         !LastInst->getOperand(0).isMBB())
487       return true;
488     if (DisableCTRLoopAnal)
489       return true;
490     TBB = SecondLastInst->getOperand(0).getMBB();
491     Cond.push_back(MachineOperand::CreateImm(0));
492     Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR,
493                                              true));
494     FBB = LastInst->getOperand(0).getMBB();
495     return false;
496   }
497
498   // If the block ends with two PPC:Bs, handle it.  The second one is not
499   // executed, so remove it.
500   if (SecondLastInst->getOpcode() == PPC::B &&
501       LastInst->getOpcode() == PPC::B) {
502     if (!SecondLastInst->getOperand(0).isMBB())
503       return true;
504     TBB = SecondLastInst->getOperand(0).getMBB();
505     I = LastInst;
506     if (AllowModify)
507       I->eraseFromParent();
508     return false;
509   }
510
511   // Otherwise, can't handle this.
512   return true;
513 }
514
515 unsigned PPCInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
516   MachineBasicBlock::iterator I = MBB.end();
517   if (I == MBB.begin()) return 0;
518   --I;
519   while (I->isDebugValue()) {
520     if (I == MBB.begin())
521       return 0;
522     --I;
523   }
524   if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC &&
525       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
526       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
527       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
528     return 0;
529
530   // Remove the branch.
531   I->eraseFromParent();
532
533   I = MBB.end();
534
535   if (I == MBB.begin()) return 1;
536   --I;
537   if (I->getOpcode() != PPC::BCC &&
538       I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn &&
539       I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ &&
540       I->getOpcode() != PPC::BDZ8  && I->getOpcode() != PPC::BDZ)
541     return 1;
542
543   // Remove the branch.
544   I->eraseFromParent();
545   return 2;
546 }
547
548 unsigned
549 PPCInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
550                            MachineBasicBlock *FBB,
551                            ArrayRef<MachineOperand> Cond,
552                            DebugLoc DL) const {
553   // Shouldn't be a fall through.
554   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
555   assert((Cond.size() == 2 || Cond.size() == 0) &&
556          "PPC branch conditions have two components!");
557
558   bool isPPC64 = Subtarget.isPPC64();
559
560   // One-way branch.
561   if (!FBB) {
562     if (Cond.empty())   // Unconditional branch
563       BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB);
564     else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
565       BuildMI(&MBB, DL, get(Cond[0].getImm() ?
566                               (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
567                               (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
568     else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
569       BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
570     else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
571       BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
572     else                // Conditional branch
573       BuildMI(&MBB, DL, get(PPC::BCC))
574         .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
575     return 1;
576   }
577
578   // Two-way Conditional Branch.
579   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
580     BuildMI(&MBB, DL, get(Cond[0].getImm() ?
581                             (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
582                             (isPPC64 ? PPC::BDZ8  : PPC::BDZ))).addMBB(TBB);
583   else if (Cond[0].getImm() == PPC::PRED_BIT_SET)
584     BuildMI(&MBB, DL, get(PPC::BC)).addOperand(Cond[1]).addMBB(TBB);
585   else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET)
586     BuildMI(&MBB, DL, get(PPC::BCn)).addOperand(Cond[1]).addMBB(TBB);
587   else
588     BuildMI(&MBB, DL, get(PPC::BCC))
589       .addImm(Cond[0].getImm()).addOperand(Cond[1]).addMBB(TBB);
590   BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB);
591   return 2;
592 }
593
594 // Select analysis.
595 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
596                 ArrayRef<MachineOperand> Cond,
597                 unsigned TrueReg, unsigned FalseReg,
598                 int &CondCycles, int &TrueCycles, int &FalseCycles) const {
599   if (!Subtarget.hasISEL())
600     return false;
601
602   if (Cond.size() != 2)
603     return false;
604
605   // If this is really a bdnz-like condition, then it cannot be turned into a
606   // select.
607   if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8)
608     return false;
609
610   // Check register classes.
611   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
612   const TargetRegisterClass *RC =
613     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
614   if (!RC)
615     return false;
616
617   // isel is for regular integer GPRs only.
618   if (!PPC::GPRCRegClass.hasSubClassEq(RC) &&
619       !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) &&
620       !PPC::G8RCRegClass.hasSubClassEq(RC) &&
621       !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC))
622     return false;
623
624   // FIXME: These numbers are for the A2, how well they work for other cores is
625   // an open question. On the A2, the isel instruction has a 2-cycle latency
626   // but single-cycle throughput. These numbers are used in combination with
627   // the MispredictPenalty setting from the active SchedMachineModel.
628   CondCycles = 1;
629   TrueCycles = 1;
630   FalseCycles = 1;
631
632   return true;
633 }
634
635 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB,
636                                 MachineBasicBlock::iterator MI, DebugLoc dl,
637                                 unsigned DestReg, ArrayRef<MachineOperand> Cond,
638                                 unsigned TrueReg, unsigned FalseReg) const {
639   assert(Cond.size() == 2 &&
640          "PPC branch conditions have two components!");
641
642   assert(Subtarget.hasISEL() &&
643          "Cannot insert select on target without ISEL support");
644
645   // Get the register classes.
646   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
647   const TargetRegisterClass *RC =
648     RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
649   assert(RC && "TrueReg and FalseReg must have overlapping register classes");
650
651   bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) ||
652                  PPC::G8RC_NOX0RegClass.hasSubClassEq(RC);
653   assert((Is64Bit ||
654           PPC::GPRCRegClass.hasSubClassEq(RC) ||
655           PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) &&
656          "isel is for regular integer GPRs only");
657
658   unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL;
659   unsigned SelectPred = Cond[0].getImm();
660
661   unsigned SubIdx;
662   bool SwapOps;
663   switch (SelectPred) {
664   default: llvm_unreachable("invalid predicate for isel");
665   case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
666   case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
667   case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
668   case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
669   case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
670   case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
671   case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
672   case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
673   case PPC::PRED_BIT_SET:   SubIdx = 0; SwapOps = false; break;
674   case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break;
675   }
676
677   unsigned FirstReg =  SwapOps ? FalseReg : TrueReg,
678            SecondReg = SwapOps ? TrueReg  : FalseReg;
679
680   // The first input register of isel cannot be r0. If it is a member
681   // of a register class that can be r0, then copy it first (the
682   // register allocator should eliminate the copy).
683   if (MRI.getRegClass(FirstReg)->contains(PPC::R0) ||
684       MRI.getRegClass(FirstReg)->contains(PPC::X0)) {
685     const TargetRegisterClass *FirstRC =
686       MRI.getRegClass(FirstReg)->contains(PPC::X0) ?
687         &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass;
688     unsigned OldFirstReg = FirstReg;
689     FirstReg = MRI.createVirtualRegister(FirstRC);
690     BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg)
691       .addReg(OldFirstReg);
692   }
693
694   BuildMI(MBB, MI, dl, get(OpCode), DestReg)
695     .addReg(FirstReg).addReg(SecondReg)
696     .addReg(Cond[1].getReg(), 0, SubIdx);
697 }
698
699 static unsigned getCRBitValue(unsigned CRBit) {
700   unsigned Ret = 4;
701   if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT ||
702       CRBit == PPC::CR2LT || CRBit == PPC::CR3LT ||
703       CRBit == PPC::CR4LT || CRBit == PPC::CR5LT ||
704       CRBit == PPC::CR6LT || CRBit == PPC::CR7LT)
705     Ret = 3;
706   if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT ||
707       CRBit == PPC::CR2GT || CRBit == PPC::CR3GT ||
708       CRBit == PPC::CR4GT || CRBit == PPC::CR5GT ||
709       CRBit == PPC::CR6GT || CRBit == PPC::CR7GT)
710     Ret = 2;
711   if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ ||
712       CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ ||
713       CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ ||
714       CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ)
715     Ret = 1;
716   if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN ||
717       CRBit == PPC::CR2UN || CRBit == PPC::CR3UN ||
718       CRBit == PPC::CR4UN || CRBit == PPC::CR5UN ||
719       CRBit == PPC::CR6UN || CRBit == PPC::CR7UN)
720     Ret = 0;
721
722   assert(Ret != 4 && "Invalid CR bit register");
723   return Ret;
724 }
725
726 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
727                                MachineBasicBlock::iterator I, DebugLoc DL,
728                                unsigned DestReg, unsigned SrcReg,
729                                bool KillSrc) const {
730   // We can end up with self copies and similar things as a result of VSX copy
731   // legalization. Promote them here.
732   const TargetRegisterInfo *TRI = &getRegisterInfo();
733   if (PPC::F8RCRegClass.contains(DestReg) &&
734       PPC::VSRCRegClass.contains(SrcReg)) {
735     unsigned SuperReg =
736       TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass);
737
738     if (VSXSelfCopyCrash && SrcReg == SuperReg)
739       llvm_unreachable("nop VSX copy");
740
741     DestReg = SuperReg;
742   } else if (PPC::VRRCRegClass.contains(DestReg) &&
743              PPC::VSRCRegClass.contains(SrcReg)) {
744     unsigned SuperReg =
745       TRI->getMatchingSuperReg(DestReg, PPC::sub_128, &PPC::VSRCRegClass);
746
747     if (VSXSelfCopyCrash && SrcReg == SuperReg)
748       llvm_unreachable("nop VSX copy");
749
750     DestReg = SuperReg;
751   } else if (PPC::F8RCRegClass.contains(SrcReg) &&
752              PPC::VSRCRegClass.contains(DestReg)) {
753     unsigned SuperReg =
754       TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass);
755
756     if (VSXSelfCopyCrash && DestReg == SuperReg)
757       llvm_unreachable("nop VSX copy");
758
759     SrcReg = SuperReg;
760   } else if (PPC::VRRCRegClass.contains(SrcReg) &&
761              PPC::VSRCRegClass.contains(DestReg)) {
762     unsigned SuperReg =
763       TRI->getMatchingSuperReg(SrcReg, PPC::sub_128, &PPC::VSRCRegClass);
764
765     if (VSXSelfCopyCrash && DestReg == SuperReg)
766       llvm_unreachable("nop VSX copy");
767
768     SrcReg = SuperReg;
769   }
770
771   // Different class register copy
772   if (PPC::CRBITRCRegClass.contains(SrcReg) &&
773       PPC::GPRCRegClass.contains(DestReg)) {
774     unsigned CRReg = getCRFromCRBit(SrcReg);
775     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
776        .addReg(CRReg), getKillRegState(KillSrc);
777     // Rotate the CR bit in the CR fields to be the least significant bit and
778     // then mask with 0x1 (MB = ME = 31).
779     BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg)
780        .addReg(DestReg, RegState::Kill)
781        .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg)))
782        .addImm(31)
783        .addImm(31);
784     return;
785   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
786       PPC::G8RCRegClass.contains(DestReg)) {
787     BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg)
788        .addReg(SrcReg), getKillRegState(KillSrc);
789     return;
790   } else if (PPC::CRRCRegClass.contains(SrcReg) &&
791       PPC::GPRCRegClass.contains(DestReg)) {
792     BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg)
793        .addReg(SrcReg), getKillRegState(KillSrc);
794     return;
795    }
796
797   unsigned Opc;
798   if (PPC::GPRCRegClass.contains(DestReg, SrcReg))
799     Opc = PPC::OR;
800   else if (PPC::G8RCRegClass.contains(DestReg, SrcReg))
801     Opc = PPC::OR8;
802   else if (PPC::F4RCRegClass.contains(DestReg, SrcReg))
803     Opc = PPC::FMR;
804   else if (PPC::CRRCRegClass.contains(DestReg, SrcReg))
805     Opc = PPC::MCRF;
806   else if (PPC::VRRCRegClass.contains(DestReg, SrcReg))
807     Opc = PPC::VOR;
808   else if (PPC::VSRCRegClass.contains(DestReg, SrcReg))
809     // There are two different ways this can be done:
810     //   1. xxlor : This has lower latency (on the P7), 2 cycles, but can only
811     //      issue in VSU pipeline 0.
812     //   2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but
813     //      can go to either pipeline.
814     // We'll always use xxlor here, because in practically all cases where
815     // copies are generated, they are close enough to some use that the
816     // lower-latency form is preferable.
817     Opc = PPC::XXLOR;
818   else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) ||
819            PPC::VSSRCRegClass.contains(DestReg, SrcReg))
820     Opc = PPC::XXLORf;
821   else if (PPC::QFRCRegClass.contains(DestReg, SrcReg))
822     Opc = PPC::QVFMR;
823   else if (PPC::QSRCRegClass.contains(DestReg, SrcReg))
824     Opc = PPC::QVFMRs;
825   else if (PPC::QBRCRegClass.contains(DestReg, SrcReg))
826     Opc = PPC::QVFMRb;
827   else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg))
828     Opc = PPC::CROR;
829   else
830     llvm_unreachable("Impossible reg-to-reg copy");
831
832   const MCInstrDesc &MCID = get(Opc);
833   if (MCID.getNumOperands() == 3)
834     BuildMI(MBB, I, DL, MCID, DestReg)
835       .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc));
836   else
837     BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc));
838 }
839
840 // This function returns true if a CR spill is necessary and false otherwise.
841 bool
842 PPCInstrInfo::StoreRegToStackSlot(MachineFunction &MF,
843                                   unsigned SrcReg, bool isKill,
844                                   int FrameIdx,
845                                   const TargetRegisterClass *RC,
846                                   SmallVectorImpl<MachineInstr*> &NewMIs,
847                                   bool &NonRI, bool &SpillsVRS) const{
848   // Note: If additional store instructions are added here,
849   // update isStoreToStackSlot.
850
851   DebugLoc DL;
852   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
853       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
854     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STW))
855                                        .addReg(SrcReg,
856                                                getKillRegState(isKill)),
857                                        FrameIdx));
858   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
859              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
860     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STD))
861                                        .addReg(SrcReg,
862                                                getKillRegState(isKill)),
863                                        FrameIdx));
864   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
865     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFD))
866                                        .addReg(SrcReg,
867                                                getKillRegState(isKill)),
868                                        FrameIdx));
869   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
870     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STFS))
871                                        .addReg(SrcReg,
872                                                getKillRegState(isKill)),
873                                        FrameIdx));
874   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
875     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CR))
876                                        .addReg(SrcReg,
877                                                getKillRegState(isKill)),
878                                        FrameIdx));
879     return true;
880   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
881     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_CRBIT))
882                                        .addReg(SrcReg,
883                                                getKillRegState(isKill)),
884                                        FrameIdx));
885     return true;
886   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
887     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STVX))
888                                        .addReg(SrcReg,
889                                                getKillRegState(isKill)),
890                                        FrameIdx));
891     NonRI = true;
892   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
893     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXVD2X))
894                                        .addReg(SrcReg,
895                                                getKillRegState(isKill)),
896                                        FrameIdx));
897     NonRI = true;
898   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
899     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSDX))
900                                        .addReg(SrcReg,
901                                                getKillRegState(isKill)),
902                                        FrameIdx));
903     NonRI = true;
904   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
905     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::STXSSPX))
906                                        .addReg(SrcReg,
907                                                getKillRegState(isKill)),
908                                        FrameIdx));
909     NonRI = true;
910   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
911     assert(Subtarget.isDarwin() &&
912            "VRSAVE only needs spill/restore on Darwin");
913     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::SPILL_VRSAVE))
914                                        .addReg(SrcReg,
915                                                getKillRegState(isKill)),
916                                        FrameIdx));
917     SpillsVRS = true;
918   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
919     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDX))
920                                        .addReg(SrcReg,
921                                                getKillRegState(isKill)),
922                                        FrameIdx));
923     NonRI = true;
924   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
925     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFSXs))
926                                        .addReg(SrcReg,
927                                                getKillRegState(isKill)),
928                                        FrameIdx));
929     NonRI = true;
930   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
931     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVSTFDXb))
932                                        .addReg(SrcReg,
933                                                getKillRegState(isKill)),
934                                        FrameIdx));
935     NonRI = true;
936   } else {
937     llvm_unreachable("Unknown regclass!");
938   }
939
940   return false;
941 }
942
943 void
944 PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
945                                   MachineBasicBlock::iterator MI,
946                                   unsigned SrcReg, bool isKill, int FrameIdx,
947                                   const TargetRegisterClass *RC,
948                                   const TargetRegisterInfo *TRI) const {
949   MachineFunction &MF = *MBB.getParent();
950   SmallVector<MachineInstr*, 4> NewMIs;
951
952   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
953   FuncInfo->setHasSpills();
954
955   bool NonRI = false, SpillsVRS = false;
956   if (StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs,
957                           NonRI, SpillsVRS))
958     FuncInfo->setSpillsCR();
959
960   if (SpillsVRS)
961     FuncInfo->setSpillsVRSAVE();
962
963   if (NonRI)
964     FuncInfo->setHasNonRISpills();
965
966   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
967     MBB.insert(MI, NewMIs[i]);
968
969   const MachineFrameInfo &MFI = *MF.getFrameInfo();
970   MachineMemOperand *MMO =
971     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
972                             MachineMemOperand::MOStore,
973                             MFI.getObjectSize(FrameIdx),
974                             MFI.getObjectAlignment(FrameIdx));
975   NewMIs.back()->addMemOperand(MF, MMO);
976 }
977
978 bool
979 PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, DebugLoc DL,
980                                    unsigned DestReg, int FrameIdx,
981                                    const TargetRegisterClass *RC,
982                                    SmallVectorImpl<MachineInstr*> &NewMIs,
983                                    bool &NonRI, bool &SpillsVRS) const{
984   // Note: If additional load instructions are added here,
985   // update isLoadFromStackSlot.
986
987   if (PPC::GPRCRegClass.hasSubClassEq(RC) ||
988       PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) {
989     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LWZ),
990                                                DestReg), FrameIdx));
991   } else if (PPC::G8RCRegClass.hasSubClassEq(RC) ||
992              PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) {
993     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LD), DestReg),
994                                        FrameIdx));
995   } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) {
996     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFD), DestReg),
997                                        FrameIdx));
998   } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) {
999     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LFS), DestReg),
1000                                        FrameIdx));
1001   } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) {
1002     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1003                                                get(PPC::RESTORE_CR), DestReg),
1004                                        FrameIdx));
1005     return true;
1006   } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) {
1007     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1008                                                get(PPC::RESTORE_CRBIT), DestReg),
1009                                        FrameIdx));
1010     return true;
1011   } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) {
1012     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LVX), DestReg),
1013                                        FrameIdx));
1014     NonRI = true;
1015   } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) {
1016     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXVD2X), DestReg),
1017                                        FrameIdx));
1018     NonRI = true;
1019   } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) {
1020     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSDX), DestReg),
1021                                        FrameIdx));
1022     NonRI = true;
1023   } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) {
1024     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::LXSSPX), DestReg),
1025                                        FrameIdx));
1026     NonRI = true;
1027   } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) {
1028     assert(Subtarget.isDarwin() &&
1029            "VRSAVE only needs spill/restore on Darwin");
1030     NewMIs.push_back(addFrameReference(BuildMI(MF, DL,
1031                                                get(PPC::RESTORE_VRSAVE),
1032                                                DestReg),
1033                                        FrameIdx));
1034     SpillsVRS = true;
1035   } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) {
1036     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDX), DestReg),
1037                                        FrameIdx));
1038     NonRI = true;
1039   } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) {
1040     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFSXs), DestReg),
1041                                        FrameIdx));
1042     NonRI = true;
1043   } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) {
1044     NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(PPC::QVLFDXb), DestReg),
1045                                        FrameIdx));
1046     NonRI = true;
1047   } else {
1048     llvm_unreachable("Unknown regclass!");
1049   }
1050
1051   return false;
1052 }
1053
1054 void
1055 PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
1056                                    MachineBasicBlock::iterator MI,
1057                                    unsigned DestReg, int FrameIdx,
1058                                    const TargetRegisterClass *RC,
1059                                    const TargetRegisterInfo *TRI) const {
1060   MachineFunction &MF = *MBB.getParent();
1061   SmallVector<MachineInstr*, 4> NewMIs;
1062   DebugLoc DL;
1063   if (MI != MBB.end()) DL = MI->getDebugLoc();
1064
1065   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1066   FuncInfo->setHasSpills();
1067
1068   bool NonRI = false, SpillsVRS = false;
1069   if (LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs,
1070                            NonRI, SpillsVRS))
1071     FuncInfo->setSpillsCR();
1072
1073   if (SpillsVRS)
1074     FuncInfo->setSpillsVRSAVE();
1075
1076   if (NonRI)
1077     FuncInfo->setHasNonRISpills();
1078
1079   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
1080     MBB.insert(MI, NewMIs[i]);
1081
1082   const MachineFrameInfo &MFI = *MF.getFrameInfo();
1083   MachineMemOperand *MMO =
1084     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
1085                             MachineMemOperand::MOLoad,
1086                             MFI.getObjectSize(FrameIdx),
1087                             MFI.getObjectAlignment(FrameIdx));
1088   NewMIs.back()->addMemOperand(MF, MMO);
1089 }
1090
1091 bool PPCInstrInfo::
1092 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
1093   assert(Cond.size() == 2 && "Invalid PPC branch opcode!");
1094   if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR)
1095     Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0);
1096   else
1097     // Leave the CR# the same, but invert the condition.
1098     Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm()));
1099   return false;
1100 }
1101
1102 bool PPCInstrInfo::FoldImmediate(MachineInstr *UseMI, MachineInstr *DefMI,
1103                              unsigned Reg, MachineRegisterInfo *MRI) const {
1104   // For some instructions, it is legal to fold ZERO into the RA register field.
1105   // A zero immediate should always be loaded with a single li.
1106   unsigned DefOpc = DefMI->getOpcode();
1107   if (DefOpc != PPC::LI && DefOpc != PPC::LI8)
1108     return false;
1109   if (!DefMI->getOperand(1).isImm())
1110     return false;
1111   if (DefMI->getOperand(1).getImm() != 0)
1112     return false;
1113
1114   // Note that we cannot here invert the arguments of an isel in order to fold
1115   // a ZERO into what is presented as the second argument. All we have here
1116   // is the condition bit, and that might come from a CR-logical bit operation.
1117
1118   const MCInstrDesc &UseMCID = UseMI->getDesc();
1119
1120   // Only fold into real machine instructions.
1121   if (UseMCID.isPseudo())
1122     return false;
1123
1124   unsigned UseIdx;
1125   for (UseIdx = 0; UseIdx < UseMI->getNumOperands(); ++UseIdx)
1126     if (UseMI->getOperand(UseIdx).isReg() &&
1127         UseMI->getOperand(UseIdx).getReg() == Reg)
1128       break;
1129
1130   assert(UseIdx < UseMI->getNumOperands() && "Cannot find Reg in UseMI");
1131   assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg");
1132
1133   const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx];
1134
1135   // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0
1136   // register (which might also be specified as a pointer class kind).
1137   if (UseInfo->isLookupPtrRegClass()) {
1138     if (UseInfo->RegClass /* Kind */ != 1)
1139       return false;
1140   } else {
1141     if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID &&
1142         UseInfo->RegClass != PPC::G8RC_NOX0RegClassID)
1143       return false;
1144   }
1145
1146   // Make sure this is not tied to an output register (or otherwise
1147   // constrained). This is true for ST?UX registers, for example, which
1148   // are tied to their output registers.
1149   if (UseInfo->Constraints != 0)
1150     return false;
1151
1152   unsigned ZeroReg;
1153   if (UseInfo->isLookupPtrRegClass()) {
1154     bool isPPC64 = Subtarget.isPPC64();
1155     ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO;
1156   } else {
1157     ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ?
1158               PPC::ZERO8 : PPC::ZERO;
1159   }
1160
1161   bool DeleteDef = MRI->hasOneNonDBGUse(Reg);
1162   UseMI->getOperand(UseIdx).setReg(ZeroReg);
1163
1164   if (DeleteDef)
1165     DefMI->eraseFromParent();
1166
1167   return true;
1168 }
1169
1170 static bool MBBDefinesCTR(MachineBasicBlock &MBB) {
1171   for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end();
1172        I != IE; ++I)
1173     if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8))
1174       return true;
1175   return false;
1176 }
1177
1178 // We should make sure that, if we're going to predicate both sides of a
1179 // condition (a diamond), that both sides don't define the counter register. We
1180 // can predicate counter-decrement-based branches, but while that predicates
1181 // the branching, it does not predicate the counter decrement. If we tried to
1182 // merge the triangle into one predicated block, we'd decrement the counter
1183 // twice.
1184 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB,
1185                      unsigned NumT, unsigned ExtraT,
1186                      MachineBasicBlock &FMBB,
1187                      unsigned NumF, unsigned ExtraF,
1188                      const BranchProbability &Probability) const {
1189   return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB));
1190 }
1191
1192
1193 bool PPCInstrInfo::isPredicated(const MachineInstr *MI) const {
1194   // The predicated branches are identified by their type, not really by the
1195   // explicit presence of a predicate. Furthermore, some of them can be
1196   // predicated more than once. Because if conversion won't try to predicate
1197   // any instruction which already claims to be predicated (by returning true
1198   // here), always return false. In doing so, we let isPredicable() be the
1199   // final word on whether not the instruction can be (further) predicated.
1200
1201   return false;
1202 }
1203
1204 bool PPCInstrInfo::isUnpredicatedTerminator(const MachineInstr *MI) const {
1205   if (!MI->isTerminator())
1206     return false;
1207
1208   // Conditional branch is a special case.
1209   if (MI->isBranch() && !MI->isBarrier())
1210     return true;
1211
1212   return !isPredicated(MI);
1213 }
1214
1215 bool PPCInstrInfo::PredicateInstruction(MachineInstr *MI,
1216                                         ArrayRef<MachineOperand> Pred) const {
1217   unsigned OpC = MI->getOpcode();
1218   if (OpC == PPC::BLR || OpC == PPC::BLR8) {
1219     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1220       bool isPPC64 = Subtarget.isPPC64();
1221       MI->setDesc(get(Pred[0].getImm() ?
1222                       (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) :
1223                       (isPPC64 ? PPC::BDZLR8  : PPC::BDZLR)));
1224     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1225       MI->setDesc(get(PPC::BCLR));
1226       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1227         .addReg(Pred[1].getReg());
1228     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1229       MI->setDesc(get(PPC::BCLRn));
1230       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1231         .addReg(Pred[1].getReg());
1232     } else {
1233       MI->setDesc(get(PPC::BCCLR));
1234       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1235         .addImm(Pred[0].getImm())
1236         .addReg(Pred[1].getReg());
1237     }
1238
1239     return true;
1240   } else if (OpC == PPC::B) {
1241     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) {
1242       bool isPPC64 = Subtarget.isPPC64();
1243       MI->setDesc(get(Pred[0].getImm() ?
1244                       (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1245                       (isPPC64 ? PPC::BDZ8  : PPC::BDZ)));
1246     } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1247       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1248       MI->RemoveOperand(0);
1249
1250       MI->setDesc(get(PPC::BC));
1251       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1252         .addReg(Pred[1].getReg())
1253         .addMBB(MBB);
1254     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1255       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1256       MI->RemoveOperand(0);
1257
1258       MI->setDesc(get(PPC::BCn));
1259       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1260         .addReg(Pred[1].getReg())
1261         .addMBB(MBB);
1262     } else {
1263       MachineBasicBlock *MBB = MI->getOperand(0).getMBB();
1264       MI->RemoveOperand(0);
1265
1266       MI->setDesc(get(PPC::BCC));
1267       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1268         .addImm(Pred[0].getImm())
1269         .addReg(Pred[1].getReg())
1270         .addMBB(MBB);
1271     }
1272
1273     return true;
1274   } else if (OpC == PPC::BCTR  || OpC == PPC::BCTR8 ||
1275              OpC == PPC::BCTRL || OpC == PPC::BCTRL8) {
1276     if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR)
1277       llvm_unreachable("Cannot predicate bctr[l] on the ctr register");
1278
1279     bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8;
1280     bool isPPC64 = Subtarget.isPPC64();
1281
1282     if (Pred[0].getImm() == PPC::PRED_BIT_SET) {
1283       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) :
1284                                 (setLR ? PPC::BCCTRL  : PPC::BCCTR)));
1285       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1286         .addReg(Pred[1].getReg());
1287       return true;
1288     } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) {
1289       MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) :
1290                                 (setLR ? PPC::BCCTRLn  : PPC::BCCTRn)));
1291       MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1292         .addReg(Pred[1].getReg());
1293       return true;
1294     }
1295
1296     MI->setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) :
1297                               (setLR ? PPC::BCCCTRL  : PPC::BCCCTR)));
1298     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
1299       .addImm(Pred[0].getImm())
1300       .addReg(Pred[1].getReg());
1301     return true;
1302   }
1303
1304   return false;
1305 }
1306
1307 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1,
1308                                      ArrayRef<MachineOperand> Pred2) const {
1309   assert(Pred1.size() == 2 && "Invalid PPC first predicate");
1310   assert(Pred2.size() == 2 && "Invalid PPC second predicate");
1311
1312   if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR)
1313     return false;
1314   if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR)
1315     return false;
1316
1317   // P1 can only subsume P2 if they test the same condition register.
1318   if (Pred1[1].getReg() != Pred2[1].getReg())
1319     return false;
1320
1321   PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm();
1322   PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm();
1323
1324   if (P1 == P2)
1325     return true;
1326
1327   // Does P1 subsume P2, e.g. GE subsumes GT.
1328   if (P1 == PPC::PRED_LE &&
1329       (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ))
1330     return true;
1331   if (P1 == PPC::PRED_GE &&
1332       (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ))
1333     return true;
1334
1335   return false;
1336 }
1337
1338 bool PPCInstrInfo::DefinesPredicate(MachineInstr *MI,
1339                                     std::vector<MachineOperand> &Pred) const {
1340   // Note: At the present time, the contents of Pred from this function is
1341   // unused by IfConversion. This implementation follows ARM by pushing the
1342   // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of
1343   // predicate, instructions defining CTR or CTR8 are also included as
1344   // predicate-defining instructions.
1345
1346   const TargetRegisterClass *RCs[] =
1347     { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass,
1348       &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass };
1349
1350   bool Found = false;
1351   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1352     const MachineOperand &MO = MI->getOperand(i);
1353     for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) {
1354       const TargetRegisterClass *RC = RCs[c];
1355       if (MO.isReg()) {
1356         if (MO.isDef() && RC->contains(MO.getReg())) {
1357           Pred.push_back(MO);
1358           Found = true;
1359         }
1360       } else if (MO.isRegMask()) {
1361         for (TargetRegisterClass::iterator I = RC->begin(),
1362              IE = RC->end(); I != IE; ++I)
1363           if (MO.clobbersPhysReg(*I)) {
1364             Pred.push_back(MO);
1365             Found = true;
1366           }
1367       }
1368     }
1369   }
1370
1371   return Found;
1372 }
1373
1374 bool PPCInstrInfo::isPredicable(MachineInstr *MI) const {
1375   unsigned OpC = MI->getOpcode();
1376   switch (OpC) {
1377   default:
1378     return false;
1379   case PPC::B:
1380   case PPC::BLR:
1381   case PPC::BLR8:
1382   case PPC::BCTR:
1383   case PPC::BCTR8:
1384   case PPC::BCTRL:
1385   case PPC::BCTRL8:
1386     return true;
1387   }
1388 }
1389
1390 bool PPCInstrInfo::analyzeCompare(const MachineInstr *MI,
1391                                   unsigned &SrcReg, unsigned &SrcReg2,
1392                                   int &Mask, int &Value) const {
1393   unsigned Opc = MI->getOpcode();
1394
1395   switch (Opc) {
1396   default: return false;
1397   case PPC::CMPWI:
1398   case PPC::CMPLWI:
1399   case PPC::CMPDI:
1400   case PPC::CMPLDI:
1401     SrcReg = MI->getOperand(1).getReg();
1402     SrcReg2 = 0;
1403     Value = MI->getOperand(2).getImm();
1404     Mask = 0xFFFF;
1405     return true;
1406   case PPC::CMPW:
1407   case PPC::CMPLW:
1408   case PPC::CMPD:
1409   case PPC::CMPLD:
1410   case PPC::FCMPUS:
1411   case PPC::FCMPUD:
1412     SrcReg = MI->getOperand(1).getReg();
1413     SrcReg2 = MI->getOperand(2).getReg();
1414     return true;
1415   }
1416 }
1417
1418 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr *CmpInstr,
1419                                         unsigned SrcReg, unsigned SrcReg2,
1420                                         int Mask, int Value,
1421                                         const MachineRegisterInfo *MRI) const {
1422   if (DisableCmpOpt)
1423     return false;
1424
1425   int OpC = CmpInstr->getOpcode();
1426   unsigned CRReg = CmpInstr->getOperand(0).getReg();
1427
1428   // FP record forms set CR1 based on the execption status bits, not a
1429   // comparison with zero.
1430   if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD)
1431     return false;
1432
1433   // The record forms set the condition register based on a signed comparison
1434   // with zero (so says the ISA manual). This is not as straightforward as it
1435   // seems, however, because this is always a 64-bit comparison on PPC64, even
1436   // for instructions that are 32-bit in nature (like slw for example).
1437   // So, on PPC32, for unsigned comparisons, we can use the record forms only
1438   // for equality checks (as those don't depend on the sign). On PPC64,
1439   // we are restricted to equality for unsigned 64-bit comparisons and for
1440   // signed 32-bit comparisons the applicability is more restricted.
1441   bool isPPC64 = Subtarget.isPPC64();
1442   bool is32BitSignedCompare   = OpC ==  PPC::CMPWI || OpC == PPC::CMPW;
1443   bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW;
1444   bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD;
1445
1446   // Get the unique definition of SrcReg.
1447   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
1448   if (!MI) return false;
1449   int MIOpC = MI->getOpcode();
1450
1451   bool equalityOnly = false;
1452   bool noSub = false;
1453   if (isPPC64) {
1454     if (is32BitSignedCompare) {
1455       // We can perform this optimization only if MI is sign-extending.
1456       if (MIOpC == PPC::SRAW  || MIOpC == PPC::SRAWo ||
1457           MIOpC == PPC::SRAWI || MIOpC == PPC::SRAWIo ||
1458           MIOpC == PPC::EXTSB || MIOpC == PPC::EXTSBo ||
1459           MIOpC == PPC::EXTSH || MIOpC == PPC::EXTSHo ||
1460           MIOpC == PPC::EXTSW || MIOpC == PPC::EXTSWo) {
1461         noSub = true;
1462       } else
1463         return false;
1464     } else if (is32BitUnsignedCompare) {
1465       // We can perform this optimization, equality only, if MI is
1466       // zero-extending.
1467       if (MIOpC == PPC::CNTLZW || MIOpC == PPC::CNTLZWo ||
1468           MIOpC == PPC::SLW    || MIOpC == PPC::SLWo ||
1469           MIOpC == PPC::SRW    || MIOpC == PPC::SRWo) {
1470         noSub = true;
1471         equalityOnly = true;
1472       } else
1473         return false;
1474     } else
1475       equalityOnly = is64BitUnsignedCompare;
1476   } else
1477     equalityOnly = is32BitUnsignedCompare;
1478
1479   if (equalityOnly) {
1480     // We need to check the uses of the condition register in order to reject
1481     // non-equality comparisons.
1482     for (MachineRegisterInfo::use_instr_iterator I =MRI->use_instr_begin(CRReg),
1483          IE = MRI->use_instr_end(); I != IE; ++I) {
1484       MachineInstr *UseMI = &*I;
1485       if (UseMI->getOpcode() == PPC::BCC) {
1486         unsigned Pred = UseMI->getOperand(0).getImm();
1487         if (Pred != PPC::PRED_EQ && Pred != PPC::PRED_NE)
1488           return false;
1489       } else if (UseMI->getOpcode() == PPC::ISEL ||
1490                  UseMI->getOpcode() == PPC::ISEL8) {
1491         unsigned SubIdx = UseMI->getOperand(3).getSubReg();
1492         if (SubIdx != PPC::sub_eq)
1493           return false;
1494       } else
1495         return false;
1496     }
1497   }
1498
1499   MachineBasicBlock::iterator I = CmpInstr;
1500
1501   // Scan forward to find the first use of the compare.
1502   for (MachineBasicBlock::iterator EL = CmpInstr->getParent()->end();
1503        I != EL; ++I) {
1504     bool FoundUse = false;
1505     for (MachineRegisterInfo::use_instr_iterator J =MRI->use_instr_begin(CRReg),
1506          JE = MRI->use_instr_end(); J != JE; ++J)
1507       if (&*J == &*I) {
1508         FoundUse = true;
1509         break;
1510       }
1511
1512     if (FoundUse)
1513       break;
1514   }
1515
1516   // There are two possible candidates which can be changed to set CR[01].
1517   // One is MI, the other is a SUB instruction.
1518   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
1519   MachineInstr *Sub = nullptr;
1520   if (SrcReg2 != 0)
1521     // MI is not a candidate for CMPrr.
1522     MI = nullptr;
1523   // FIXME: Conservatively refuse to convert an instruction which isn't in the
1524   // same BB as the comparison. This is to allow the check below to avoid calls
1525   // (and other explicit clobbers); instead we should really check for these
1526   // more explicitly (in at least a few predecessors).
1527   else if (MI->getParent() != CmpInstr->getParent() || Value != 0) {
1528     // PPC does not have a record-form SUBri.
1529     return false;
1530   }
1531
1532   // Search for Sub.
1533   const TargetRegisterInfo *TRI = &getRegisterInfo();
1534   --I;
1535
1536   // Get ready to iterate backward from CmpInstr.
1537   MachineBasicBlock::iterator E = MI,
1538                               B = CmpInstr->getParent()->begin();
1539
1540   for (; I != E && !noSub; --I) {
1541     const MachineInstr &Instr = *I;
1542     unsigned IOpC = Instr.getOpcode();
1543
1544     if (&*I != CmpInstr && (
1545         Instr.modifiesRegister(PPC::CR0, TRI) ||
1546         Instr.readsRegister(PPC::CR0, TRI)))
1547       // This instruction modifies or uses the record condition register after
1548       // the one we want to change. While we could do this transformation, it
1549       // would likely not be profitable. This transformation removes one
1550       // instruction, and so even forcing RA to generate one move probably
1551       // makes it unprofitable.
1552       return false;
1553
1554     // Check whether CmpInstr can be made redundant by the current instruction.
1555     if ((OpC == PPC::CMPW || OpC == PPC::CMPLW ||
1556          OpC == PPC::CMPD || OpC == PPC::CMPLD) &&
1557         (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) &&
1558         ((Instr.getOperand(1).getReg() == SrcReg &&
1559           Instr.getOperand(2).getReg() == SrcReg2) ||
1560         (Instr.getOperand(1).getReg() == SrcReg2 &&
1561          Instr.getOperand(2).getReg() == SrcReg))) {
1562       Sub = &*I;
1563       break;
1564     }
1565
1566     if (I == B)
1567       // The 'and' is below the comparison instruction.
1568       return false;
1569   }
1570
1571   // Return false if no candidates exist.
1572   if (!MI && !Sub)
1573     return false;
1574
1575   // The single candidate is called MI.
1576   if (!MI) MI = Sub;
1577
1578   int NewOpC = -1;
1579   MIOpC = MI->getOpcode();
1580   if (MIOpC == PPC::ANDIo || MIOpC == PPC::ANDIo8)
1581     NewOpC = MIOpC;
1582   else {
1583     NewOpC = PPC::getRecordFormOpcode(MIOpC);
1584     if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1)
1585       NewOpC = MIOpC;
1586   }
1587
1588   // FIXME: On the non-embedded POWER architectures, only some of the record
1589   // forms are fast, and we should use only the fast ones.
1590
1591   // The defining instruction has a record form (or is already a record
1592   // form). It is possible, however, that we'll need to reverse the condition
1593   // code of the users.
1594   if (NewOpC == -1)
1595     return false;
1596
1597   SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate;
1598   SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate;
1599
1600   // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP
1601   // needs to be updated to be based on SUB.  Push the condition code
1602   // operands to OperandsToUpdate.  If it is safe to remove CmpInstr, the
1603   // condition code of these operands will be modified.
1604   bool ShouldSwap = false;
1605   if (Sub) {
1606     ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
1607       Sub->getOperand(2).getReg() == SrcReg;
1608
1609     // The operands to subf are the opposite of sub, so only in the fixed-point
1610     // case, invert the order.
1611     ShouldSwap = !ShouldSwap;
1612   }
1613
1614   if (ShouldSwap)
1615     for (MachineRegisterInfo::use_instr_iterator
1616          I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end();
1617          I != IE; ++I) {
1618       MachineInstr *UseMI = &*I;
1619       if (UseMI->getOpcode() == PPC::BCC) {
1620         PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm();
1621         assert((!equalityOnly ||
1622                 Pred == PPC::PRED_EQ || Pred == PPC::PRED_NE) &&
1623                "Invalid predicate for equality-only optimization");
1624         PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)),
1625                                 PPC::getSwappedPredicate(Pred)));
1626       } else if (UseMI->getOpcode() == PPC::ISEL ||
1627                  UseMI->getOpcode() == PPC::ISEL8) {
1628         unsigned NewSubReg = UseMI->getOperand(3).getSubReg();
1629         assert((!equalityOnly || NewSubReg == PPC::sub_eq) &&
1630                "Invalid CR bit for equality-only optimization");
1631
1632         if (NewSubReg == PPC::sub_lt)
1633           NewSubReg = PPC::sub_gt;
1634         else if (NewSubReg == PPC::sub_gt)
1635           NewSubReg = PPC::sub_lt;
1636
1637         SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)),
1638                                                  NewSubReg));
1639       } else // We need to abort on a user we don't understand.
1640         return false;
1641     }
1642
1643   // Create a new virtual register to hold the value of the CR set by the
1644   // record-form instruction. If the instruction was not previously in
1645   // record form, then set the kill flag on the CR.
1646   CmpInstr->eraseFromParent();
1647
1648   MachineBasicBlock::iterator MII = MI;
1649   BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(),
1650           get(TargetOpcode::COPY), CRReg)
1651     .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0);
1652
1653   if (MIOpC != NewOpC) {
1654     // We need to be careful here: we're replacing one instruction with
1655     // another, and we need to make sure that we get all of the right
1656     // implicit uses and defs. On the other hand, the caller may be holding
1657     // an iterator to this instruction, and so we can't delete it (this is
1658     // specifically the case if this is the instruction directly after the
1659     // compare).
1660
1661     const MCInstrDesc &NewDesc = get(NewOpC);
1662     MI->setDesc(NewDesc);
1663
1664     if (NewDesc.ImplicitDefs)
1665       for (const uint16_t *ImpDefs = NewDesc.getImplicitDefs();
1666            *ImpDefs; ++ImpDefs)
1667         if (!MI->definesRegister(*ImpDefs))
1668           MI->addOperand(*MI->getParent()->getParent(),
1669                          MachineOperand::CreateReg(*ImpDefs, true, true));
1670     if (NewDesc.ImplicitUses)
1671       for (const uint16_t *ImpUses = NewDesc.getImplicitUses();
1672            *ImpUses; ++ImpUses)
1673         if (!MI->readsRegister(*ImpUses))
1674           MI->addOperand(*MI->getParent()->getParent(),
1675                          MachineOperand::CreateReg(*ImpUses, false, true));
1676   }
1677
1678   // Modify the condition code of operands in OperandsToUpdate.
1679   // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
1680   // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
1681   for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++)
1682     PredsToUpdate[i].first->setImm(PredsToUpdate[i].second);
1683
1684   for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++)
1685     SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second);
1686
1687   return true;
1688 }
1689
1690 /// GetInstSize - Return the number of bytes of code the specified
1691 /// instruction may be.  This returns the maximum number of bytes.
1692 ///
1693 unsigned PPCInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
1694   unsigned Opcode = MI->getOpcode();
1695
1696   if (Opcode == PPC::INLINEASM) {
1697     const MachineFunction *MF = MI->getParent()->getParent();
1698     const char *AsmStr = MI->getOperand(0).getSymbolName();
1699     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
1700   } else if (Opcode == TargetOpcode::STACKMAP) {
1701     return MI->getOperand(1).getImm();
1702   } else if (Opcode == TargetOpcode::PATCHPOINT) {
1703     PatchPointOpers Opers(MI);
1704     return Opers.getMetaOper(PatchPointOpers::NBytesPos).getImm();
1705   } else {
1706     const MCInstrDesc &Desc = get(Opcode);
1707     return Desc.getSize();
1708   }
1709 }
1710