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