1 //===-- MipsInstrInfo.cpp - Mips 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 Mips implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MipsInstrInfo.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MipsMachineFunction.h"
17 #include "MipsSubtarget.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 #include "llvm/Support/TargetRegistry.h"
23 
24 using namespace llvm;
25 
26 #define GET_INSTRINFO_CTOR_DTOR
27 #include "MipsGenInstrInfo.inc"
28 
29 // Pin the vtable to this file.
30 void MipsInstrInfo::anchor() {}
31 
32 MipsInstrInfo::MipsInstrInfo(const MipsSubtarget &STI, unsigned UncondBr)
33     : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
34       Subtarget(STI), UncondBrOpc(UncondBr) {}
35 
36 const MipsInstrInfo *MipsInstrInfo::create(MipsSubtarget &STI) {
37   if (STI.inMips16Mode())
38     return llvm::createMips16InstrInfo(STI);
39 
40   return llvm::createMipsSEInstrInfo(STI);
41 }
42 
43 bool MipsInstrInfo::isZeroImm(const MachineOperand &op) const {
44   return op.isImm() && op.getImm() == 0;
45 }
46 
47 /// insertNoop - If data hazard condition is found insert the target nop
48 /// instruction.
49 void MipsInstrInfo::
50 insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
51 {
52   DebugLoc DL;
53   BuildMI(MBB, MI, DL, get(Mips::NOP));
54 }
55 
56 MachineMemOperand *MipsInstrInfo::GetMemOperand(MachineBasicBlock &MBB, int FI,
57                                                 unsigned Flag) const {
58   MachineFunction &MF = *MBB.getParent();
59   MachineFrameInfo &MFI = *MF.getFrameInfo();
60   unsigned Align = MFI.getObjectAlignment(FI);
61 
62   return MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
63                                  Flag, MFI.getObjectSize(FI), Align);
64 }
65 
66 //===----------------------------------------------------------------------===//
67 // Branch Analysis
68 //===----------------------------------------------------------------------===//
69 
70 void MipsInstrInfo::AnalyzeCondBr(const MachineInstr *Inst, unsigned Opc,
71                                   MachineBasicBlock *&BB,
72                                   SmallVectorImpl<MachineOperand> &Cond) const {
73   assert(getAnalyzableBrOpc(Opc) && "Not an analyzable branch");
74   int NumOp = Inst->getNumExplicitOperands();
75 
76   // for both int and fp branches, the last explicit operand is the
77   // MBB.
78   BB = Inst->getOperand(NumOp-1).getMBB();
79   Cond.push_back(MachineOperand::CreateImm(Opc));
80 
81   for (int i=0; i<NumOp-1; i++)
82     Cond.push_back(Inst->getOperand(i));
83 }
84 
85 bool MipsInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,
86                                   MachineBasicBlock *&TBB,
87                                   MachineBasicBlock *&FBB,
88                                   SmallVectorImpl<MachineOperand> &Cond,
89                                   bool AllowModify) const {
90   SmallVector<MachineInstr*, 2> BranchInstrs;
91   BranchType BT = AnalyzeBranch(MBB, TBB, FBB, Cond, AllowModify, BranchInstrs);
92 
93   return (BT == BT_None) || (BT == BT_Indirect);
94 }
95 
96 void
97 MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
98                            DebugLoc DL, ArrayRef<MachineOperand> Cond) const {
99   unsigned Opc = Cond[0].getImm();
100   const MCInstrDesc &MCID = get(Opc);
101   MachineInstrBuilder MIB = BuildMI(&MBB, DL, MCID);
102 
103   for (unsigned i = 1; i < Cond.size(); ++i) {
104     if (Cond[i].isReg())
105       MIB.addReg(Cond[i].getReg());
106     else if (Cond[i].isImm())
107       MIB.addImm(Cond[i].getImm());
108     else
109        assert(true && "Cannot copy operand");
110   }
111   MIB.addMBB(TBB);
112 }
113 
114 unsigned MipsInstrInfo::InsertBranch(
115     MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
116     ArrayRef<MachineOperand> Cond, DebugLoc DL) const {
117   // Shouldn't be a fall through.
118   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
119 
120   // # of condition operands:
121   //  Unconditional branches: 0
122   //  Floating point branches: 1 (opc)
123   //  Int BranchZero: 2 (opc, reg)
124   //  Int Branch: 3 (opc, reg0, reg1)
125   assert((Cond.size() <= 3) &&
126          "# of Mips branch conditions must be <= 3!");
127 
128   // Two-way Conditional branch.
129   if (FBB) {
130     BuildCondBr(MBB, TBB, DL, Cond);
131     BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(FBB);
132     return 2;
133   }
134 
135   // One way branch.
136   // Unconditional branch.
137   if (Cond.empty())
138     BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(TBB);
139   else // Conditional branch.
140     BuildCondBr(MBB, TBB, DL, Cond);
141   return 1;
142 }
143 
144 unsigned MipsInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
145   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
146   MachineBasicBlock::reverse_iterator FirstBr;
147   unsigned removed;
148 
149   // Skip all the debug instructions.
150   while (I != REnd && I->isDebugValue())
151     ++I;
152 
153   FirstBr = I;
154 
155   // Up to 2 branches are removed.
156   // Note that indirect branches are not removed.
157   for (removed = 0; I != REnd && removed < 2; ++I, ++removed)
158     if (!getAnalyzableBrOpc(I->getOpcode()))
159       break;
160 
161   MBB.erase(I.base(), FirstBr.base());
162 
163   return removed;
164 }
165 
166 /// ReverseBranchCondition - Return the inverse opcode of the
167 /// specified Branch instruction.
168 bool MipsInstrInfo::ReverseBranchCondition(
169     SmallVectorImpl<MachineOperand> &Cond) const {
170   assert( (Cond.size() && Cond.size() <= 3) &&
171           "Invalid Mips branch condition!");
172   Cond[0].setImm(getOppositeBranchOpc(Cond[0].getImm()));
173   return false;
174 }
175 
176 MipsInstrInfo::BranchType MipsInstrInfo::AnalyzeBranch(
177     MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB,
178     SmallVectorImpl<MachineOperand> &Cond, bool AllowModify,
179     SmallVectorImpl<MachineInstr *> &BranchInstrs) const {
180 
181   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
182 
183   // Skip all the debug instructions.
184   while (I != REnd && I->isDebugValue())
185     ++I;
186 
187   if (I == REnd || !isUnpredicatedTerminator(*I)) {
188     // This block ends with no branches (it just falls through to its succ).
189     // Leave TBB/FBB null.
190     TBB = FBB = nullptr;
191     return BT_NoBranch;
192   }
193 
194   MachineInstr *LastInst = &*I;
195   unsigned LastOpc = LastInst->getOpcode();
196   BranchInstrs.push_back(LastInst);
197 
198   // Not an analyzable branch (e.g., indirect jump).
199   if (!getAnalyzableBrOpc(LastOpc))
200     return LastInst->isIndirectBranch() ? BT_Indirect : BT_None;
201 
202   // Get the second to last instruction in the block.
203   unsigned SecondLastOpc = 0;
204   MachineInstr *SecondLastInst = nullptr;
205 
206   if (++I != REnd) {
207     SecondLastInst = &*I;
208     SecondLastOpc = getAnalyzableBrOpc(SecondLastInst->getOpcode());
209 
210     // Not an analyzable branch (must be an indirect jump).
211     if (isUnpredicatedTerminator(*SecondLastInst) && !SecondLastOpc)
212       return BT_None;
213   }
214 
215   // If there is only one terminator instruction, process it.
216   if (!SecondLastOpc) {
217     // Unconditional branch.
218     if (LastOpc == UncondBrOpc) {
219       TBB = LastInst->getOperand(0).getMBB();
220       return BT_Uncond;
221     }
222 
223     // Conditional branch
224     AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);
225     return BT_Cond;
226   }
227 
228   // If we reached here, there are two branches.
229   // If there are three terminators, we don't know what sort of block this is.
230   if (++I != REnd && isUnpredicatedTerminator(*I))
231     return BT_None;
232 
233   BranchInstrs.insert(BranchInstrs.begin(), SecondLastInst);
234 
235   // If second to last instruction is an unconditional branch,
236   // analyze it and remove the last instruction.
237   if (SecondLastOpc == UncondBrOpc) {
238     // Return if the last instruction cannot be removed.
239     if (!AllowModify)
240       return BT_None;
241 
242     TBB = SecondLastInst->getOperand(0).getMBB();
243     LastInst->eraseFromParent();
244     BranchInstrs.pop_back();
245     return BT_Uncond;
246   }
247 
248   // Conditional branch followed by an unconditional branch.
249   // The last one must be unconditional.
250   if (LastOpc != UncondBrOpc)
251     return BT_None;
252 
253   AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);
254   FBB = LastInst->getOperand(0).getMBB();
255 
256   return BT_CondUncond;
257 }
258 
259 /// Return the corresponding compact (no delay slot) form of a branch.
260 unsigned MipsInstrInfo::getEquivalentCompactForm(
261     const MachineBasicBlock::iterator I) const {
262   unsigned Opcode = I->getOpcode();
263   bool canUseShortMMBranches =
264       Subtarget.inMicroMipsMode() &&
265       (Opcode == Mips::BNE || Opcode == Mips::BEQ) &&
266       I->getOperand(1).getReg() == Subtarget.getABI().GetZeroReg();
267 
268   if (Subtarget.hasMips32r6() || canUseShortMMBranches) {
269     switch (Opcode) {
270     case Mips::B:
271       return Mips::BC;
272     case Mips::BAL:
273       return Mips::BALC;
274     case Mips::BEQ:
275       if (canUseShortMMBranches)
276         return Mips::BEQZC_MM;
277       else
278         return Mips::BEQC;
279     case Mips::BNE:
280       if (canUseShortMMBranches)
281         return Mips::BNEZC_MM;
282       else
283         return Mips::BNEC;
284     case Mips::BGE:
285       return Mips::BGEC;
286     case Mips::BGEU:
287       return Mips::BGEUC;
288     case Mips::BGEZ:
289       return Mips::BGEZC;
290     case Mips::BGTZ:
291       return Mips::BGTZC;
292     case Mips::BLEZ:
293       return Mips::BLEZC;
294     case Mips::BLT:
295       return Mips::BLTC;
296     case Mips::BLTU:
297       return Mips::BLTUC;
298     case Mips::BLTZ:
299       return Mips::BLTZC;
300     default:
301       return 0;
302     }
303   }
304 
305   return 0;
306 }
307 
308 /// Predicate for distingushing between control transfer instructions and all
309 /// other instructions for handling forbidden slots. Consider inline assembly
310 /// as unsafe as well.
311 bool MipsInstrInfo::SafeInForbiddenSlot(const MachineInstr &MI) const {
312   if (MI.isInlineAsm())
313     return false;
314 
315   return (MI.getDesc().TSFlags & MipsII::IsCTI) == 0;
316 
317 }
318 
319 /// Predicate for distingushing instructions that have forbidden slots.
320 bool MipsInstrInfo::HasForbiddenSlot(const MachineInstr &MI) const {
321   return (MI.getDesc().TSFlags & MipsII::HasForbiddenSlot) != 0;
322 }
323 
324 /// Return the number of bytes of code the specified instruction may be.
325 unsigned MipsInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
326   switch (MI->getOpcode()) {
327   default:
328     return MI->getDesc().getSize();
329   case  TargetOpcode::INLINEASM: {       // Inline Asm: Variable size.
330     const MachineFunction *MF = MI->getParent()->getParent();
331     const char *AsmStr = MI->getOperand(0).getSymbolName();
332     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
333   }
334   case Mips::CONSTPOOL_ENTRY:
335     // If this machine instr is a constant pool entry, its size is recorded as
336     // operand #2.
337     return MI->getOperand(2).getImm();
338   }
339 }
340 
341 MachineInstrBuilder
342 MipsInstrInfo::genInstrWithNewOpc(unsigned NewOpc,
343                                   MachineBasicBlock::iterator I) const {
344   MachineInstrBuilder MIB;
345   bool BranchWithZeroOperand = false;
346 
347   // Certain branches have two forms: e.g beq $1, $zero, dst vs beqz $1, dest
348   // Pick the zero form of the branch for readable assembly and for greater
349   // branch distance in non-microMIPS mode.
350   if (I->isBranch() && I->getOperand(1).isReg() &&
351       // FIXME: Certain atomic sequences on mips64 generate 32bit references to
352       // Mips::ZERO, which is incorrect. This test should be updated to use
353       // Subtarget.getABI().GetZeroReg() when those atomic sequences and others
354       // are fixed.
355       (I->getOperand(1).getReg() == Mips::ZERO ||
356        I->getOperand(1).getReg() == Mips::ZERO_64)) {
357     BranchWithZeroOperand = true;
358     switch (NewOpc) {
359     case Mips::BEQC:
360       NewOpc = Mips::BEQZC;
361       break;
362     case Mips::BNEC:
363       NewOpc = Mips::BNEZC;
364       break;
365     case Mips::BGEC:
366       NewOpc = Mips::BGEZC;
367       break;
368     case Mips::BLTC:
369       NewOpc = Mips::BLTZC;
370       break;
371     case Mips::BNEZC_MM:
372     case Mips::BEQZC_MM:
373       break;
374     default:
375       BranchWithZeroOperand = false;
376       break;
377     }
378   }
379 
380   MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), get(NewOpc));
381 
382   for (unsigned J = 0, E = I->getDesc().getNumOperands(); J < E; ++J)
383     if (!(BranchWithZeroOperand && (J == 1)))
384       MIB.addOperand(I->getOperand(J));
385 
386   MIB.setMemRefs(I->memoperands_begin(), I->memoperands_end());
387   return MIB;
388 }
389