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