Remove the need to cache the subtarget in the Mips TargetRegisterInfo
[oota-llvm.git] / lib / Target / Mips / Mips16InstrInfo.cpp
1 //===-- Mips16InstrInfo.cpp - Mips16 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 Mips16 implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "Mips16InstrInfo.h"
14 #include "InstPrinter/MipsInstPrinter.h"
15 #include "MipsMachineFunction.h"
16 #include "MipsTargetMachine.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/RegisterScavenging.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include <cctype>
28
29 using namespace llvm;
30
31 #define DEBUG_TYPE "mips16-instrinfo"
32
33 Mips16InstrInfo::Mips16InstrInfo(const MipsSubtarget &STI)
34     : MipsInstrInfo(STI, Mips::Bimm16), RI() {}
35
36 const MipsRegisterInfo &Mips16InstrInfo::getRegisterInfo() const {
37   return RI;
38 }
39
40 /// isLoadFromStackSlot - If the specified machine instruction is a direct
41 /// load from a stack slot, return the virtual or physical register number of
42 /// the destination along with the FrameIndex of the loaded stack slot.  If
43 /// not, return 0.  This predicate must return 0 if the instruction has
44 /// any side effects other than loading from the stack slot.
45 unsigned Mips16InstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
46                                               int &FrameIndex) const {
47   return 0;
48 }
49
50 /// isStoreToStackSlot - If the specified machine instruction is a direct
51 /// store to a stack slot, return the virtual or physical register number of
52 /// the source reg along with the FrameIndex of the loaded stack slot.  If
53 /// not, return 0.  This predicate must return 0 if the instruction has
54 /// any side effects other than storing to the stack slot.
55 unsigned Mips16InstrInfo::isStoreToStackSlot(const MachineInstr *MI,
56                                              int &FrameIndex) const {
57   return 0;
58 }
59
60 void Mips16InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
61                                   MachineBasicBlock::iterator I, DebugLoc DL,
62                                   unsigned DestReg, unsigned SrcReg,
63                                   bool KillSrc) const {
64   unsigned Opc = 0;
65
66   if (Mips::CPU16RegsRegClass.contains(DestReg) &&
67       Mips::GPR32RegClass.contains(SrcReg))
68     Opc = Mips::MoveR3216;
69   else if (Mips::GPR32RegClass.contains(DestReg) &&
70            Mips::CPU16RegsRegClass.contains(SrcReg))
71     Opc = Mips::Move32R16;
72   else if ((SrcReg == Mips::HI0) &&
73            (Mips::CPU16RegsRegClass.contains(DestReg)))
74     Opc = Mips::Mfhi16, SrcReg = 0;
75
76   else if ((SrcReg == Mips::LO0) &&
77            (Mips::CPU16RegsRegClass.contains(DestReg)))
78     Opc = Mips::Mflo16, SrcReg = 0;
79
80
81   assert(Opc && "Cannot copy registers");
82
83   MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc));
84
85   if (DestReg)
86     MIB.addReg(DestReg, RegState::Define);
87
88   if (SrcReg)
89     MIB.addReg(SrcReg, getKillRegState(KillSrc));
90 }
91
92 void Mips16InstrInfo::storeRegToStack(MachineBasicBlock &MBB,
93                                       MachineBasicBlock::iterator I,
94                                       unsigned SrcReg, bool isKill, int FI,
95                                       const TargetRegisterClass *RC,
96                                       const TargetRegisterInfo *TRI,
97                                       int64_t Offset) const {
98   DebugLoc DL;
99   if (I != MBB.end()) DL = I->getDebugLoc();
100   MachineMemOperand *MMO = GetMemOperand(MBB, FI, MachineMemOperand::MOStore);
101   unsigned Opc = 0;
102   if (Mips::CPU16RegsRegClass.hasSubClassEq(RC))
103     Opc = Mips::SwRxSpImmX16;
104   assert(Opc && "Register class not handled!");
105   BuildMI(MBB, I, DL, get(Opc)).addReg(SrcReg, getKillRegState(isKill)).
106       addFrameIndex(FI).addImm(Offset)
107       .addMemOperand(MMO);
108 }
109
110 void Mips16InstrInfo::loadRegFromStack(MachineBasicBlock &MBB,
111                                        MachineBasicBlock::iterator I,
112                                        unsigned DestReg, int FI,
113                                        const TargetRegisterClass *RC,
114                                        const TargetRegisterInfo *TRI,
115                                        int64_t Offset) const {
116   DebugLoc DL;
117   if (I != MBB.end()) DL = I->getDebugLoc();
118   MachineMemOperand *MMO = GetMemOperand(MBB, FI, MachineMemOperand::MOLoad);
119   unsigned Opc = 0;
120
121   if (Mips::CPU16RegsRegClass.hasSubClassEq(RC))
122     Opc = Mips::LwRxSpImmX16;
123   assert(Opc && "Register class not handled!");
124   BuildMI(MBB, I, DL, get(Opc), DestReg).addFrameIndex(FI).addImm(Offset)
125     .addMemOperand(MMO);
126 }
127
128 bool Mips16InstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const {
129   MachineBasicBlock &MBB = *MI->getParent();
130   switch(MI->getDesc().getOpcode()) {
131   default:
132     return false;
133   case Mips::RetRA16:
134     ExpandRetRA16(MBB, MI, Mips::JrcRa16);
135     break;
136   }
137
138   MBB.erase(MI);
139   return true;
140 }
141
142 /// GetOppositeBranchOpc - Return the inverse of the specified
143 /// opcode, e.g. turning BEQ to BNE.
144 unsigned Mips16InstrInfo::getOppositeBranchOpc(unsigned Opc) const {
145   switch (Opc) {
146   case Mips::BeqzRxImmX16: return Mips::BnezRxImmX16;
147   case Mips::BnezRxImmX16: return Mips::BeqzRxImmX16;
148   case Mips::BeqzRxImm16: return Mips::BnezRxImm16;
149   case Mips::BnezRxImm16: return Mips::BeqzRxImm16;
150   case Mips::BteqzT8CmpX16: return Mips::BtnezT8CmpX16;
151   case Mips::BteqzT8SltX16: return Mips::BtnezT8SltX16;
152   case Mips::BteqzT8SltiX16: return Mips::BtnezT8SltiX16;
153   case Mips::Btnez16: return Mips::Bteqz16;
154   case Mips::BtnezX16: return Mips::BteqzX16;
155   case Mips::BtnezT8CmpiX16: return Mips::BteqzT8CmpiX16;
156   case Mips::BtnezT8SltuX16: return Mips::BteqzT8SltuX16;
157   case Mips::BtnezT8SltiuX16: return Mips::BteqzT8SltiuX16;
158   case Mips::Bteqz16: return Mips::Btnez16;
159   case Mips::BteqzX16: return Mips::BtnezX16;
160   case Mips::BteqzT8CmpiX16: return Mips::BtnezT8CmpiX16;
161   case Mips::BteqzT8SltuX16: return Mips::BtnezT8SltuX16;
162   case Mips::BteqzT8SltiuX16: return Mips::BtnezT8SltiuX16;
163   case Mips::BtnezT8CmpX16: return Mips::BteqzT8CmpX16;
164   case Mips::BtnezT8SltX16: return Mips::BteqzT8SltX16;
165   case Mips::BtnezT8SltiX16: return Mips::BteqzT8SltiX16;
166   }
167   llvm_unreachable("Illegal opcode!");
168 }
169
170 static void addSaveRestoreRegs(MachineInstrBuilder &MIB,
171                                const std::vector<CalleeSavedInfo> &CSI,
172                                unsigned Flags = 0) {
173   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
174     // Add the callee-saved register as live-in. Do not add if the register is
175     // RA and return address is taken, because it has already been added in
176     // method MipsTargetLowering::LowerRETURNADDR.
177     // It's killed at the spill, unless the register is RA and return address
178     // is taken.
179     unsigned Reg = CSI[e-i-1].getReg();
180     switch (Reg) {
181     case Mips::RA:
182     case Mips::S0:
183     case Mips::S1:
184       MIB.addReg(Reg, Flags);
185       break;
186     case Mips::S2:
187       break;
188     default:
189       llvm_unreachable("unexpected mips16 callee saved register");
190
191     }
192   }
193 }
194 // Adjust SP by FrameSize bytes. Save RA, S0, S1
195 void Mips16InstrInfo::makeFrame(unsigned SP, int64_t FrameSize,
196                                 MachineBasicBlock &MBB,
197                                 MachineBasicBlock::iterator I) const {
198   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
199   MachineFunction &MF = *MBB.getParent();
200   MachineFrameInfo *MFI    = MF.getFrameInfo();
201   const BitVector Reserved = RI.getReservedRegs(MF);
202   bool SaveS2 = Reserved[Mips::S2];
203   MachineInstrBuilder MIB;
204   unsigned Opc = ((FrameSize <= 128) && !SaveS2)? Mips::Save16:Mips::SaveX16;
205   MIB = BuildMI(MBB, I, DL, get(Opc));
206   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
207   addSaveRestoreRegs(MIB, CSI);
208   if (SaveS2)
209     MIB.addReg(Mips::S2);
210   if (isUInt<11>(FrameSize))
211     MIB.addImm(FrameSize);
212   else {
213     int Base = 2040; // should create template function like isUInt that
214                      // returns largest possible n bit unsigned integer
215     int64_t Remainder = FrameSize - Base;
216     MIB.addImm(Base);
217     if (isInt<16>(-Remainder))
218       BuildAddiuSpImm(MBB, I, -Remainder);
219     else
220       adjustStackPtrBig(SP, -Remainder, MBB, I, Mips::V0, Mips::V1);
221   }
222 }
223
224 // Adjust SP by FrameSize bytes. Restore RA, S0, S1
225 void Mips16InstrInfo::restoreFrame(unsigned SP, int64_t FrameSize,
226                                    MachineBasicBlock &MBB,
227                                    MachineBasicBlock::iterator I) const {
228   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
229   MachineFunction *MF = MBB.getParent();
230   MachineFrameInfo *MFI    = MF->getFrameInfo();
231   const BitVector Reserved = RI.getReservedRegs(*MF);
232   bool SaveS2 = Reserved[Mips::S2];
233   MachineInstrBuilder MIB;
234   unsigned Opc = ((FrameSize <= 128) && !SaveS2)?
235     Mips::Restore16:Mips::RestoreX16;
236
237   if (!isUInt<11>(FrameSize)) {
238     unsigned Base = 2040;
239     int64_t Remainder = FrameSize - Base;
240     FrameSize = Base; // should create template function like isUInt that
241                      // returns largest possible n bit unsigned integer
242
243     if (isInt<16>(Remainder))
244       BuildAddiuSpImm(MBB, I, Remainder);
245     else
246       adjustStackPtrBig(SP, Remainder, MBB, I, Mips::A0, Mips::A1);
247   }
248   MIB = BuildMI(MBB, I, DL, get(Opc));
249   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
250   addSaveRestoreRegs(MIB, CSI, RegState::Define);
251   if (SaveS2)
252     MIB.addReg(Mips::S2, RegState::Define);
253   MIB.addImm(FrameSize);
254 }
255
256 // Adjust SP by Amount bytes where bytes can be up to 32bit number.
257 // This can only be called at times that we know that there is at least one free
258 // register.
259 // This is clearly safe at prologue and epilogue.
260 //
261 void Mips16InstrInfo::adjustStackPtrBig(unsigned SP, int64_t Amount,
262                                         MachineBasicBlock &MBB,
263                                         MachineBasicBlock::iterator I,
264                                         unsigned Reg1, unsigned Reg2) const {
265   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
266   //
267   // li reg1, constant
268   // move reg2, sp
269   // add reg1, reg1, reg2
270   // move sp, reg1
271   //
272   //
273   MachineInstrBuilder MIB1 = BuildMI(MBB, I, DL, get(Mips::LwConstant32), Reg1);
274   MIB1.addImm(Amount).addImm(-1);
275   MachineInstrBuilder MIB2 = BuildMI(MBB, I, DL, get(Mips::MoveR3216), Reg2);
276   MIB2.addReg(Mips::SP, RegState::Kill);
277   MachineInstrBuilder MIB3 = BuildMI(MBB, I, DL, get(Mips::AdduRxRyRz16), Reg1);
278   MIB3.addReg(Reg1);
279   MIB3.addReg(Reg2, RegState::Kill);
280   MachineInstrBuilder MIB4 = BuildMI(MBB, I, DL, get(Mips::Move32R16),
281                                                      Mips::SP);
282   MIB4.addReg(Reg1, RegState::Kill);
283 }
284
285 void Mips16InstrInfo::adjustStackPtrBigUnrestricted(
286     unsigned SP, int64_t Amount, MachineBasicBlock &MBB,
287     MachineBasicBlock::iterator I) const {
288    llvm_unreachable("adjust stack pointer amount exceeded");
289 }
290
291 /// Adjust SP by Amount bytes.
292 void Mips16InstrInfo::adjustStackPtr(unsigned SP, int64_t Amount,
293                                      MachineBasicBlock &MBB,
294                                      MachineBasicBlock::iterator I) const {
295   if (isInt<16>(Amount))  // need to change to addiu sp, ....and isInt<16>
296     BuildAddiuSpImm(MBB, I, Amount);
297   else
298     adjustStackPtrBigUnrestricted(SP, Amount, MBB, I);
299 }
300
301 /// This function generates the sequence of instructions needed to get the
302 /// result of adding register REG and immediate IMM.
303 unsigned Mips16InstrInfo::loadImmediate(unsigned FrameReg, int64_t Imm,
304                                         MachineBasicBlock &MBB,
305                                         MachineBasicBlock::iterator II,
306                                         DebugLoc DL, unsigned &NewImm) const {
307   //
308   // given original instruction is:
309   // Instr rx, T[offset] where offset is too big.
310   //
311   // lo = offset & 0xFFFF
312   // hi = ((offset >> 16) + (lo >> 15)) & 0xFFFF;
313   //
314   // let T = temporary register
315   // li T, hi
316   // shl T, 16
317   // add T, Rx, T
318   //
319   RegScavenger rs;
320   int32_t lo = Imm & 0xFFFF;
321   NewImm = lo;
322   int Reg =0;
323   int SpReg = 0;
324
325   rs.enterBasicBlock(&MBB);
326   rs.forward(II);
327   //
328   // We need to know which registers can be used, in the case where there
329   // are not enough free registers. We exclude all registers that
330   // are used in the instruction that we are helping.
331   //  // Consider all allocatable registers in the register class initially
332   BitVector Candidates =
333       RI.getAllocatableSet
334       (*II->getParent()->getParent(), &Mips::CPU16RegsRegClass);
335   // Exclude all the registers being used by the instruction.
336   for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
337     MachineOperand &MO = II->getOperand(i);
338     if (MO.isReg() && MO.getReg() != 0 && !MO.isDef() &&
339         !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
340       Candidates.reset(MO.getReg());
341   }
342
343   // If the same register was used and defined in an instruction, then
344   // it will not be in the list of candidates.
345   //
346   // we need to analyze the instruction that we are helping.
347   // we need to know if it defines register x but register x is not
348   // present as an operand of the instruction. this tells
349   // whether the register is live before the instruction. if it's not
350   // then we don't need to save it in case there are no free registers.
351   int DefReg = 0;
352   for (unsigned i = 0, e = II->getNumOperands(); i != e; ++i) {
353     MachineOperand &MO = II->getOperand(i);
354     if (MO.isReg() && MO.isDef()) {
355       DefReg = MO.getReg();
356       break;
357     }
358   }
359
360   BitVector Available = rs.getRegsAvailable(&Mips::CPU16RegsRegClass);
361   Available &= Candidates;
362   //
363   // we use T0 for the first register, if we need to save something away.
364   // we use T1 for the second register, if we need to save something away.
365   //
366   unsigned FirstRegSaved =0, SecondRegSaved=0;
367   unsigned FirstRegSavedTo = 0, SecondRegSavedTo = 0;
368
369   Reg = Available.find_first();
370
371   if (Reg == -1) {
372     Reg = Candidates.find_first();
373     Candidates.reset(Reg);
374     if (DefReg != Reg) {
375       FirstRegSaved = Reg;
376       FirstRegSavedTo = Mips::T0;
377       copyPhysReg(MBB, II, DL, FirstRegSavedTo, FirstRegSaved, true);
378     }
379   }
380   else
381     Available.reset(Reg);
382   BuildMI(MBB, II, DL, get(Mips::LwConstant32), Reg).addImm(Imm).addImm(-1);
383   NewImm = 0;
384   if (FrameReg == Mips::SP) {
385     SpReg = Available.find_first();
386     if (SpReg == -1) {
387       SpReg = Candidates.find_first();
388       // Candidates.reset(SpReg); // not really needed
389       if (DefReg!= SpReg) {
390         SecondRegSaved = SpReg;
391         SecondRegSavedTo = Mips::T1;
392       }
393       if (SecondRegSaved)
394         copyPhysReg(MBB, II, DL, SecondRegSavedTo, SecondRegSaved, true);
395     }
396    else
397      Available.reset(SpReg);
398     copyPhysReg(MBB, II, DL, SpReg, Mips::SP, false);
399     BuildMI(MBB, II, DL, get(Mips::  AdduRxRyRz16), Reg).addReg(SpReg, RegState::Kill)
400       .addReg(Reg);
401   }
402   else
403     BuildMI(MBB, II, DL, get(Mips::  AdduRxRyRz16), Reg).addReg(FrameReg)
404       .addReg(Reg, RegState::Kill);
405   if (FirstRegSaved || SecondRegSaved) {
406     II = std::next(II);
407     if (FirstRegSaved)
408       copyPhysReg(MBB, II, DL, FirstRegSaved, FirstRegSavedTo, true);
409     if (SecondRegSaved)
410       copyPhysReg(MBB, II, DL, SecondRegSaved, SecondRegSavedTo, true);
411   }
412   return Reg;
413 }
414
415 unsigned Mips16InstrInfo::getAnalyzableBrOpc(unsigned Opc) const {
416   return (Opc == Mips::BeqzRxImmX16   || Opc == Mips::BimmX16  ||
417           Opc == Mips::Bimm16  ||
418           Opc == Mips::Bteqz16        || Opc == Mips::Btnez16 ||
419           Opc == Mips::BeqzRxImm16    || Opc == Mips::BnezRxImm16   ||
420           Opc == Mips::BnezRxImmX16   || Opc == Mips::BteqzX16 ||
421           Opc == Mips::BteqzT8CmpX16  || Opc == Mips::BteqzT8CmpiX16 ||
422           Opc == Mips::BteqzT8SltX16  || Opc == Mips::BteqzT8SltuX16  ||
423           Opc == Mips::BteqzT8SltiX16 || Opc == Mips::BteqzT8SltiuX16 ||
424           Opc == Mips::BtnezX16       || Opc == Mips::BtnezT8CmpX16 ||
425           Opc == Mips::BtnezT8CmpiX16 || Opc == Mips::BtnezT8SltX16 ||
426           Opc == Mips::BtnezT8SltuX16 || Opc == Mips::BtnezT8SltiX16 ||
427           Opc == Mips::BtnezT8SltiuX16 ) ? Opc : 0;
428 }
429
430 void Mips16InstrInfo::ExpandRetRA16(MachineBasicBlock &MBB,
431                                   MachineBasicBlock::iterator I,
432                                   unsigned Opc) const {
433   BuildMI(MBB, I, I->getDebugLoc(), get(Opc));
434 }
435
436 const MCInstrDesc &Mips16InstrInfo::AddiuSpImm(int64_t Imm) const {
437   if (validSpImm8(Imm))
438     return get(Mips::AddiuSpImm16);
439   else
440     return get(Mips::AddiuSpImmX16);
441 }
442
443 void Mips16InstrInfo::BuildAddiuSpImm
444   (MachineBasicBlock &MBB, MachineBasicBlock::iterator I, int64_t Imm) const {
445   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
446   BuildMI(MBB, I, DL, AddiuSpImm(Imm)).addImm(Imm);
447 }
448
449 const MipsInstrInfo *llvm::createMips16InstrInfo(const MipsSubtarget &STI) {
450   return new Mips16InstrInfo(STI);
451 }
452
453 bool Mips16InstrInfo::validImmediate(unsigned Opcode, unsigned Reg,
454                                      int64_t Amount) {
455   switch (Opcode) {
456   case Mips::LbRxRyOffMemX16:
457   case Mips::LbuRxRyOffMemX16:
458   case Mips::LhRxRyOffMemX16:
459   case Mips::LhuRxRyOffMemX16:
460   case Mips::SbRxRyOffMemX16:
461   case Mips::ShRxRyOffMemX16:
462   case Mips::LwRxRyOffMemX16:
463   case Mips::SwRxRyOffMemX16:
464   case Mips::SwRxSpImmX16:
465   case Mips::LwRxSpImmX16:
466     return isInt<16>(Amount);
467   case Mips::AddiuRxRyOffMemX16:
468     if ((Reg == Mips::PC) || (Reg == Mips::SP))
469       return isInt<16>(Amount);
470     return isInt<15>(Amount);
471   }
472   llvm_unreachable("unexpected Opcode in validImmediate");
473 }
474
475 /// Measure the specified inline asm to determine an approximation of its
476 /// length.
477 /// Comments (which run till the next SeparatorString or newline) do not
478 /// count as an instruction.
479 /// Any other non-whitespace text is considered an instruction, with
480 /// multiple instructions separated by SeparatorString or newlines.
481 /// Variable-length instructions are not handled here; this function
482 /// may be overloaded in the target code to do that.
483 /// We implement the special case of the .space directive taking only an
484 /// integer argument, which is the size in bytes. This is used for creating
485 /// inline code spacing for testing purposes using inline assembly.
486 ///
487 unsigned Mips16InstrInfo::getInlineAsmLength(const char *Str,
488                                              const MCAsmInfo &MAI) const {
489
490   // Count the number of instructions in the asm.
491   bool atInsnStart = true;
492   unsigned Length = 0;
493   for (; *Str; ++Str) {
494     if (*Str == '\n' || strncmp(Str, MAI.getSeparatorString(),
495                                 strlen(MAI.getSeparatorString())) == 0)
496       atInsnStart = true;
497     if (atInsnStart && !std::isspace(static_cast<unsigned char>(*Str))) {
498       if (strncmp(Str, ".space", 6)==0) {
499         char *EStr; int Sz;
500         Sz = strtol(Str+6, &EStr, 10);
501         while (isspace(*EStr)) ++EStr;
502         if (*EStr=='\0') {
503           DEBUG(dbgs() << "parsed .space " << Sz << '\n');
504           return Sz;
505         }
506       }
507       Length += MAI.getMaxInstLength();
508       atInsnStart = false;
509     }
510     if (atInsnStart && strncmp(Str, MAI.getCommentString(),
511                                strlen(MAI.getCommentString())) == 0)
512       atInsnStart = false;
513   }
514
515   return Length;
516 }