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