xref: /freebsd/contrib/llvm-project/llvm/lib/Target/Mips/MipsInstrInfo.cpp (revision 577b62c2bacc7dfa228591ca3da361e1bc398301)
1 //===- MipsInstrInfo.cpp - Mips Instruction Information -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the Mips implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MipsInstrInfo.h"
14 #include "MCTargetDesc/MipsBaseInfo.h"
15 #include "MCTargetDesc/MipsMCTargetDesc.h"
16 #include "MipsSubtarget.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/TargetOpcodes.h"
25 #include "llvm/CodeGen/TargetSubtargetInfo.h"
26 #include "llvm/IR/DebugInfoMetadata.h"
27 #include "llvm/IR/DebugLoc.h"
28 #include "llvm/MC/MCInstrDesc.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include <cassert>
31 
32 using namespace llvm;
33 
34 #define GET_INSTRINFO_CTOR_DTOR
35 #include "MipsGenInstrInfo.inc"
36 
37 // Pin the vtable to this file.
38 void MipsInstrInfo::anchor() {}
39 
40 MipsInstrInfo::MipsInstrInfo(const MipsSubtarget &STI, unsigned UncondBr)
41     : MipsGenInstrInfo(Mips::ADJCALLSTACKDOWN, Mips::ADJCALLSTACKUP),
42       Subtarget(STI), UncondBrOpc(UncondBr) {}
43 
44 const MipsInstrInfo *MipsInstrInfo::create(MipsSubtarget &STI) {
45   if (STI.inMips16Mode())
46     return createMips16InstrInfo(STI);
47 
48   return createMipsSEInstrInfo(STI);
49 }
50 
51 bool MipsInstrInfo::isZeroImm(const MachineOperand &op) const {
52   return op.isImm() && op.getImm() == 0;
53 }
54 
55 /// insertNoop - If data hazard condition is found insert the target nop
56 /// instruction.
57 void MipsInstrInfo::
58 insertNoop(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
59 {
60   DebugLoc DL;
61   BuildMI(MBB, MI, DL, get(Mips::NOP));
62 }
63 
64 MachineInstrBuilder MipsInstrInfo::insertNop(MachineBasicBlock &MBB,
65                                              MachineBasicBlock::iterator MI,
66                                              DebugLoc DL) const {
67   assert(!Subtarget.inMips16Mode() &&
68          "insertNop does not support MIPS16e mode at this time");
69   const unsigned MMOpc =
70       Subtarget.hasMips32r6() ? Mips::SLL_MMR6 : Mips::SLL_MM;
71   const unsigned Opc = Subtarget.inMicroMipsMode() ? MMOpc : Mips::SLL;
72   return BuildMI(MBB, MI, DL, get(Opc), Mips::ZERO)
73       .addReg(Mips::ZERO)
74       .addImm(0);
75 }
76 
77 MachineMemOperand *
78 MipsInstrInfo::GetMemOperand(MachineBasicBlock &MBB, int FI,
79                              MachineMemOperand::Flags Flags) const {
80   MachineFunction &MF = *MBB.getParent();
81   MachineFrameInfo &MFI = MF.getFrameInfo();
82 
83   return MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(MF, FI),
84                                  Flags, MFI.getObjectSize(FI),
85                                  MFI.getObjectAlign(FI));
86 }
87 
88 //===----------------------------------------------------------------------===//
89 // Branch Analysis
90 //===----------------------------------------------------------------------===//
91 
92 void MipsInstrInfo::AnalyzeCondBr(const MachineInstr *Inst, unsigned Opc,
93                                   MachineBasicBlock *&BB,
94                                   SmallVectorImpl<MachineOperand> &Cond) const {
95   assert(getAnalyzableBrOpc(Opc) && "Not an analyzable branch");
96   int NumOp = Inst->getNumExplicitOperands();
97 
98   // for both int and fp branches, the last explicit operand is the
99   // MBB.
100   BB = Inst->getOperand(NumOp-1).getMBB();
101   Cond.push_back(MachineOperand::CreateImm(Opc));
102 
103   for (int i = 0; i < NumOp-1; i++)
104     Cond.push_back(Inst->getOperand(i));
105 }
106 
107 bool MipsInstrInfo::analyzeBranch(MachineBasicBlock &MBB,
108                                   MachineBasicBlock *&TBB,
109                                   MachineBasicBlock *&FBB,
110                                   SmallVectorImpl<MachineOperand> &Cond,
111                                   bool AllowModify) const {
112   SmallVector<MachineInstr*, 2> BranchInstrs;
113   BranchType BT = analyzeBranch(MBB, TBB, FBB, Cond, AllowModify, BranchInstrs);
114 
115   return (BT == BT_None) || (BT == BT_Indirect);
116 }
117 
118 void MipsInstrInfo::BuildCondBr(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
119                                 const DebugLoc &DL,
120                                 ArrayRef<MachineOperand> Cond) const {
121   unsigned Opc = Cond[0].getImm();
122   const MCInstrDesc &MCID = get(Opc);
123   MachineInstrBuilder MIB = BuildMI(&MBB, DL, MCID);
124 
125   for (unsigned i = 1; i < Cond.size(); ++i) {
126     assert((Cond[i].isImm() || Cond[i].isReg()) &&
127            "Cannot copy operand for conditional branch!");
128     MIB.add(Cond[i]);
129   }
130   MIB.addMBB(TBB);
131 }
132 
133 unsigned MipsInstrInfo::insertBranch(MachineBasicBlock &MBB,
134                                      MachineBasicBlock *TBB,
135                                      MachineBasicBlock *FBB,
136                                      ArrayRef<MachineOperand> Cond,
137                                      const DebugLoc &DL,
138                                      int *BytesAdded) const {
139   // Shouldn't be a fall through.
140   assert(TBB && "insertBranch must not be told to insert a fallthrough");
141   assert(!BytesAdded && "code size not handled");
142 
143   // # of condition operands:
144   //  Unconditional branches: 0
145   //  Floating point branches: 1 (opc)
146   //  Int BranchZero: 2 (opc, reg)
147   //  Int Branch: 3 (opc, reg0, reg1)
148   assert((Cond.size() <= 3) &&
149          "# of Mips branch conditions must be <= 3!");
150 
151   // Two-way Conditional branch.
152   if (FBB) {
153     BuildCondBr(MBB, TBB, DL, Cond);
154     BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(FBB);
155     return 2;
156   }
157 
158   // One way branch.
159   // Unconditional branch.
160   if (Cond.empty())
161     BuildMI(&MBB, DL, get(UncondBrOpc)).addMBB(TBB);
162   else // Conditional branch.
163     BuildCondBr(MBB, TBB, DL, Cond);
164   return 1;
165 }
166 
167 unsigned MipsInstrInfo::removeBranch(MachineBasicBlock &MBB,
168                                      int *BytesRemoved) const {
169   assert(!BytesRemoved && "code size not handled");
170 
171   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
172   unsigned removed = 0;
173 
174   // Up to 2 branches are removed.
175   // Note that indirect branches are not removed.
176   while (I != REnd && removed < 2) {
177     // Skip past debug instructions.
178     if (I->isDebugInstr()) {
179       ++I;
180       continue;
181     }
182     if (!getAnalyzableBrOpc(I->getOpcode()))
183       break;
184     // Remove the branch.
185     I->eraseFromParent();
186     I = MBB.rbegin();
187     ++removed;
188   }
189 
190   return removed;
191 }
192 
193 /// reverseBranchCondition - Return the inverse opcode of the
194 /// specified Branch instruction.
195 bool MipsInstrInfo::reverseBranchCondition(
196     SmallVectorImpl<MachineOperand> &Cond) const {
197   assert( (Cond.size() && Cond.size() <= 3) &&
198           "Invalid Mips branch condition!");
199   Cond[0].setImm(getOppositeBranchOpc(Cond[0].getImm()));
200   return false;
201 }
202 
203 MipsInstrInfo::BranchType MipsInstrInfo::analyzeBranch(
204     MachineBasicBlock &MBB, MachineBasicBlock *&TBB, MachineBasicBlock *&FBB,
205     SmallVectorImpl<MachineOperand> &Cond, bool AllowModify,
206     SmallVectorImpl<MachineInstr *> &BranchInstrs) const {
207   MachineBasicBlock::reverse_iterator I = MBB.rbegin(), REnd = MBB.rend();
208 
209   // Skip all the debug instructions.
210   while (I != REnd && I->isDebugInstr())
211     ++I;
212 
213   if (I == REnd || !isUnpredicatedTerminator(*I)) {
214     // This block ends with no branches (it just falls through to its succ).
215     // Leave TBB/FBB null.
216     TBB = FBB = nullptr;
217     return BT_NoBranch;
218   }
219 
220   MachineInstr *LastInst = &*I;
221   unsigned LastOpc = LastInst->getOpcode();
222   BranchInstrs.push_back(LastInst);
223 
224   // Not an analyzable branch (e.g., indirect jump).
225   if (!getAnalyzableBrOpc(LastOpc))
226     return LastInst->isIndirectBranch() ? BT_Indirect : BT_None;
227 
228   // Get the second to last instruction in the block.
229   unsigned SecondLastOpc = 0;
230   MachineInstr *SecondLastInst = nullptr;
231 
232   // Skip past any debug instruction to see if the second last actual
233   // is a branch.
234   ++I;
235   while (I != REnd && I->isDebugInstr())
236     ++I;
237 
238   if (I != REnd) {
239     SecondLastInst = &*I;
240     SecondLastOpc = getAnalyzableBrOpc(SecondLastInst->getOpcode());
241 
242     // Not an analyzable branch (must be an indirect jump).
243     if (isUnpredicatedTerminator(*SecondLastInst) && !SecondLastOpc)
244       return BT_None;
245   }
246 
247   // If there is only one terminator instruction, process it.
248   if (!SecondLastOpc) {
249     // Unconditional branch.
250     if (LastInst->isUnconditionalBranch()) {
251       TBB = LastInst->getOperand(0).getMBB();
252       return BT_Uncond;
253     }
254 
255     // Conditional branch
256     AnalyzeCondBr(LastInst, LastOpc, TBB, Cond);
257     return BT_Cond;
258   }
259 
260   // If we reached here, there are two branches.
261   // If there are three terminators, we don't know what sort of block this is.
262   if (++I != REnd && isUnpredicatedTerminator(*I))
263     return BT_None;
264 
265   BranchInstrs.insert(BranchInstrs.begin(), SecondLastInst);
266 
267   // If second to last instruction is an unconditional branch,
268   // analyze it and remove the last instruction.
269   if (SecondLastInst->isUnconditionalBranch()) {
270     // Return if the last instruction cannot be removed.
271     if (!AllowModify)
272       return BT_None;
273 
274     TBB = SecondLastInst->getOperand(0).getMBB();
275     LastInst->eraseFromParent();
276     BranchInstrs.pop_back();
277     return BT_Uncond;
278   }
279 
280   // Conditional branch followed by an unconditional branch.
281   // The last one must be unconditional.
282   if (!LastInst->isUnconditionalBranch())
283     return BT_None;
284 
285   AnalyzeCondBr(SecondLastInst, SecondLastOpc, TBB, Cond);
286   FBB = LastInst->getOperand(0).getMBB();
287 
288   return BT_CondUncond;
289 }
290 
291 bool MipsInstrInfo::isBranchOffsetInRange(unsigned BranchOpc,
292                                           int64_t BrOffset) const {
293   switch (BranchOpc) {
294   case Mips::B:
295   case Mips::BAL:
296   case Mips::BAL_BR:
297   case Mips::BAL_BR_MM:
298   case Mips::BC1F:
299   case Mips::BC1FL:
300   case Mips::BC1T:
301   case Mips::BC1TL:
302   case Mips::BEQ:     case Mips::BEQ64:
303   case Mips::BEQL:
304   case Mips::BGEZ:    case Mips::BGEZ64:
305   case Mips::BGEZL:
306   case Mips::BGEZAL:
307   case Mips::BGEZALL:
308   case Mips::BGTZ:    case Mips::BGTZ64:
309   case Mips::BGTZL:
310   case Mips::BLEZ:    case Mips::BLEZ64:
311   case Mips::BLEZL:
312   case Mips::BLTZ:    case Mips::BLTZ64:
313   case Mips::BLTZL:
314   case Mips::BLTZAL:
315   case Mips::BLTZALL:
316   case Mips::BNE:     case Mips::BNE64:
317   case Mips::BNEL:
318     return isInt<18>(BrOffset);
319 
320   // microMIPSr3 branches
321   case Mips::B_MM:
322   case Mips::BC1F_MM:
323   case Mips::BC1T_MM:
324   case Mips::BEQ_MM:
325   case Mips::BGEZ_MM:
326   case Mips::BGEZAL_MM:
327   case Mips::BGTZ_MM:
328   case Mips::BLEZ_MM:
329   case Mips::BLTZ_MM:
330   case Mips::BLTZAL_MM:
331   case Mips::BNE_MM:
332   case Mips::BEQZC_MM:
333   case Mips::BNEZC_MM:
334     return isInt<17>(BrOffset);
335 
336   // microMIPSR3 short branches.
337   case Mips::B16_MM:
338     return isInt<11>(BrOffset);
339 
340   case Mips::BEQZ16_MM:
341   case Mips::BNEZ16_MM:
342     return isInt<8>(BrOffset);
343 
344   // MIPSR6 branches.
345   case Mips::BALC:
346   case Mips::BC:
347     return isInt<28>(BrOffset);
348 
349   case Mips::BC1EQZ:
350   case Mips::BC1NEZ:
351   case Mips::BC2EQZ:
352   case Mips::BC2NEZ:
353   case Mips::BEQC:   case Mips::BEQC64:
354   case Mips::BNEC:   case Mips::BNEC64:
355   case Mips::BGEC:   case Mips::BGEC64:
356   case Mips::BGEUC:  case Mips::BGEUC64:
357   case Mips::BGEZC:  case Mips::BGEZC64:
358   case Mips::BGTZC:  case Mips::BGTZC64:
359   case Mips::BLEZC:  case Mips::BLEZC64:
360   case Mips::BLTC:   case Mips::BLTC64:
361   case Mips::BLTUC:  case Mips::BLTUC64:
362   case Mips::BLTZC:  case Mips::BLTZC64:
363   case Mips::BNVC:
364   case Mips::BOVC:
365   case Mips::BGEZALC:
366   case Mips::BEQZALC:
367   case Mips::BGTZALC:
368   case Mips::BLEZALC:
369   case Mips::BLTZALC:
370   case Mips::BNEZALC:
371     return isInt<18>(BrOffset);
372 
373   case Mips::BEQZC:  case Mips::BEQZC64:
374   case Mips::BNEZC:  case Mips::BNEZC64:
375     return isInt<23>(BrOffset);
376 
377   // microMIPSR6 branches
378   case Mips::BC16_MMR6:
379     return isInt<11>(BrOffset);
380 
381   case Mips::BEQZC16_MMR6:
382   case Mips::BNEZC16_MMR6:
383     return isInt<8>(BrOffset);
384 
385   case Mips::BALC_MMR6:
386   case Mips::BC_MMR6:
387     return isInt<27>(BrOffset);
388 
389   case Mips::BC1EQZC_MMR6:
390   case Mips::BC1NEZC_MMR6:
391   case Mips::BC2EQZC_MMR6:
392   case Mips::BC2NEZC_MMR6:
393   case Mips::BGEZALC_MMR6:
394   case Mips::BEQZALC_MMR6:
395   case Mips::BGTZALC_MMR6:
396   case Mips::BLEZALC_MMR6:
397   case Mips::BLTZALC_MMR6:
398   case Mips::BNEZALC_MMR6:
399   case Mips::BNVC_MMR6:
400   case Mips::BOVC_MMR6:
401     return isInt<17>(BrOffset);
402 
403   case Mips::BEQC_MMR6:
404   case Mips::BNEC_MMR6:
405   case Mips::BGEC_MMR6:
406   case Mips::BGEUC_MMR6:
407   case Mips::BGEZC_MMR6:
408   case Mips::BGTZC_MMR6:
409   case Mips::BLEZC_MMR6:
410   case Mips::BLTC_MMR6:
411   case Mips::BLTUC_MMR6:
412   case Mips::BLTZC_MMR6:
413     return isInt<18>(BrOffset);
414 
415   case Mips::BEQZC_MMR6:
416   case Mips::BNEZC_MMR6:
417     return isInt<23>(BrOffset);
418 
419   // DSP branches.
420   case Mips::BPOSGE32:
421     return isInt<18>(BrOffset);
422   case Mips::BPOSGE32_MM:
423   case Mips::BPOSGE32C_MMR3:
424     return isInt<17>(BrOffset);
425 
426   // cnMIPS branches.
427   case Mips::BBIT0:
428   case Mips::BBIT032:
429   case Mips::BBIT1:
430   case Mips::BBIT132:
431     return isInt<18>(BrOffset);
432 
433   // MSA branches.
434   case Mips::BZ_B:
435   case Mips::BZ_H:
436   case Mips::BZ_W:
437   case Mips::BZ_D:
438   case Mips::BZ_V:
439   case Mips::BNZ_B:
440   case Mips::BNZ_H:
441   case Mips::BNZ_W:
442   case Mips::BNZ_D:
443   case Mips::BNZ_V:
444     return isInt<18>(BrOffset);
445   }
446 
447   llvm_unreachable("Unknown branch instruction!");
448 }
449 
450 /// Return the corresponding compact (no delay slot) form of a branch.
451 unsigned MipsInstrInfo::getEquivalentCompactForm(
452     const MachineBasicBlock::iterator I) const {
453   unsigned Opcode = I->getOpcode();
454   bool canUseShortMicroMipsCTI = false;
455 
456   if (Subtarget.inMicroMipsMode()) {
457     switch (Opcode) {
458     case Mips::BNE:
459     case Mips::BNE_MM:
460     case Mips::BEQ:
461     case Mips::BEQ_MM:
462     // microMIPS has NE,EQ branches that do not have delay slots provided one
463     // of the operands is zero.
464       if (I->getOperand(1).getReg() == Subtarget.getABI().GetZeroReg())
465         canUseShortMicroMipsCTI = true;
466       break;
467     // For microMIPS the PseudoReturn and PseudoIndirectBranch are always
468     // expanded to JR_MM, so they can be replaced with JRC16_MM.
469     case Mips::JR:
470     case Mips::PseudoReturn:
471     case Mips::PseudoIndirectBranch:
472       canUseShortMicroMipsCTI = true;
473       break;
474     }
475   }
476 
477   // MIPSR6 forbids both operands being the zero register.
478   if (Subtarget.hasMips32r6() && (I->getNumOperands() > 1) &&
479       (I->getOperand(0).isReg() &&
480        (I->getOperand(0).getReg() == Mips::ZERO ||
481         I->getOperand(0).getReg() == Mips::ZERO_64)) &&
482       (I->getOperand(1).isReg() &&
483        (I->getOperand(1).getReg() == Mips::ZERO ||
484         I->getOperand(1).getReg() == Mips::ZERO_64)))
485     return 0;
486 
487   if (Subtarget.hasMips32r6() || canUseShortMicroMipsCTI) {
488     switch (Opcode) {
489     case Mips::B:
490       return Mips::BC;
491     case Mips::BAL:
492       return Mips::BALC;
493     case Mips::BEQ:
494     case Mips::BEQ_MM:
495       if (canUseShortMicroMipsCTI)
496         return Mips::BEQZC_MM;
497       else if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
498         return 0;
499       return Mips::BEQC;
500     case Mips::BNE:
501     case Mips::BNE_MM:
502       if (canUseShortMicroMipsCTI)
503         return Mips::BNEZC_MM;
504       else if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
505         return 0;
506       return Mips::BNEC;
507     case Mips::BGE:
508       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
509         return 0;
510       return Mips::BGEC;
511     case Mips::BGEU:
512       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
513         return 0;
514       return Mips::BGEUC;
515     case Mips::BGEZ:
516       return Mips::BGEZC;
517     case Mips::BGTZ:
518       return Mips::BGTZC;
519     case Mips::BLEZ:
520       return Mips::BLEZC;
521     case Mips::BLT:
522       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
523         return 0;
524       return Mips::BLTC;
525     case Mips::BLTU:
526       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
527         return 0;
528       return Mips::BLTUC;
529     case Mips::BLTZ:
530       return Mips::BLTZC;
531     case Mips::BEQ64:
532       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
533         return 0;
534       return Mips::BEQC64;
535     case Mips::BNE64:
536       if (I->getOperand(0).getReg() == I->getOperand(1).getReg())
537         return 0;
538       return Mips::BNEC64;
539     case Mips::BGTZ64:
540       return Mips::BGTZC64;
541     case Mips::BGEZ64:
542       return Mips::BGEZC64;
543     case Mips::BLTZ64:
544       return Mips::BLTZC64;
545     case Mips::BLEZ64:
546       return Mips::BLEZC64;
547     // For MIPSR6, the instruction 'jic' can be used for these cases. Some
548     // tools will accept 'jrc reg' as an alias for 'jic 0, $reg'.
549     case Mips::JR:
550     case Mips::PseudoIndirectBranchR6:
551     case Mips::PseudoReturn:
552     case Mips::TAILCALLR6REG:
553       if (canUseShortMicroMipsCTI)
554         return Mips::JRC16_MM;
555       return Mips::JIC;
556     case Mips::JALRPseudo:
557       return Mips::JIALC;
558     case Mips::JR64:
559     case Mips::PseudoIndirectBranch64R6:
560     case Mips::PseudoReturn64:
561     case Mips::TAILCALL64R6REG:
562       return Mips::JIC64;
563     case Mips::JALR64Pseudo:
564       return Mips::JIALC64;
565     default:
566       return 0;
567     }
568   }
569 
570   return 0;
571 }
572 
573 /// Predicate for distingushing between control transfer instructions and all
574 /// other instructions for handling forbidden slots. Consider inline assembly
575 /// as unsafe as well.
576 bool MipsInstrInfo::SafeInForbiddenSlot(const MachineInstr &MI) const {
577   if (MI.isInlineAsm())
578     return false;
579 
580   return (MI.getDesc().TSFlags & MipsII::IsCTI) == 0;
581 }
582 
583 bool MipsInstrInfo::SafeInFPUDelaySlot(const MachineInstr &MIInSlot,
584                                        const MachineInstr &FPUMI) const {
585   if (MIInSlot.isInlineAsm())
586     return false;
587 
588   if (HasFPUDelaySlot(MIInSlot))
589     return false;
590 
591   switch (MIInSlot.getOpcode()) {
592   case Mips::BC1F:
593   case Mips::BC1FL:
594   case Mips::BC1T:
595   case Mips::BC1TL:
596     return false;
597   }
598 
599   for (const MachineOperand &Op : FPUMI.defs()) {
600     if (!Op.isReg())
601       continue;
602 
603     bool Reads, Writes;
604     std::tie(Reads, Writes) = MIInSlot.readsWritesVirtualRegister(Op.getReg());
605 
606     if (Reads || Writes)
607       return false;
608   }
609 
610   return true;
611 }
612 
613 /// Predicate for distinguishing instructions that are hazardous in a load delay
614 /// slot. Consider inline assembly as unsafe as well.
615 bool MipsInstrInfo::SafeInLoadDelaySlot(const MachineInstr &MIInSlot,
616                                         const MachineInstr &LoadMI) const {
617   if (MIInSlot.isInlineAsm())
618     return false;
619 
620   return !llvm::any_of(LoadMI.defs(), [&](const MachineOperand &Op) {
621     return Op.isReg() && MIInSlot.readsRegister(Op.getReg());
622   });
623 }
624 
625 /// Predicate for distingushing instructions that have forbidden slots.
626 bool MipsInstrInfo::HasForbiddenSlot(const MachineInstr &MI) const {
627   return (MI.getDesc().TSFlags & MipsII::HasForbiddenSlot) != 0;
628 }
629 
630 /// Predicate for distingushing instructions that have FPU delay slots.
631 bool MipsInstrInfo::HasFPUDelaySlot(const MachineInstr &MI) const {
632   switch (MI.getOpcode()) {
633   case Mips::MTC1:
634   case Mips::MFC1:
635   case Mips::MTC1_D64:
636   case Mips::MFC1_D64:
637   case Mips::DMTC1:
638   case Mips::DMFC1:
639   case Mips::FCMP_S32:
640   case Mips::FCMP_D32:
641   case Mips::FCMP_D64:
642     return true;
643 
644   default:
645     return false;
646   }
647 }
648 
649 /// Predicate for distingushing instructions that have load delay slots.
650 bool MipsInstrInfo::HasLoadDelaySlot(const MachineInstr &MI) const {
651   switch (MI.getOpcode()) {
652   case Mips::LB:
653   case Mips::LBu:
654   case Mips::LH:
655   case Mips::LHu:
656   case Mips::LW:
657   case Mips::LWR:
658   case Mips::LWL:
659     return true;
660   default:
661     return false;
662   }
663 }
664 
665 /// Return the number of bytes of code the specified instruction may be.
666 unsigned MipsInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
667   switch (MI.getOpcode()) {
668   default:
669     return MI.getDesc().getSize();
670   case  TargetOpcode::INLINEASM:
671   case  TargetOpcode::INLINEASM_BR: {       // Inline Asm: Variable size.
672     const MachineFunction *MF = MI.getParent()->getParent();
673     const char *AsmStr = MI.getOperand(0).getSymbolName();
674     return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo());
675   }
676   case Mips::CONSTPOOL_ENTRY:
677     // If this machine instr is a constant pool entry, its size is recorded as
678     // operand #2.
679     return MI.getOperand(2).getImm();
680   }
681 }
682 
683 MachineInstrBuilder
684 MipsInstrInfo::genInstrWithNewOpc(unsigned NewOpc,
685                                   MachineBasicBlock::iterator I) const {
686   MachineInstrBuilder MIB;
687 
688   // Certain branches have two forms: e.g beq $1, $zero, dest vs beqz $1, dest
689   // Pick the zero form of the branch for readable assembly and for greater
690   // branch distance in non-microMIPS mode.
691   // Additional MIPSR6 does not permit the use of register $zero for compact
692   // branches.
693   // FIXME: Certain atomic sequences on mips64 generate 32bit references to
694   // Mips::ZERO, which is incorrect. This test should be updated to use
695   // Subtarget.getABI().GetZeroReg() when those atomic sequences and others
696   // are fixed.
697   int ZeroOperandPosition = -1;
698   bool BranchWithZeroOperand = false;
699   if (I->isBranch() && !I->isPseudo()) {
700     auto TRI = I->getParent()->getParent()->getSubtarget().getRegisterInfo();
701     ZeroOperandPosition = I->findRegisterUseOperandIdx(Mips::ZERO, false, TRI);
702     BranchWithZeroOperand = ZeroOperandPosition != -1;
703   }
704 
705   if (BranchWithZeroOperand) {
706     switch (NewOpc) {
707     case Mips::BEQC:
708       NewOpc = Mips::BEQZC;
709       break;
710     case Mips::BNEC:
711       NewOpc = Mips::BNEZC;
712       break;
713     case Mips::BGEC:
714       NewOpc = Mips::BGEZC;
715       break;
716     case Mips::BLTC:
717       NewOpc = Mips::BLTZC;
718       break;
719     case Mips::BEQC64:
720       NewOpc = Mips::BEQZC64;
721       break;
722     case Mips::BNEC64:
723       NewOpc = Mips::BNEZC64;
724       break;
725     }
726   }
727 
728   MIB = BuildMI(*I->getParent(), I, I->getDebugLoc(), get(NewOpc));
729 
730   // For MIPSR6 JI*C requires an immediate 0 as an operand, JIALC(64) an
731   // immediate 0 as an operand and requires the removal of it's implicit-def %ra
732   // implicit operand as copying the implicit operations of the instructio we're
733   // looking at will give us the correct flags.
734   if (NewOpc == Mips::JIC || NewOpc == Mips::JIALC || NewOpc == Mips::JIC64 ||
735       NewOpc == Mips::JIALC64) {
736 
737     if (NewOpc == Mips::JIALC || NewOpc == Mips::JIALC64)
738       MIB->removeOperand(0);
739 
740     for (unsigned J = 0, E = I->getDesc().getNumOperands(); J < E; ++J) {
741       MIB.add(I->getOperand(J));
742     }
743 
744     MIB.addImm(0);
745 
746     // If I has an MCSymbol operand (used by asm printer, to emit R_MIPS_JALR),
747     // add it to the new instruction.
748     for (unsigned J = I->getDesc().getNumOperands(), E = I->getNumOperands();
749          J < E; ++J) {
750       const MachineOperand &MO = I->getOperand(J);
751       if (MO.isMCSymbol() && (MO.getTargetFlags() & MipsII::MO_JALR))
752         MIB.addSym(MO.getMCSymbol(), MipsII::MO_JALR);
753     }
754 
755 
756   } else {
757     for (unsigned J = 0, E = I->getDesc().getNumOperands(); J < E; ++J) {
758       if (BranchWithZeroOperand && (unsigned)ZeroOperandPosition == J)
759         continue;
760 
761       MIB.add(I->getOperand(J));
762     }
763   }
764 
765   MIB.copyImplicitOps(*I);
766   MIB.cloneMemRefs(*I);
767   return MIB;
768 }
769 
770 bool MipsInstrInfo::findCommutedOpIndices(const MachineInstr &MI,
771                                           unsigned &SrcOpIdx1,
772                                           unsigned &SrcOpIdx2) const {
773   assert(!MI.isBundle() &&
774          "TargetInstrInfo::findCommutedOpIndices() can't handle bundles");
775 
776   const MCInstrDesc &MCID = MI.getDesc();
777   if (!MCID.isCommutable())
778     return false;
779 
780   switch (MI.getOpcode()) {
781   case Mips::DPADD_U_H:
782   case Mips::DPADD_U_W:
783   case Mips::DPADD_U_D:
784   case Mips::DPADD_S_H:
785   case Mips::DPADD_S_W:
786   case Mips::DPADD_S_D:
787     // The first operand is both input and output, so it should not commute
788     if (!fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3))
789       return false;
790 
791     if (!MI.getOperand(SrcOpIdx1).isReg() || !MI.getOperand(SrcOpIdx2).isReg())
792       return false;
793     return true;
794   }
795   return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2);
796 }
797 
798 // ins, ext, dext*, dins have the following constraints:
799 // X <= pos      <  Y
800 // X <  size     <= Y
801 // X <  pos+size <= Y
802 //
803 // dinsm and dinsu have the following constraints:
804 // X <= pos      <  Y
805 // X <= size     <= Y
806 // X <  pos+size <= Y
807 //
808 // The callee of verifyInsExtInstruction however gives the bounds of
809 // dins[um] like the other (d)ins (d)ext(um) instructions, so that this
810 // function doesn't have to vary it's behaviour based on the instruction
811 // being checked.
812 static bool verifyInsExtInstruction(const MachineInstr &MI, StringRef &ErrInfo,
813                                     const int64_t PosLow, const int64_t PosHigh,
814                                     const int64_t SizeLow,
815                                     const int64_t SizeHigh,
816                                     const int64_t BothLow,
817                                     const int64_t BothHigh) {
818   MachineOperand MOPos = MI.getOperand(2);
819   if (!MOPos.isImm()) {
820     ErrInfo = "Position is not an immediate!";
821     return false;
822   }
823   int64_t Pos = MOPos.getImm();
824   if (!((PosLow <= Pos) && (Pos < PosHigh))) {
825     ErrInfo = "Position operand is out of range!";
826     return false;
827   }
828 
829   MachineOperand MOSize = MI.getOperand(3);
830   if (!MOSize.isImm()) {
831     ErrInfo = "Size operand is not an immediate!";
832     return false;
833   }
834   int64_t Size = MOSize.getImm();
835   if (!((SizeLow < Size) && (Size <= SizeHigh))) {
836     ErrInfo = "Size operand is out of range!";
837     return false;
838   }
839 
840   if (!((BothLow < (Pos + Size)) && ((Pos + Size) <= BothHigh))) {
841     ErrInfo = "Position + Size is out of range!";
842     return false;
843   }
844 
845   return true;
846 }
847 
848 //  Perform target specific instruction verification.
849 bool MipsInstrInfo::verifyInstruction(const MachineInstr &MI,
850                                       StringRef &ErrInfo) const {
851   // Verify that ins and ext instructions are well formed.
852   switch (MI.getOpcode()) {
853     case Mips::EXT:
854     case Mips::EXT_MM:
855     case Mips::INS:
856     case Mips::INS_MM:
857     case Mips::DINS:
858       return verifyInsExtInstruction(MI, ErrInfo, 0, 32, 0, 32, 0, 32);
859     case Mips::DINSM:
860       // The ISA spec has a subtle difference between dinsm and dextm
861       // in that it says:
862       // 2 <= size <= 64 for 'dinsm' but 'dextm' has 32 < size <= 64.
863       // To make the bounds checks similar, the range 1 < size <= 64 is checked
864       // for 'dinsm'.
865       return verifyInsExtInstruction(MI, ErrInfo, 0, 32, 1, 64, 32, 64);
866     case Mips::DINSU:
867       // The ISA spec has a subtle difference between dinsu and dextu in that
868       // the size range of dinsu is specified as 1 <= size <= 32 whereas size
869       // for dextu is 0 < size <= 32. The range checked for dinsu here is
870       // 0 < size <= 32, which is equivalent and similar to dextu.
871       return verifyInsExtInstruction(MI, ErrInfo, 32, 64, 0, 32, 32, 64);
872     case Mips::DEXT:
873       return verifyInsExtInstruction(MI, ErrInfo, 0, 32, 0, 32, 0, 63);
874     case Mips::DEXTM:
875       return verifyInsExtInstruction(MI, ErrInfo, 0, 32, 32, 64, 32, 64);
876     case Mips::DEXTU:
877       return verifyInsExtInstruction(MI, ErrInfo, 32, 64, 0, 32, 32, 64);
878     case Mips::TAILCALLREG:
879     case Mips::PseudoIndirectBranch:
880     case Mips::JR:
881     case Mips::JR64:
882     case Mips::JALR:
883     case Mips::JALR64:
884     case Mips::JALRPseudo:
885       if (!Subtarget.useIndirectJumpsHazard())
886         return true;
887 
888       ErrInfo = "invalid instruction when using jump guards!";
889       return false;
890     default:
891       return true;
892   }
893 
894   return true;
895 }
896 
897 std::pair<unsigned, unsigned>
898 MipsInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
899   return std::make_pair(TF, 0u);
900 }
901 
902 ArrayRef<std::pair<unsigned, const char*>>
903 MipsInstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
904  using namespace MipsII;
905 
906  static const std::pair<unsigned, const char*> Flags[] = {
907     {MO_GOT,          "mips-got"},
908     {MO_GOT_CALL,     "mips-got-call"},
909     {MO_GPREL,        "mips-gprel"},
910     {MO_ABS_HI,       "mips-abs-hi"},
911     {MO_ABS_LO,       "mips-abs-lo"},
912     {MO_TLSGD,        "mips-tlsgd"},
913     {MO_TLSLDM,       "mips-tlsldm"},
914     {MO_DTPREL_HI,    "mips-dtprel-hi"},
915     {MO_DTPREL_LO,    "mips-dtprel-lo"},
916     {MO_GOTTPREL,     "mips-gottprel"},
917     {MO_TPREL_HI,     "mips-tprel-hi"},
918     {MO_TPREL_LO,     "mips-tprel-lo"},
919     {MO_GPOFF_HI,     "mips-gpoff-hi"},
920     {MO_GPOFF_LO,     "mips-gpoff-lo"},
921     {MO_GOT_DISP,     "mips-got-disp"},
922     {MO_GOT_PAGE,     "mips-got-page"},
923     {MO_GOT_OFST,     "mips-got-ofst"},
924     {MO_HIGHER,       "mips-higher"},
925     {MO_HIGHEST,      "mips-highest"},
926     {MO_GOT_HI16,     "mips-got-hi16"},
927     {MO_GOT_LO16,     "mips-got-lo16"},
928     {MO_CALL_HI16,    "mips-call-hi16"},
929     {MO_CALL_LO16,    "mips-call-lo16"},
930     {MO_JALR,         "mips-jalr"}
931   };
932   return makeArrayRef(Flags);
933 }
934 
935 Optional<ParamLoadedValue>
936 MipsInstrInfo::describeLoadedValue(const MachineInstr &MI, Register Reg) const {
937   DIExpression *Expr =
938       DIExpression::get(MI.getMF()->getFunction().getContext(), {});
939 
940   // TODO: Special MIPS instructions that need to be described separately.
941   if (auto RegImm = isAddImmediate(MI, Reg)) {
942     Register SrcReg = RegImm->Reg;
943     int64_t Offset = RegImm->Imm;
944     // When SrcReg is $zero, treat loaded value as immediate only.
945     // Ex. $a2 = ADDiu $zero, 10
946     if (SrcReg == Mips::ZERO || SrcReg == Mips::ZERO_64) {
947       return ParamLoadedValue(MI.getOperand(2), Expr);
948     }
949     Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset, Offset);
950     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
951   } else if (auto DestSrc = isCopyInstr(MI)) {
952     const MachineFunction *MF = MI.getMF();
953     const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
954     Register DestReg = DestSrc->Destination->getReg();
955     // TODO: Handle cases where the Reg is sub- or super-register of the
956     // DestReg.
957     if (TRI->isSuperRegister(Reg, DestReg) || TRI->isSubRegister(Reg, DestReg))
958       return None;
959   }
960 
961   return TargetInstrInfo::describeLoadedValue(MI, Reg);
962 }
963 
964 Optional<RegImmPair> MipsInstrInfo::isAddImmediate(const MachineInstr &MI,
965                                                    Register Reg) const {
966   // TODO: Handle cases where Reg is a super- or sub-register of the
967   // destination register.
968   const MachineOperand &Op0 = MI.getOperand(0);
969   if (!Op0.isReg() || Reg != Op0.getReg())
970     return None;
971 
972   switch (MI.getOpcode()) {
973   case Mips::ADDiu:
974   case Mips::DADDiu: {
975     const MachineOperand &Dop = MI.getOperand(0);
976     const MachineOperand &Sop1 = MI.getOperand(1);
977     const MachineOperand &Sop2 = MI.getOperand(2);
978     // Value is sum of register and immediate. Immediate value could be
979     // global string address which is not supported.
980     if (Dop.isReg() && Sop1.isReg() && Sop2.isImm())
981       return RegImmPair{Sop1.getReg(), Sop2.getImm()};
982     // TODO: Handle case where Sop1 is a frame-index.
983   }
984   }
985   return None;
986 }
987