782d2037043c85db49ce60517362f90d711bac7d
[oota-llvm.git] / lib / Target / Mips / MipsISelDAGToDAG.cpp
1 //===-- MipsISelDAGToDAG.cpp - A Dag to Dag Inst Selector for Mips --------===//
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 defines an instruction selector for the MIPS target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "mips-isel"
15 #include "Mips.h"
16 #include "MipsAnalyzeImmediate.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsRegisterInfo.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MCTargetDesc/MipsBaseInfo.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/SelectionDAGNodes.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 using namespace llvm;
39
40 //===----------------------------------------------------------------------===//
41 // Instruction Selector Implementation
42 //===----------------------------------------------------------------------===//
43
44 //===----------------------------------------------------------------------===//
45 // MipsDAGToDAGISel - MIPS specific code to select MIPS machine
46 // instructions for SelectionDAG operations.
47 //===----------------------------------------------------------------------===//
48 namespace {
49
50 class MipsDAGToDAGISel : public SelectionDAGISel {
51
52   /// TM - Keep a reference to MipsTargetMachine.
53   MipsTargetMachine &TM;
54
55   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
56   /// make the right decision when generating code for different targets.
57   const MipsSubtarget &Subtarget;
58
59 public:
60   explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
61   SelectionDAGISel(tm),
62   TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
63
64   // Pass Name
65   virtual const char *getPassName() const {
66     return "MIPS DAG->DAG Pattern Instruction Selection";
67   }
68
69   virtual bool runOnMachineFunction(MachineFunction &MF);
70
71 private:
72   // Include the pieces autogenerated from the target description.
73   #include "MipsGenDAGISel.inc"
74
75   /// getTargetMachine - Return a reference to the TargetMachine, casted
76   /// to the target-specific type.
77   const MipsTargetMachine &getTargetMachine() {
78     return static_cast<const MipsTargetMachine &>(TM);
79   }
80
81   /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
82   /// to the target-specific type.
83   const MipsInstrInfo *getInstrInfo() {
84     return getTargetMachine().getInstrInfo();
85   }
86
87   SDNode *getGlobalBaseReg();
88
89   std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl,
90                                          EVT Ty, bool HasLo, bool HasHi);
91
92   SDNode *Select(SDNode *N);
93
94   // Complex Pattern.
95   bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offset);
96
97   // getImm - Return a target constant with the specified value.
98   inline SDValue getImm(const SDNode *Node, unsigned Imm) {
99     return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
100   }
101
102   void InitGlobalBaseReg(MachineFunction &MF);
103
104   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
105                                             char ConstraintCode,
106                                             std::vector<SDValue> &OutOps);
107 };
108
109 }
110
111 // Insert instructions to initialize the global base register in the
112 // first MBB of the function. When the ABI is O32 and the relocation model is
113 // PIC, the necessary instructions are emitted later to prevent optimization
114 // passes from moving them.
115 void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
116   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
117
118   if (!MipsFI->globalBaseRegSet())
119     return;
120
121   MachineBasicBlock &MBB = MF.front();
122   MachineBasicBlock::iterator I = MBB.begin();
123   MachineRegisterInfo &RegInfo = MF.getRegInfo();
124   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
125   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
126   unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
127   bool FixGlobalBaseReg = MipsFI->globalBaseRegFixed();
128
129   if (Subtarget.isABI_O32() && FixGlobalBaseReg)
130     // $gp is the global base register.
131     V0 = V1 = GlobalBaseReg;
132   else {
133     const TargetRegisterClass *RC;
134     RC = Subtarget.isABI_N64() ?
135          Mips::CPU64RegsRegisterClass : Mips::CPURegsRegisterClass;
136
137     V0 = RegInfo.createVirtualRegister(RC);
138     V1 = RegInfo.createVirtualRegister(RC);
139   }
140
141   if (Subtarget.isABI_N64()) {
142     MF.getRegInfo().addLiveIn(Mips::T9_64);
143
144     // lui $v0, %hi(%neg(%gp_rel(fname)))
145     // daddu $v1, $v0, $t9
146     // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
147     const GlobalValue *FName = MF.getFunction();
148     BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
149       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
150     BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0).addReg(Mips::T9_64);
151     BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
152       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
153   } else if (MF.getTarget().getRelocationModel() == Reloc::Static) {
154     // Set global register to __gnu_local_gp.
155     //
156     // lui   $v0, %hi(__gnu_local_gp)
157     // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
158     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
159       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
160     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
161       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
162   } else {
163     MF.getRegInfo().addLiveIn(Mips::T9);
164
165     if (Subtarget.isABI_N32()) {
166       // lui $v0, %hi(%neg(%gp_rel(fname)))
167       // addu $v1, $v0, $t9
168       // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
169       const GlobalValue *FName = MF.getFunction();
170       BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
171         .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
172       BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
173       BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
174         .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
175     } else if (!MipsFI->globalBaseRegFixed()) {
176       assert(Subtarget.isABI_O32());
177
178       BuildMI(MBB, I, DL, TII.get(Mips::SETGP2), GlobalBaseReg)
179         .addReg(Mips::T9);
180     }
181   }
182 }
183
184 bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
185   bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
186
187   InitGlobalBaseReg(MF);
188
189   return Ret;
190 }
191
192 /// getGlobalBaseReg - Output the instructions required to put the
193 /// GOT address into a register.
194 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
195   unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
196   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
197 }
198
199 /// ComplexPattern used on MipsInstrInfo
200 /// Used on Mips Load/Store instructions
201 bool MipsDAGToDAGISel::
202 SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset) {
203   EVT ValTy = Addr.getValueType();
204
205   // If Parent is an unaligned f32 load or store, select a (base + index)
206   // floating point load/store instruction (luxc1 or suxc1).
207   const LSBaseSDNode* LS = 0;
208
209   if (Parent && (LS = dyn_cast<LSBaseSDNode>(Parent))) {
210     EVT VT = LS->getMemoryVT();
211
212     if (VT.getSizeInBits() / 8 > LS->getAlignment()) {
213       assert(TLI.allowsUnalignedMemoryAccesses(VT) &&
214              "Unaligned loads/stores not supported for this type.");
215       if (VT == MVT::f32)
216         return false;
217     }
218   }
219
220   // if Address is FI, get the TargetFrameIndex.
221   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
222     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
223     Offset = CurDAG->getTargetConstant(0, ValTy);
224     return true;
225   }
226
227   // on PIC code Load GA
228   if (Addr.getOpcode() == MipsISD::Wrapper) {
229     Base   = Addr.getOperand(0);
230     Offset = Addr.getOperand(1);
231     return true;
232   }
233
234   if (TM.getRelocationModel() != Reloc::PIC_) {
235     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
236         Addr.getOpcode() == ISD::TargetGlobalAddress))
237       return false;
238   }
239
240   // Addresses of the form FI+const or FI|const
241   if (CurDAG->isBaseWithConstantOffset(Addr)) {
242     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
243     if (isInt<16>(CN->getSExtValue())) {
244
245       // If the first operand is a FI, get the TargetFI Node
246       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
247                                   (Addr.getOperand(0)))
248         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
249       else
250         Base = Addr.getOperand(0);
251
252       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
253       return true;
254     }
255   }
256
257   // Operand is a result from an ADD.
258   if (Addr.getOpcode() == ISD::ADD) {
259     // When loading from constant pools, load the lower address part in
260     // the instruction itself. Example, instead of:
261     //  lui $2, %hi($CPI1_0)
262     //  addiu $2, $2, %lo($CPI1_0)
263     //  lwc1 $f0, 0($2)
264     // Generate:
265     //  lui $2, %hi($CPI1_0)
266     //  lwc1 $f0, %lo($CPI1_0)($2)
267     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
268       SDValue LoVal = Addr.getOperand(1);
269       if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||
270           isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
271         Base = Addr.getOperand(0);
272         Offset = LoVal.getOperand(0);
273         return true;
274       }
275     }
276
277     // If an indexed floating point load/store can be emitted, return false.
278     if (LS && (LS->getMemoryVT() == MVT::f32 || LS->getMemoryVT() == MVT::f64) &&
279         Subtarget.hasMips32r2Or64())
280       return false;
281   }
282
283   Base   = Addr;
284   Offset = CurDAG->getTargetConstant(0, ValTy);
285   return true;
286 }
287
288 /// Select multiply instructions.
289 std::pair<SDNode*, SDNode*>
290 MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
291                              bool HasLo, bool HasHi) {
292   SDNode *Lo = 0, *Hi = 0;
293   SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
294                                        N->getOperand(1));
295   SDValue InFlag = SDValue(Mul, 0);
296
297   if (HasLo) {
298     Lo = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64, dl,
299                                 Ty, MVT::Glue, InFlag);
300     InFlag = SDValue(Lo, 1);
301   }
302   if (HasHi)
303     Hi = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64, dl,
304                                 Ty, InFlag);
305
306   return std::make_pair(Lo, Hi);
307 }
308
309
310 /// Select instructions not customized! Used for
311 /// expanded, promoted and normal instructions
312 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
313   unsigned Opcode = Node->getOpcode();
314   DebugLoc dl = Node->getDebugLoc();
315
316   // Dump information about the Node being selected
317   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
318
319   // If we have a custom node, we already have selected!
320   if (Node->isMachineOpcode()) {
321     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
322     return NULL;
323   }
324
325   ///
326   // Instruction Selection not handled by the auto-generated
327   // tablegen selection should be handled here.
328   ///
329   EVT NodeTy = Node->getValueType(0);
330   unsigned MultOpc;
331
332   switch(Opcode) {
333   default: break;
334
335   case ISD::SUBE:
336   case ISD::ADDE: {
337     SDValue InFlag = Node->getOperand(2), CmpLHS;
338     unsigned Opc = InFlag.getOpcode(); (void)Opc;
339     assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
340             (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
341            "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
342
343     unsigned MOp;
344     if (Opcode == ISD::ADDE) {
345       CmpLHS = InFlag.getValue(0);
346       MOp = Mips::ADDu;
347     } else {
348       CmpLHS = InFlag.getOperand(0);
349       MOp = Mips::SUBu;
350     }
351
352     SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
353
354     SDValue LHS = Node->getOperand(0);
355     SDValue RHS = Node->getOperand(1);
356
357     EVT VT = LHS.getValueType();
358     SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
359     SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
360                                               SDValue(Carry,0), RHS);
361
362     return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
363                                 LHS, SDValue(AddCarry,0));
364   }
365
366   /// Mul with two results
367   case ISD::SMUL_LOHI:
368   case ISD::UMUL_LOHI: {
369     if (NodeTy == MVT::i32)
370       MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
371     else
372       MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
373
374     std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
375                                                   true, true);
376
377     if (!SDValue(Node, 0).use_empty())
378       ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
379
380     if (!SDValue(Node, 1).use_empty())
381       ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
382
383     return NULL;
384   }
385
386   /// Special Muls
387   case ISD::MUL: {
388     // Mips32 has a 32-bit three operand mul instruction.
389     if (Subtarget.hasMips32() && NodeTy == MVT::i32)
390       break;
391     return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
392                       dl, NodeTy, true, false).first;
393   }
394   case ISD::MULHS:
395   case ISD::MULHU: {
396     if (NodeTy == MVT::i32)
397       MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
398     else
399       MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
400
401     return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
402   }
403
404   // Get target GOT address.
405   case ISD::GLOBAL_OFFSET_TABLE:
406     return getGlobalBaseReg();
407
408   case ISD::ConstantFP: {
409     ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
410     if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
411       if (Subtarget.hasMips64()) {
412         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
413                                               Mips::ZERO_64, MVT::i64);
414         return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
415       }
416
417       SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
418                                             Mips::ZERO, MVT::i32);
419       return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
420                                     Zero);
421     }
422     break;
423   }
424
425   case ISD::Constant: {
426     const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
427     unsigned Size = CN->getValueSizeInBits(0);
428
429     if (Size == 32)
430       break;
431
432     MipsAnalyzeImmediate AnalyzeImm;
433     int64_t Imm = CN->getSExtValue();
434
435     const MipsAnalyzeImmediate::InstSeq &Seq =
436       AnalyzeImm.Analyze(Imm, Size, false);
437
438     MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
439     DebugLoc DL = CN->getDebugLoc();
440     SDNode *RegOpnd;
441     SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
442                                                 MVT::i64);
443
444     // The first instruction can be a LUi which is different from other
445     // instructions (ADDiu, ORI and SLL) in that it does not have a register
446     // operand.
447     if (Inst->Opc == Mips::LUi64)
448       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
449     else
450       RegOpnd =
451         CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
452                                CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
453                                ImmOpnd);
454
455     // The remaining instructions in the sequence are handled here.
456     for (++Inst; Inst != Seq.end(); ++Inst) {
457       ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
458                                           MVT::i64);
459       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
460                                        SDValue(RegOpnd, 0), ImmOpnd);
461     }
462
463     return RegOpnd;
464   }
465
466   case MipsISD::ThreadPointer: {
467     EVT PtrVT = TLI.getPointerTy();
468     unsigned RdhwrOpc, SrcReg, DestReg;
469
470     if (PtrVT == MVT::i32) {
471       RdhwrOpc = Mips::RDHWR;
472       SrcReg = Mips::HWR29;
473       DestReg = Mips::V1;
474     } else {
475       RdhwrOpc = Mips::RDHWR64;
476       SrcReg = Mips::HWR29_64;
477       DestReg = Mips::V1_64;
478     }
479
480     SDNode *Rdhwr =
481       CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
482                              Node->getValueType(0),
483                              CurDAG->getRegister(SrcReg, PtrVT));
484     SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
485                                          SDValue(Rdhwr, 0));
486     SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
487     ReplaceUses(SDValue(Node, 0), ResNode);
488     return ResNode.getNode();
489   }
490   }
491
492   // Select the default instruction
493   SDNode *ResNode = SelectCode(Node);
494
495   DEBUG(errs() << "=> ");
496   if (ResNode == NULL || ResNode == Node)
497     DEBUG(Node->dump(CurDAG));
498   else
499     DEBUG(ResNode->dump(CurDAG));
500   DEBUG(errs() << "\n");
501   return ResNode;
502 }
503
504 bool MipsDAGToDAGISel::
505 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
506                              std::vector<SDValue> &OutOps) {
507   assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
508   OutOps.push_back(Op);
509   return false;
510 }
511
512 /// createMipsISelDag - This pass converts a legalized DAG into a
513 /// MIPS-specific DAG, ready for instruction scheduling.
514 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
515   return new MipsDAGToDAGISel(TM);
516 }