Change the interface to the type legalization method
[oota-llvm.git] / lib / Target / XCore / XCoreInstrInfo.cpp
1 //===- XCoreInstrInfo.cpp - XCore Instruction Information -------*- C++ -*-===//
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 XCore implementation of the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "XCoreMachineFunctionInfo.h"
15 #include "XCoreInstrInfo.h"
16 #include "XCore.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineLocation.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "XCoreGenInstrInfo.inc"
23 #include "llvm/Support/Debug.h"
24
25 namespace llvm {
26 namespace XCore {
27
28   // XCore Condition Codes
29   enum CondCode {
30     COND_TRUE,
31     COND_FALSE,
32     COND_INVALID
33   };
34 }
35 }
36
37 using namespace llvm;
38
39 XCoreInstrInfo::XCoreInstrInfo(void)
40   : TargetInstrInfoImpl(XCoreInsts, array_lengthof(XCoreInsts)),
41     RI(*this) {
42 }
43
44 static bool isZeroImm(const MachineOperand &op) {
45   return op.isImm() && op.getImm() == 0;
46 }
47
48 /// Return true if the instruction is a register to register move and
49 /// leave the source and dest operands in the passed parameters.
50 ///
51 bool XCoreInstrInfo::isMoveInstr(const MachineInstr &MI,
52                                  unsigned &SrcReg, unsigned &DstReg) const {
53   // We look for 4 kinds of patterns here:
54   // add dst, src, 0
55   // sub dst, src, 0
56   // or dst, src, src
57   // and dst, src, src
58   if ((MI.getOpcode() == XCore::ADD_2rus || MI.getOpcode() == XCore::SUB_2rus)
59       && isZeroImm(MI.getOperand(2))) {
60     DstReg = MI.getOperand(0).getReg();
61     SrcReg = MI.getOperand(1).getReg();
62     return true;
63   } else if ((MI.getOpcode() == XCore::OR_3r || MI.getOpcode() == XCore::AND_3r)
64       && MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
65     DstReg = MI.getOperand(0).getReg();
66     SrcReg = MI.getOperand(1).getReg();
67     return true;
68   }
69   return false;
70 }
71
72 /// isLoadFromStackSlot - If the specified machine instruction is a direct
73 /// load from a stack slot, return the virtual or physical register number of
74 /// the destination along with the FrameIndex of the loaded stack slot.  If
75 /// not, return 0.  This predicate must return 0 if the instruction has
76 /// any side effects other than loading from the stack slot.
77 unsigned
78 XCoreInstrInfo::isLoadFromStackSlot(const MachineInstr *MI, int &FrameIndex) const{
79   int Opcode = MI->getOpcode();
80   if (Opcode == XCore::LDWSP_ru6 || Opcode == XCore::LDWSP_lru6) 
81   {
82     if ((MI->getOperand(1).isFI()) && // is a stack slot
83         (MI->getOperand(2).isImm()) &&  // the imm is zero
84         (isZeroImm(MI->getOperand(2)))) 
85     {
86       FrameIndex = MI->getOperand(1).getIndex();
87       return MI->getOperand(0).getReg();
88     }
89   }
90   return 0;
91 }
92   
93   /// isStoreToStackSlot - If the specified machine instruction is a direct
94   /// store to a stack slot, return the virtual or physical register number of
95   /// the source reg along with the FrameIndex of the loaded stack slot.  If
96   /// not, return 0.  This predicate must return 0 if the instruction has
97   /// any side effects other than storing to the stack slot.
98 unsigned
99 XCoreInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
100                                    int &FrameIndex) const {
101   int Opcode = MI->getOpcode();
102   if (Opcode == XCore::STWSP_ru6 || Opcode == XCore::STWSP_lru6) 
103   {
104     if ((MI->getOperand(1).isFI()) && // is a stack slot
105         (MI->getOperand(2).isImm()) &&  // the imm is zero
106         (isZeroImm(MI->getOperand(2)))) 
107     {
108       FrameIndex = MI->getOperand(1).getIndex();
109       return MI->getOperand(0).getReg();
110     }
111   }
112   else if (Opcode == XCore::STWSP_ru6_2 || Opcode == XCore::STWSP_lru6_2)
113   {
114     if (MI->getOperand(1).isFI())
115     {
116       FrameIndex = MI->getOperand(1).getIndex();
117       return MI->getOperand(0).getReg();
118     }
119   }
120   return 0;
121 }
122
123 /// isInvariantLoad - Return true if the specified instruction (which is marked
124 /// mayLoad) is loading from a location whose value is invariant across the
125 /// function.  For example, loading a value from the constant pool or from
126 /// from the argument area of a function if it does not change.  This should
127 /// only return true of *all* loads the instruction does are invariant (if it
128 /// does multiple loads).
129 bool
130 XCoreInstrInfo::isInvariantLoad(const MachineInstr *MI) const {
131   // Loads from constants pools and loads from invariant argument slots are
132   // invariant
133   int Opcode = MI->getOpcode();
134   if (Opcode == XCore::LDWCP_ru6 || Opcode == XCore::LDWCP_lru6) {
135     return MI->getOperand(1).isCPI();
136   }
137   int FrameIndex;
138   if (isLoadFromStackSlot(MI, FrameIndex)) {
139     const MachineFrameInfo &MFI =
140       *MI->getParent()->getParent()->getFrameInfo();
141     return MFI.isFixedObjectIndex(FrameIndex) &&
142            MFI.isImmutableObjectIndex(FrameIndex);
143   }
144   return false;
145 }
146
147 //===----------------------------------------------------------------------===//
148 // Branch Analysis
149 //===----------------------------------------------------------------------===//
150
151 static inline bool IsBRU(unsigned BrOpc) {
152   return BrOpc == XCore::BRFU_u6
153       || BrOpc == XCore::BRFU_lu6
154       || BrOpc == XCore::BRBU_u6
155       || BrOpc == XCore::BRBU_lu6;
156 }
157
158 static inline bool IsBRT(unsigned BrOpc) {
159   return BrOpc == XCore::BRFT_ru6
160       || BrOpc == XCore::BRFT_lru6
161       || BrOpc == XCore::BRBT_ru6
162       || BrOpc == XCore::BRBT_lru6;
163 }
164
165 static inline bool IsBRF(unsigned BrOpc) {
166   return BrOpc == XCore::BRFF_ru6
167       || BrOpc == XCore::BRFF_lru6
168       || BrOpc == XCore::BRBF_ru6
169       || BrOpc == XCore::BRBF_lru6;
170 }
171
172 static inline bool IsCondBranch(unsigned BrOpc) {
173   return IsBRF(BrOpc) || IsBRT(BrOpc);
174 }
175
176 /// GetCondFromBranchOpc - Return the XCore CC that matches 
177 /// the correspondent Branch instruction opcode.
178 static XCore::CondCode GetCondFromBranchOpc(unsigned BrOpc) 
179 {
180   if (IsBRT(BrOpc)) {
181     return XCore::COND_TRUE;
182   } else if (IsBRF(BrOpc)) {
183     return XCore::COND_FALSE;
184   } else {
185     return XCore::COND_INVALID;
186   }
187 }
188
189 /// GetCondBranchFromCond - Return the Branch instruction
190 /// opcode that matches the cc.
191 static inline unsigned GetCondBranchFromCond(XCore::CondCode CC) 
192 {
193   switch (CC) {
194   default: assert(0 && "Illegal condition code!");
195   case XCore::COND_TRUE   : return XCore::BRFT_lru6;
196   case XCore::COND_FALSE  : return XCore::BRFF_lru6;
197   }
198 }
199
200 /// GetOppositeBranchCondition - Return the inverse of the specified 
201 /// condition, e.g. turning COND_E to COND_NE.
202 static inline XCore::CondCode GetOppositeBranchCondition(XCore::CondCode CC)
203 {
204   switch (CC) {
205   default: assert(0 && "Illegal condition code!");
206   case XCore::COND_TRUE   : return XCore::COND_FALSE;
207   case XCore::COND_FALSE  : return XCore::COND_TRUE;
208   }
209 }
210
211 /// AnalyzeBranch - Analyze the branching code at the end of MBB, returning
212 /// true if it cannot be understood (e.g. it's a switch dispatch or isn't
213 /// implemented for a target).  Upon success, this returns false and returns
214 /// with the following information in various cases:
215 ///
216 /// 1. If this block ends with no branches (it just falls through to its succ)
217 ///    just return false, leaving TBB/FBB null.
218 /// 2. If this block ends with only an unconditional branch, it sets TBB to be
219 ///    the destination block.
220 /// 3. If this block ends with an conditional branch and it falls through to
221 ///    an successor block, it sets TBB to be the branch destination block and a
222 ///    list of operands that evaluate the condition. These
223 ///    operands can be passed to other TargetInstrInfo methods to create new
224 ///    branches.
225 /// 4. If this block ends with an conditional branch and an unconditional
226 ///    block, it returns the 'true' destination in TBB, the 'false' destination
227 ///    in FBB, and a list of operands that evaluate the condition. These
228 ///    operands can be passed to other TargetInstrInfo methods to create new
229 ///    branches.
230 ///
231 /// Note that RemoveBranch and InsertBranch must be implemented to support
232 /// cases where this method returns success.
233 ///
234 bool
235 XCoreInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB, MachineBasicBlock *&TBB,
236                            MachineBasicBlock *&FBB,
237                            SmallVectorImpl<MachineOperand> &Cond) const {
238   // If the block has no terminators, it just falls into the block after it.
239   MachineBasicBlock::iterator I = MBB.end();
240   if (I == MBB.begin() || !isUnpredicatedTerminator(--I))
241     return false;
242
243   // Get the last instruction in the block.
244   MachineInstr *LastInst = I;
245   
246   // If there is only one terminator instruction, process it.
247   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
248     if (IsBRU(LastInst->getOpcode())) {
249       TBB = LastInst->getOperand(0).getMBB();
250       return false;
251     }
252     
253     XCore::CondCode BranchCode = GetCondFromBranchOpc(LastInst->getOpcode());
254     if (BranchCode == XCore::COND_INVALID)
255       return true;  // Can't handle indirect branch.
256     
257     // Conditional branch
258     // Block ends with fall-through condbranch.
259
260     TBB = LastInst->getOperand(1).getMBB();
261     Cond.push_back(MachineOperand::CreateImm(BranchCode));
262     Cond.push_back(LastInst->getOperand(0));
263     return false;
264   }
265   
266   // Get the instruction before it if it's a terminator.
267   MachineInstr *SecondLastInst = I;
268
269   // If there are three terminators, we don't know what sort of block this is.
270   if (SecondLastInst && I != MBB.begin() &&
271       isUnpredicatedTerminator(--I))
272     return true;
273   
274   unsigned SecondLastOpc    = SecondLastInst->getOpcode();
275   XCore::CondCode BranchCode = GetCondFromBranchOpc(SecondLastOpc);
276   
277   // If the block ends with conditional branch followed by unconditional,
278   // handle it.
279   if (BranchCode != XCore::COND_INVALID
280     && IsBRU(LastInst->getOpcode())) {
281
282     TBB = SecondLastInst->getOperand(1).getMBB();
283     Cond.push_back(MachineOperand::CreateImm(BranchCode));
284     Cond.push_back(SecondLastInst->getOperand(0));
285
286     FBB = LastInst->getOperand(0).getMBB();
287     return false;
288   }
289   
290   // If the block ends with two unconditional branches, handle it.  The second
291   // one is not executed, so remove it.
292   if (IsBRU(SecondLastInst->getOpcode()) && 
293       IsBRU(LastInst->getOpcode())) {
294     TBB = SecondLastInst->getOperand(0).getMBB();
295     I = LastInst;
296     I->eraseFromParent();
297     return false;
298   }
299
300   // Otherwise, can't handle this.
301   return true;
302 }
303
304 unsigned
305 XCoreInstrInfo::InsertBranch(MachineBasicBlock &MBB,MachineBasicBlock *TBB,
306                              MachineBasicBlock *FBB,
307                              const SmallVectorImpl<MachineOperand> &Cond)const{
308   // Shouldn't be a fall through.
309   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
310   assert((Cond.size() == 2 || Cond.size() == 0) &&
311          "Unexpected number of components!");
312   
313   if (FBB == 0) { // One way branch.
314     if (Cond.empty()) {
315       // Unconditional branch
316       BuildMI(&MBB, get(XCore::BRFU_lu6)).addMBB(TBB);
317     } else {
318       // Conditional branch.
319       unsigned Opc = GetCondBranchFromCond((XCore::CondCode)Cond[0].getImm());
320       BuildMI(&MBB, get(Opc)).addReg(Cond[1].getReg())
321                              .addMBB(TBB);
322     }
323     return 1;
324   }
325   
326   // Two-way Conditional branch.
327   assert(Cond.size() == 2 && "Unexpected number of components!");
328   unsigned Opc = GetCondBranchFromCond((XCore::CondCode)Cond[0].getImm());
329   BuildMI(&MBB, get(Opc)).addReg(Cond[1].getReg())
330                          .addMBB(TBB);
331   BuildMI(&MBB, get(XCore::BRFU_lu6)).addMBB(FBB);
332   return 2;
333 }
334
335 unsigned
336 XCoreInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
337   MachineBasicBlock::iterator I = MBB.end();
338   if (I == MBB.begin()) return 0;
339   --I;
340   if (!IsBRU(I->getOpcode()) && !IsCondBranch(I->getOpcode()))
341     return 0;
342   
343   // Remove the branch.
344   I->eraseFromParent();
345   
346   I = MBB.end();
347
348   if (I == MBB.begin()) return 1;
349   --I;
350   if (!IsCondBranch(I->getOpcode()))
351     return 1;
352   
353   // Remove the branch.
354   I->eraseFromParent();
355   return 2;
356 }
357
358 bool XCoreInstrInfo::copyRegToReg(MachineBasicBlock &MBB,
359                                      MachineBasicBlock::iterator I,
360                                      unsigned DestReg, unsigned SrcReg,
361                                      const TargetRegisterClass *DestRC,
362                                      const TargetRegisterClass *SrcRC) const {
363   if (DestRC == SrcRC) {
364     if (DestRC == XCore::GRRegsRegisterClass) {
365       BuildMI(MBB, I, get(XCore::ADD_2rus), DestReg).addReg(SrcReg).addImm(0);
366       return true;
367     } else {
368       return false;
369     }
370   }
371   
372   if (SrcRC == XCore::RRegsRegisterClass && SrcReg == XCore::SP &&
373     DestRC == XCore::GRRegsRegisterClass) {
374     BuildMI(MBB, I, get(XCore::LDAWSP_ru6), DestReg).addImm(0).addImm(0);
375     return true;
376   }
377   if (DestRC == XCore::RRegsRegisterClass && DestReg == XCore::SP &&
378     SrcRC == XCore::GRRegsRegisterClass) {
379     BuildMI(MBB, I, get(XCore::SETSP_1r)).addReg(SrcReg);
380     return true;
381   }
382   return false;
383 }
384
385 void XCoreInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
386                                   MachineBasicBlock::iterator I,
387                                   unsigned SrcReg, bool isKill, int FrameIndex,
388                                   const TargetRegisterClass *RC) const
389 {
390   BuildMI(MBB, I, get(XCore::STWSP_lru6)).addReg(SrcReg, false, false, isKill)
391                                          .addFrameIndex(FrameIndex).addImm(0);
392 }
393
394 void XCoreInstrInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
395                             bool isKill, SmallVectorImpl<MachineOperand> &Addr,
396                             const TargetRegisterClass *RC,
397                             SmallVectorImpl<MachineInstr*> &NewMIs) const
398 {
399   assert(0 && "unimplemented\n");
400 }
401
402 void XCoreInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
403                                   MachineBasicBlock::iterator I,
404                                   unsigned DestReg, int FrameIndex,
405                                   const TargetRegisterClass *RC) const
406 {
407   BuildMI(MBB, I, get(XCore::LDWSP_lru6), DestReg).addFrameIndex(FrameIndex)
408                                                   .addImm(0);
409 }
410
411 void XCoreInstrInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
412                               SmallVectorImpl<MachineOperand> &Addr,
413                               const TargetRegisterClass *RC,
414                               SmallVectorImpl<MachineInstr*> &NewMIs) const
415 {
416   assert(0 && "unimplemented\n");
417 }
418
419 bool XCoreInstrInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
420                                 MachineBasicBlock::iterator MI,
421                         const std::vector<CalleeSavedInfo> &CSI) const
422 {
423   if (CSI.empty()) {
424     return true;
425   }
426   MachineFunction *MF = MBB.getParent();
427   const MachineFrameInfo *MFI = MF->getFrameInfo();
428   MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
429   XCoreFunctionInfo *XFI = MF->getInfo<XCoreFunctionInfo>();
430   
431   bool emitFrameMoves = XCoreRegisterInfo::needsFrameMoves(*MF);
432   
433   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
434                                                     it != CSI.end(); ++it) {
435     // Add the callee-saved register as live-in. It's killed at the spill.
436     MBB.addLiveIn(it->getReg());
437
438     storeRegToStackSlot(MBB, MI, it->getReg(), true,
439                                    it->getFrameIdx(), it->getRegClass());
440     if (emitFrameMoves) {
441       unsigned SaveLabelId = MMI->NextLabelID();
442       BuildMI(MBB, MI, get(XCore::DBG_LABEL)).addImm(SaveLabelId);
443       XFI->getSpillLabels().push_back(
444           std::pair<unsigned, CalleeSavedInfo>(SaveLabelId, *it));
445     }
446   }
447   return true;
448 }
449
450 bool XCoreInstrInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
451                                          MachineBasicBlock::iterator MI,
452                                const std::vector<CalleeSavedInfo> &CSI) const
453 {
454   bool AtStart = MI == MBB.begin();
455   MachineBasicBlock::iterator BeforeI = MI;
456   if (!AtStart)
457     --BeforeI;
458   for (std::vector<CalleeSavedInfo>::const_iterator it = CSI.begin();
459                                                     it != CSI.end(); ++it) {
460     
461     loadRegFromStackSlot(MBB, MI, it->getReg(),
462                                   it->getFrameIdx(),
463                                   it->getRegClass());
464     assert(MI != MBB.begin() &&
465            "loadRegFromStackSlot didn't insert any code!");
466     // Insert in reverse order.  loadRegFromStackSlot can insert multiple
467     // instructions.
468     if (AtStart)
469       MI = MBB.begin();
470     else {
471       MI = BeforeI;
472       ++MI;
473     }
474   }
475   return true;
476 }
477
478 /// BlockHasNoFallThrough - Analyse if MachineBasicBlock does not
479 /// fall-through into its successor block.
480 bool XCoreInstrInfo::
481 BlockHasNoFallThrough(const MachineBasicBlock &MBB) const 
482 {
483   if (MBB.empty()) return false;
484   
485   switch (MBB.back().getOpcode()) {
486   case XCore::RETSP_u6:     // Return.
487   case XCore::RETSP_lu6:
488   case XCore::BAU_1r:       // Indirect branch.
489   case XCore::BRFU_u6:      // Uncond branch.
490   case XCore::BRFU_lu6:
491   case XCore::BRBU_u6:
492   case XCore::BRBU_lu6:
493     return true;
494   default: return false;
495   }
496 }
497
498 /// ReverseBranchCondition - Return the inverse opcode of the 
499 /// specified Branch instruction.
500 bool XCoreInstrInfo::
501 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const 
502 {
503   assert((Cond.size() == 2) && 
504           "Invalid XCore branch condition!");
505   Cond[0].setImm(GetOppositeBranchCondition((XCore::CondCode)Cond[0].getImm()));
506   return false;
507 }