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