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