MipsSEISelDAGToDAG.cpp revision fc82e4db13b46b2f14f5895d2a0b33524d55d06a
1//===-- MipsSEISelDAGToDAG.cpp - A Dag to Dag Inst Selector for MipsSE ----===//
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// Subclass of MipsDAGToDAGISel specialized for mips32/64.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "mips-isel"
15#include "MipsSEISelDAGToDAG.h"
16#include "Mips.h"
17#include "MCTargetDesc/MipsBaseInfo.h"
18#include "MipsAnalyzeImmediate.h"
19#include "MipsMachineFunction.h"
20#include "MipsRegisterInfo.h"
21#include "llvm/CodeGen/MachineConstantPool.h"
22#include "llvm/CodeGen/MachineFrameInfo.h"
23#include "llvm/CodeGen/MachineFunction.h"
24#include "llvm/CodeGen/MachineInstrBuilder.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/CodeGen/SelectionDAGNodes.h"
27#include "llvm/IR/GlobalValue.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CFG.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetMachine.h"
36using namespace llvm;
37
38bool MipsSEDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
39  if (Subtarget.inMips16Mode())
40    return false;
41  return MipsDAGToDAGISel::runOnMachineFunction(MF);
42}
43
44bool MipsSEDAGToDAGISel::replaceUsesWithZeroReg(MachineRegisterInfo *MRI,
45                                                const MachineInstr& MI) {
46  unsigned DstReg = 0, ZeroReg = 0;
47
48  // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
49  if ((MI.getOpcode() == Mips::ADDiu) &&
50      (MI.getOperand(1).getReg() == Mips::ZERO) &&
51      (MI.getOperand(2).getImm() == 0)) {
52    DstReg = MI.getOperand(0).getReg();
53    ZeroReg = Mips::ZERO;
54  } else if ((MI.getOpcode() == Mips::DADDiu) &&
55             (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
56             (MI.getOperand(2).getImm() == 0)) {
57    DstReg = MI.getOperand(0).getReg();
58    ZeroReg = Mips::ZERO_64;
59  }
60
61  if (!DstReg)
62    return false;
63
64  // Replace uses with ZeroReg.
65  for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
66       E = MRI->use_end(); U != E;) {
67    MachineOperand &MO = U.getOperand();
68    unsigned OpNo = U.getOperandNo();
69    MachineInstr *MI = MO.getParent();
70    ++U;
71
72    // Do not replace if it is a phi's operand or is tied to def operand.
73    if (MI->isPHI() || MI->isRegTiedToDefOperand(OpNo) || MI->isPseudo())
74      continue;
75
76    MO.setReg(ZeroReg);
77  }
78
79  return true;
80}
81
82void MipsSEDAGToDAGISel::initGlobalBaseReg(MachineFunction &MF) {
83  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
84
85  if (!MipsFI->globalBaseRegSet())
86    return;
87
88  MachineBasicBlock &MBB = MF.front();
89  MachineBasicBlock::iterator I = MBB.begin();
90  MachineRegisterInfo &RegInfo = MF.getRegInfo();
91  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
92  DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
93  unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
94  const TargetRegisterClass *RC;
95
96  if (Subtarget.isABI_N64())
97    RC = (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
98  else
99    RC = (const TargetRegisterClass*)&Mips::CPURegsRegClass;
100
101  V0 = RegInfo.createVirtualRegister(RC);
102  V1 = RegInfo.createVirtualRegister(RC);
103
104  if (Subtarget.isABI_N64()) {
105    MF.getRegInfo().addLiveIn(Mips::T9_64);
106    MBB.addLiveIn(Mips::T9_64);
107
108    // lui $v0, %hi(%neg(%gp_rel(fname)))
109    // daddu $v1, $v0, $t9
110    // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
111    const GlobalValue *FName = MF.getFunction();
112    BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
113      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
114    BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
115      .addReg(Mips::T9_64);
116    BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
117      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
118    return;
119  }
120
121  if (MF.getTarget().getRelocationModel() == Reloc::Static) {
122    // Set global register to __gnu_local_gp.
123    //
124    // lui   $v0, %hi(__gnu_local_gp)
125    // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
126    BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
127      .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
128    BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
129      .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
130    return;
131  }
132
133  MF.getRegInfo().addLiveIn(Mips::T9);
134  MBB.addLiveIn(Mips::T9);
135
136  if (Subtarget.isABI_N32()) {
137    // lui $v0, %hi(%neg(%gp_rel(fname)))
138    // addu $v1, $v0, $t9
139    // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
140    const GlobalValue *FName = MF.getFunction();
141    BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
142      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
143    BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
144    BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
145      .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
146    return;
147  }
148
149  assert(Subtarget.isABI_O32());
150
151  // For O32 ABI, the following instruction sequence is emitted to initialize
152  // the global base register:
153  //
154  //  0. lui   $2, %hi(_gp_disp)
155  //  1. addiu $2, $2, %lo(_gp_disp)
156  //  2. addu  $globalbasereg, $2, $t9
157  //
158  // We emit only the last instruction here.
159  //
160  // GNU linker requires that the first two instructions appear at the beginning
161  // of a function and no instructions be inserted before or between them.
162  // The two instructions are emitted during lowering to MC layer in order to
163  // avoid any reordering.
164  //
165  // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
166  // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
167  // reads it.
168  MF.getRegInfo().addLiveIn(Mips::V0);
169  MBB.addLiveIn(Mips::V0);
170  BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
171    .addReg(Mips::V0).addReg(Mips::T9);
172}
173
174void MipsSEDAGToDAGISel::processFunctionAfterISel(MachineFunction &MF) {
175  initGlobalBaseReg(MF);
176
177  MachineRegisterInfo *MRI = &MF.getRegInfo();
178
179  for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
180       ++MFI)
181    for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
182      replaceUsesWithZeroReg(MRI, *I);
183}
184
185SDNode *MipsSEDAGToDAGISel::selectAddESubE(unsigned MOp, SDValue InFlag,
186                                           SDValue CmpLHS, DebugLoc DL,
187                                           SDNode *Node) const {
188  unsigned Opc = InFlag.getOpcode(); (void)Opc;
189
190  assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
191          (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
192         "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
193
194  SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
195  SDValue LHS = Node->getOperand(0), RHS = Node->getOperand(1);
196  EVT VT = LHS.getValueType();
197
198  SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, DL, VT, Ops, 2);
199  SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, DL, VT,
200                                            SDValue(Carry, 0), RHS);
201  return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue, LHS,
202                              SDValue(AddCarry, 0));
203}
204
205/// ComplexPattern used on MipsInstrInfo
206/// Used on Mips Load/Store instructions
207bool MipsSEDAGToDAGISel::selectAddrRegImm(SDValue Addr, SDValue &Base,
208                                          SDValue &Offset) const {
209  EVT ValTy = Addr.getValueType();
210
211  // if Address is FI, get the TargetFrameIndex.
212  if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
213    Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
214    Offset = CurDAG->getTargetConstant(0, ValTy);
215    return true;
216  }
217
218  // on PIC code Load GA
219  if (Addr.getOpcode() == MipsISD::Wrapper) {
220    Base   = Addr.getOperand(0);
221    Offset = Addr.getOperand(1);
222    return true;
223  }
224
225  if (TM.getRelocationModel() != Reloc::PIC_) {
226    if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
227        Addr.getOpcode() == ISD::TargetGlobalAddress))
228      return false;
229  }
230
231  // Addresses of the form FI+const or FI|const
232  if (CurDAG->isBaseWithConstantOffset(Addr)) {
233    ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
234    if (isInt<16>(CN->getSExtValue())) {
235
236      // If the first operand is a FI, get the TargetFI Node
237      if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
238                                  (Addr.getOperand(0)))
239        Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
240      else
241        Base = Addr.getOperand(0);
242
243      Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
244      return true;
245    }
246  }
247
248  // Operand is a result from an ADD.
249  if (Addr.getOpcode() == ISD::ADD) {
250    // When loading from constant pools, load the lower address part in
251    // the instruction itself. Example, instead of:
252    //  lui $2, %hi($CPI1_0)
253    //  addiu $2, $2, %lo($CPI1_0)
254    //  lwc1 $f0, 0($2)
255    // Generate:
256    //  lui $2, %hi($CPI1_0)
257    //  lwc1 $f0, %lo($CPI1_0)($2)
258    if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
259        Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
260      SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
261      if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
262          isa<JumpTableSDNode>(Opnd0)) {
263        Base = Addr.getOperand(0);
264        Offset = Opnd0;
265        return true;
266      }
267    }
268  }
269
270  return false;
271}
272
273bool MipsSEDAGToDAGISel::selectAddrDefault(SDValue Addr, SDValue &Base,
274                                           SDValue &Offset) const {
275  Base = Addr;
276  Offset = CurDAG->getTargetConstant(0, Addr.getValueType());
277  return true;
278}
279
280bool MipsSEDAGToDAGISel::selectIntAddr(SDValue Addr, SDValue &Base,
281                                       SDValue &Offset) const {
282  return selectAddrRegImm(Addr, Base, Offset) ||
283    selectAddrDefault(Addr, Base, Offset);
284}
285
286std::pair<bool, SDNode*> MipsSEDAGToDAGISel::selectNode(SDNode *Node) {
287  unsigned Opcode = Node->getOpcode();
288  DebugLoc DL = Node->getDebugLoc();
289
290  ///
291  // Instruction Selection not handled by the auto-generated
292  // tablegen selection should be handled here.
293  ///
294  SDNode *Result;
295
296  switch(Opcode) {
297  default: break;
298
299  case ISD::SUBE: {
300    SDValue InFlag = Node->getOperand(2);
301    Result = selectAddESubE(Mips::SUBu, InFlag, InFlag.getOperand(0), DL, Node);
302    return std::make_pair(true, Result);
303  }
304
305  case ISD::ADDE: {
306    SDValue InFlag = Node->getOperand(2);
307    Result = selectAddESubE(Mips::ADDu, InFlag, InFlag.getValue(0), DL, Node);
308    return std::make_pair(true, Result);
309  }
310
311  case ISD::ConstantFP: {
312    ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
313    if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
314      if (Subtarget.hasMips64()) {
315        SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
316                                              Mips::ZERO_64, MVT::i64);
317        Result = CurDAG->getMachineNode(Mips::DMTC1, DL, MVT::f64, Zero);
318      } else {
319        SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL,
320                                              Mips::ZERO, MVT::i32);
321        Result = CurDAG->getMachineNode(Mips::BuildPairF64, DL, MVT::f64, Zero,
322                                        Zero);
323      }
324
325      return std::make_pair(true, Result);
326    }
327    break;
328  }
329
330  case ISD::Constant: {
331    const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
332    unsigned Size = CN->getValueSizeInBits(0);
333
334    if (Size == 32)
335      break;
336
337    MipsAnalyzeImmediate AnalyzeImm;
338    int64_t Imm = CN->getSExtValue();
339
340    const MipsAnalyzeImmediate::InstSeq &Seq =
341      AnalyzeImm.Analyze(Imm, Size, false);
342
343    MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
344    DebugLoc DL = CN->getDebugLoc();
345    SDNode *RegOpnd;
346    SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
347                                                MVT::i64);
348
349    // The first instruction can be a LUi which is different from other
350    // instructions (ADDiu, ORI and SLL) in that it does not have a register
351    // operand.
352    if (Inst->Opc == Mips::LUi64)
353      RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
354    else
355      RegOpnd =
356        CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
357                               CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
358                               ImmOpnd);
359
360    // The remaining instructions in the sequence are handled here.
361    for (++Inst; Inst != Seq.end(); ++Inst) {
362      ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
363                                          MVT::i64);
364      RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
365                                       SDValue(RegOpnd, 0), ImmOpnd);
366    }
367
368    return std::make_pair(true, RegOpnd);
369  }
370
371  case MipsISD::ThreadPointer: {
372    EVT PtrVT = TLI.getPointerTy();
373    unsigned RdhwrOpc, SrcReg, DestReg;
374
375    if (PtrVT == MVT::i32) {
376      RdhwrOpc = Mips::RDHWR;
377      SrcReg = Mips::HWR29;
378      DestReg = Mips::V1;
379    } else {
380      RdhwrOpc = Mips::RDHWR64;
381      SrcReg = Mips::HWR29_64;
382      DestReg = Mips::V1_64;
383    }
384
385    SDNode *Rdhwr =
386      CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
387                             Node->getValueType(0),
388                             CurDAG->getRegister(SrcReg, PtrVT));
389    SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), DL, DestReg,
390                                         SDValue(Rdhwr, 0));
391    SDValue ResNode = CurDAG->getCopyFromReg(Chain, DL, DestReg, PtrVT);
392    ReplaceUses(SDValue(Node, 0), ResNode);
393    return std::make_pair(true, ResNode.getNode());
394  }
395
396  case MipsISD::InsertLOHI: {
397    unsigned RCID = Subtarget.hasDSP() ? Mips::ACRegsDSPRegClassID :
398                                         Mips::ACRegsRegClassID;
399    SDValue RegClass = CurDAG->getTargetConstant(RCID, MVT::i32);
400    SDValue LoIdx = CurDAG->getTargetConstant(Mips::sub_lo, MVT::i32);
401    SDValue HiIdx = CurDAG->getTargetConstant(Mips::sub_hi, MVT::i32);
402    const SDValue Ops[] = { RegClass, Node->getOperand(0), LoIdx,
403                            Node->getOperand(1), HiIdx };
404    SDNode *Res = CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL,
405                                         MVT::Untyped, Ops, 5);
406    return std::make_pair(true, Res);
407  }
408  }
409
410  return std::make_pair(false, (SDNode*)NULL);
411}
412
413FunctionPass *llvm::createMipsSEISelDag(MipsTargetMachine &TM) {
414  return new MipsSEDAGToDAGISel(TM);
415}
416