MipsInstrInfo.cpp revision 794bf17cbe0bac301ef9e52fb4a0295bfdfe0cab
1//===- MipsInstrInfo.cpp - Mips Instruction Information ---------*- C++ -*-===//
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 Mips implementation of the TargetInstrInfo class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MipsInstrInfo.h"
15#include "MipsTargetMachine.h"
16#include "MipsMachineFunction.h"
17#include "InstPrinter/MipsInstPrinter.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/CodeGen/MachineInstrBuilder.h"
20#include "llvm/CodeGen/MachineRegisterInfo.h"
21#include "llvm/Support/ErrorHandling.h"
22
23#define GET_INSTRINFO_CTOR
24#define GET_INSTRINFO_MC_DESC
25#include "MipsGenInstrInfo.inc"
26
27using namespace llvm;
28
29MipsInstrInfo::MipsInstrInfo(MipsTargetMachine &tm)
30  : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
31    TM(tm), RI(*TM.getSubtargetImpl(), *this) {}
32
33
34const MipsRegisterInfo &MipsInstrInfo::getRegisterInfo() const {
35  return RI;
36}
37
38static bool isZeroImm(const MachineOperand &op) {
39  return op.isImm() && op.getImm() == 0;
40}
41
42/// isLoadFromStackSlot - If the specified machine instruction is a direct
43/// load from a stack slot, return the virtual or physical register number of
44/// the destination along with the FrameIndex of the loaded stack slot.  If
45/// not, return 0.  This predicate must return 0 if the instruction has
46/// any side effects other than loading from the stack slot.
47unsigned MipsInstrInfo::
48isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const
49{
50  if ((MI->getOpcode() == Mips::LW) || (MI->getOpcode() == Mips::LWC1) ||
51      (MI->getOpcode() == Mips::LDC1)) {
52    if ((MI->getOperand(1).isFI()) && // is a stack slot
53        (MI->getOperand(2).isImm()) &&  // the imm is zero
54        (isZeroImm(MI->getOperand(2)))) {
55      FrameIndex = MI->getOperand(1).getIndex();
56      return MI->getOperand(0).getReg();
57    }
58  }
59
60  return 0;
61}
62
63/// isStoreToStackSlot - If the specified machine instruction is a direct
64/// store to a stack slot, return the virtual or physical register number of
65/// the source reg along with the FrameIndex of the loaded stack slot.  If
66/// not, return 0.  This predicate must return 0 if the instruction has
67/// any side effects other than storing to the stack slot.
68unsigned MipsInstrInfo::
69isStoreToStackSlot(const MachineInstr *MI, int &FrameIndex) const
70{
71  if ((MI->getOpcode() == Mips::SW) || (MI->getOpcode() == Mips::SWC1) ||
72      (MI->getOpcode() == Mips::SDC1)) {
73    if ((MI->getOperand(1).isFI()) && // is a stack slot
74        (MI->getOperand(2).isImm()) &&  // the imm is zero
75        (isZeroImm(MI->getOperand(2)))) {
76      FrameIndex = MI->getOperand(1).getIndex();
77      return MI->getOperand(0).getReg();
78    }
79  }
80  return 0;
81}
82
83/// insertNoop - If data hazard condition is found insert the target nop
84/// instruction.
85void MipsInstrInfo::
86insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
87{
88  DebugLoc DL;
89  BuildMI(MBB, MI, DL, get(Mips::NOP));
90}
91
92void MipsInstrInfo::
93copyPhysReg(MachineBasicBlock &MBB,
94            MachineBasicBlock::iterator I, DebugLoc DL,
95            unsigned DestReg, unsigned SrcReg,
96            bool KillSrc) const {
97  bool DestCPU = Mips::CPURegsRegClass.contains(DestReg);
98  bool SrcCPU  = Mips::CPURegsRegClass.contains(SrcReg);
99
100  // CPU-CPU is the most common.
101  if (DestCPU && SrcCPU) {
102    BuildMI(MBB, I, DL, get(Mips::ADDu), DestReg).addReg(Mips::ZERO)
103      .addReg(SrcReg, getKillRegState(KillSrc));
104    return;
105  }
106
107  // Copy to CPU from other registers.
108  if (DestCPU) {
109    if (Mips::CCRRegClass.contains(SrcReg))
110      BuildMI(MBB, I, DL, get(Mips::CFC1), DestReg)
111        .addReg(SrcReg, getKillRegState(KillSrc));
112    else if (Mips::FGR32RegClass.contains(SrcReg))
113      BuildMI(MBB, I, DL, get(Mips::MFC1), DestReg)
114        .addReg(SrcReg, getKillRegState(KillSrc));
115    else if (SrcReg == Mips::HI)
116      BuildMI(MBB, I, DL, get(Mips::MFHI), DestReg);
117    else if (SrcReg == Mips::LO)
118      BuildMI(MBB, I, DL, get(Mips::MFLO), DestReg);
119    else
120      llvm_unreachable("Copy to CPU from invalid register");
121    return;
122  }
123
124  // Copy to other registers from CPU.
125  if (SrcCPU) {
126    if (Mips::CCRRegClass.contains(DestReg))
127      BuildMI(MBB, I, DL, get(Mips::CTC1), DestReg)
128        .addReg(SrcReg, getKillRegState(KillSrc));
129    else if (Mips::FGR32RegClass.contains(DestReg))
130      BuildMI(MBB, I, DL, get(Mips::MTC1), DestReg)
131        .addReg(SrcReg, getKillRegState(KillSrc));
132    else if (DestReg == Mips::HI)
133      BuildMI(MBB, I, DL, get(Mips::MTHI))
134        .addReg(SrcReg, getKillRegState(KillSrc));
135    else if (DestReg == Mips::LO)
136      BuildMI(MBB, I, DL, get(Mips::MTLO))
137        .addReg(SrcReg, getKillRegState(KillSrc));
138    else
139      llvm_unreachable("Copy from CPU to invalid register");
140    return;
141  }
142
143  if (Mips::FGR32RegClass.contains(DestReg, SrcReg)) {
144    BuildMI(MBB, I, DL, get(Mips::FMOV_S32), DestReg)
145      .addReg(SrcReg, getKillRegState(KillSrc));
146    return;
147  }
148
149  if (Mips::AFGR64RegClass.contains(DestReg, SrcReg)) {
150    BuildMI(MBB, I, DL, get(Mips::FMOV_D32), DestReg)
151      .addReg(SrcReg, getKillRegState(KillSrc));
152    return;
153  }
154
155  if (Mips::CCRRegClass.contains(DestReg, SrcReg)) {
156    BuildMI(MBB, I, DL, get(Mips::MOVCCRToCCR), DestReg)
157      .addReg(SrcReg, getKillRegState(KillSrc));
158    return;
159  }
160  llvm_unreachable("Cannot copy registers");
161}
162
163void MipsInstrInfo::
164storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
165                    unsigned SrcReg, bool isKill, int FI,
166                    const TargetRegisterClass *RC,
167                    const TargetRegisterInfo *TRI) const {
168  DebugLoc DL;
169  if (I != MBB.end()) DL = I->getDebugLoc();
170
171  if (RC == Mips::CPURegsRegisterClass)
172    BuildMI(MBB, I, DL, get(Mips::SW)).addReg(SrcReg, getKillRegState(isKill))
173                                      .addFrameIndex(FI).addImm(0);
174  else if (RC == Mips::FGR32RegisterClass)
175    BuildMI(MBB, I, DL, get(Mips::SWC1)).addReg(SrcReg, getKillRegState(isKill))
176                                        .addFrameIndex(FI).addImm(0);
177  else if (RC == Mips::AFGR64RegisterClass) {
178    if (!TM.getSubtarget<MipsSubtarget>().isMips1()) {
179      BuildMI(MBB, I, DL, get(Mips::SDC1))
180        .addReg(SrcReg, getKillRegState(isKill))
181        .addFrameIndex(FI).addImm(0);
182    } else {
183      const TargetRegisterInfo *TRI =
184        MBB.getParent()->getTarget().getRegisterInfo();
185      const unsigned *SubSet = TRI->getSubRegisters(SrcReg);
186      BuildMI(MBB, I, DL, get(Mips::SWC1))
187        .addReg(SubSet[0], getKillRegState(isKill))
188        .addFrameIndex(FI).addImm(0);
189      BuildMI(MBB, I, DL, get(Mips::SWC1))
190        .addReg(SubSet[1], getKillRegState(isKill))
191        .addFrameIndex(FI).addImm(4);
192    }
193  } else
194    llvm_unreachable("Register class not handled!");
195}
196
197void MipsInstrInfo::
198loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
199                     unsigned DestReg, int FI,
200                     const TargetRegisterClass *RC,
201                     const TargetRegisterInfo *TRI) const
202{
203  DebugLoc DL;
204  if (I != MBB.end()) DL = I->getDebugLoc();
205
206  if (RC == Mips::CPURegsRegisterClass)
207    BuildMI(MBB, I, DL, get(Mips::LW), DestReg).addFrameIndex(FI).addImm(0);
208  else if (RC == Mips::FGR32RegisterClass)
209    BuildMI(MBB, I, DL, get(Mips::LWC1), DestReg).addFrameIndex(FI).addImm(0);
210  else if (RC == Mips::AFGR64RegisterClass) {
211    if (!TM.getSubtarget<MipsSubtarget>().isMips1()) {
212      BuildMI(MBB, I, DL, get(Mips::LDC1), DestReg).addFrameIndex(FI).addImm(0);
213    } else {
214      const TargetRegisterInfo *TRI =
215        MBB.getParent()->getTarget().getRegisterInfo();
216      const unsigned *SubSet = TRI->getSubRegisters(DestReg);
217      BuildMI(MBB, I, DL, get(Mips::LWC1), SubSet[0])
218        .addFrameIndex(FI).addImm(0);
219      BuildMI(MBB, I, DL, get(Mips::LWC1), SubSet[1])
220        .addFrameIndex(FI).addImm(4);
221    }
222  } else
223    llvm_unreachable("Register class not handled!");
224}
225
226MachineInstr*
227MipsInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF, int FrameIx,
228                                        uint64_t Offset, const MDNode *MDPtr,
229                                        DebugLoc DL) const {
230  MachineInstrBuilder MIB = BuildMI(MF, DL, get(Mips::DBG_VALUE))
231    .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
232  return &*MIB;
233}
234
235//===----------------------------------------------------------------------===//
236// Branch Analysis
237//===----------------------------------------------------------------------===//
238
239static unsigned GetAnalyzableBrOpc(unsigned Opc) {
240  return (Opc == Mips::BEQ  || Opc == Mips::BNE  || Opc == Mips::BGTZ ||
241          Opc == Mips::BGEZ || Opc == Mips::BLTZ || Opc == Mips::BLEZ ||
242          Opc == Mips::BC1T || Opc == Mips::BC1F || Opc == Mips::J) ? Opc : 0;
243}
244
245/// GetOppositeBranchOpc - Return the inverse of the specified
246/// opcode, e.g. turning BEQ to BNE.
247unsigned Mips::GetOppositeBranchOpc(unsigned Opc)
248{
249  switch (Opc) {
250  default: llvm_unreachable("Illegal opcode!");
251  case Mips::BEQ  : return Mips::BNE;
252  case Mips::BNE  : return Mips::BEQ;
253  case Mips::BGTZ : return Mips::BLEZ;
254  case Mips::BGEZ : return Mips::BLTZ;
255  case Mips::BLTZ : return Mips::BGEZ;
256  case Mips::BLEZ : return Mips::BGTZ;
257  case Mips::BC1T : return Mips::BC1F;
258  case Mips::BC1F : return Mips::BC1T;
259  }
260}
261
262static void AnalyzeCondBr(const MachineInstr* Inst, unsigned Opc,
263                          MachineBasicBlock *&BB,
264                          SmallVectorImpl<MachineOperand>& Cond) {
265  assert(GetAnalyzableBrOpc(Opc) && "Not an analyzable branch");
266  int NumOp = Inst->getNumExplicitOperands();
267
268  // for both int and fp branches, the last explicit operand is the
269  // MBB.
270  BB = Inst->getOperand(NumOp-1).getMBB();
271  Cond.push_back(MachineOperand::CreateImm(Opc));
272
273  for (int i=0; i<NumOp-1; i++)
274    Cond.push_back(Inst->getOperand(i));
275}
276
277bool MipsInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
278                                  MachineBasicBlock *&TBB,
279                                  MachineBasicBlock *&FBB,
280                                  SmallVectorImpl<MachineOperand> &Cond,
281                                  bool AllowModify) const
282{
283  MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
284
285  // Skip all the debug instructions.
286  while (I != REnd && I->isDebugValue())
287    ++I;
288
289  if (I == REnd || !isUnpredicatedTerminator(&*I)) {
290    // If this block ends with no branches (it just falls through to its succ)
291    // just return false, leaving TBB/FBB null.
292    TBB = FBB = NULL;
293    return false;
294  }
295
296  MachineInstr *LastInst = &*I;
297  unsigned LastOpc = LastInst->getOpcode();
298
299  // Not an analyzable branch (must be an indirect jump).
300  if (!GetAnalyzableBrOpc(LastOpc))
301    return true;
302
303  // Get the second to last instruction in the block.
304  unsigned SecondLastOpc = 0;
305  MachineInstr *SecondLastInst = NULL;
306
307  if (++I != REnd) {
308    SecondLastInst = &*I;
309    SecondLastOpc = GetAnalyzableBrOpc(SecondLastInst->getOpcode());
310
311    // Not an analyzable branch (must be an indirect jump).
312    if (isUnpredicatedTerminator(SecondLastInst) && !SecondLastOpc)
313      return true;
314  }
315
316  // If there is only one terminator instruction, process it.
317  if (!SecondLastOpc) {
318    // Unconditional branch
319    if (LastOpc == Mips::J) {
320      TBB = LastInst->getOperand(0).getMBB();
321      return false;
322    }
323
324    // Conditional branch
325    AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);
326    return false;
327  }
328
329  // If we reached here, there are two branches.
330  // If there are three terminators, we don't know what sort of block this is.
331  if (++I != REnd && isUnpredicatedTerminator(&*I))
332    return true;
333
334  // If second to last instruction is an unconditional branch,
335  // analyze it and remove the last instruction.
336  if (SecondLastOpc == Mips::J) {
337    // Return if the last instruction cannot be removed.
338    if (!AllowModify)
339      return true;
340
341    TBB = SecondLastInst->getOperand(0).getMBB();
342    LastInst->eraseFromParent();
343    return false;
344  }
345
346  // Conditional branch followed by an unconditional branch.
347  // The last one must be unconditional.
348  if (LastOpc != Mips::J)
349    return true;
350
351  AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);
352  FBB = LastInst->getOperand(0).getMBB();
353
354  return false;
355}
356
357void MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB,
358                                MachineBasicBlock *TBB, DebugLoc DL,
359                                const SmallVectorImpl<MachineOperand>& Cond)
360  const {
361  unsigned Opc = Cond[0].getImm();
362  const MCInstrDesc &MCID = get(Opc);
363  MachineInstrBuilder MIB = BuildMI(&MBB, DL, MCID);
364
365  for (unsigned i = 1; i < Cond.size(); ++i)
366    MIB.addReg(Cond[i].getReg());
367
368  MIB.addMBB(TBB);
369}
370
371unsigned MipsInstrInfo::
372InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
373             MachineBasicBlock *FBB,
374             const SmallVectorImpl<MachineOperand> &Cond,
375             DebugLoc DL) const {
376  // Shouldn't be a fall through.
377  assert(TBB && "InsertBranch must not be told to insert a fallthrough");
378
379  // # of condition operands:
380  //  Unconditional branches: 0
381  //  Floating point branches: 1 (opc)
382  //  Int BranchZero: 2 (opc, reg)
383  //  Int Branch: 3 (opc, reg0, reg1)
384  assert((Cond.size() <= 3) &&
385         "# of Mips branch conditions must be <= 3!");
386
387  // Two-way Conditional branch.
388  if (FBB) {
389    BuildCondBr(MBB, TBB, DL, Cond);
390    BuildMI(&MBB, DL, get(Mips::J)).addMBB(FBB);
391    return 2;
392  }
393
394  // One way branch.
395  // Unconditional branch.
396  if (Cond.empty())
397    BuildMI(&MBB, DL, get(Mips::J)).addMBB(TBB);
398  else // Conditional branch.
399    BuildCondBr(MBB, TBB, DL, Cond);
400  return 1;
401}
402
403unsigned MipsInstrInfo::
404RemoveBranch(MachineBasicBlock &MBB) const
405{
406  MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
407  MachineBasicBlock::reverse_iterator FirstBr;
408  unsigned removed;
409
410  // Skip all the debug instructions.
411  while (I != REnd && I->isDebugValue())
412    ++I;
413
414  FirstBr = I;
415
416  // Up to 2 branches are removed.
417  // Note that indirect branches are not removed.
418  for(removed = 0; I != REnd && removed < 2; ++I, ++removed)
419    if (!GetAnalyzableBrOpc(I->getOpcode()))
420      break;
421
422  MBB.erase(I.base(), FirstBr.base());
423
424  return removed;
425}
426
427/// ReverseBranchCondition - Return the inverse opcode of the
428/// specified Branch instruction.
429bool MipsInstrInfo::
430ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const
431{
432  assert( (Cond.size() && Cond.size() <= 3) &&
433          "Invalid Mips branch condition!");
434  Cond[0].setImm(Mips::GetOppositeBranchOpc(Cond[0].getImm()));
435  return false;
436}
437
438/// getGlobalBaseReg - Return a virtual register initialized with the
439/// the global base register value. Output instructions required to
440/// initialize the register in the function entry block, if necessary.
441///
442unsigned MipsInstrInfo::getGlobalBaseReg(MachineFunction *MF) const {
443  MipsFunctionInfo *MipsFI = MF->getInfo<MipsFunctionInfo>();
444  unsigned GlobalBaseReg = MipsFI->getGlobalBaseReg();
445  if (GlobalBaseReg != 0)
446    return GlobalBaseReg;
447
448  // Insert the set of GlobalBaseReg into the first MBB of the function
449  MachineBasicBlock &FirstMBB = MF->front();
450  MachineBasicBlock::iterator MBBI = FirstMBB.begin();
451  MachineRegisterInfo &RegInfo = MF->getRegInfo();
452  const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
453
454  GlobalBaseReg = RegInfo.createVirtualRegister(Mips::CPURegsRegisterClass);
455  BuildMI(FirstMBB, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY),
456          GlobalBaseReg).addReg(Mips::GP);
457  RegInfo.addLiveIn(Mips::GP);
458
459  MipsFI->setGlobalBaseReg(GlobalBaseReg);
460  return GlobalBaseReg;
461}
462