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