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