[mips] Remove SDNPWantParent from the list of SDNodeProperties.
[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 "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsAnalyzeImmediate.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsRegisterInfo.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "llvm/CodeGen/MachineConstantPool.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/SelectionDAGISel.h"
28 #include "llvm/CodeGen/SelectionDAGNodes.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Type.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetMachine.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   SDValue getMips16SPAliasReg();
90
91   void getMips16SPRefReg(SDNode *parent, SDValue &AliasReg);
92
93   std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl,
94                                          EVT Ty, bool HasLo, bool HasHi);
95
96   SDNode *Select(SDNode *N);
97
98   // Complex Pattern.
99   /// (reg + imm).
100   bool selectAddrRegImm(SDValue Addr, SDValue &Base, SDValue &Offset) const;
101
102   /// Fall back on this function if all else fails.
103   bool selectAddrDefault(SDValue Addr, SDValue &Base, SDValue &Offset) const;
104
105   /// Match integer address pattern.
106   bool selectIntAddr(SDValue Addr, SDValue &Base, SDValue &Offset) const;
107
108   bool SelectAddr16(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offset,
109        SDValue &Alias);
110
111   // getImm - Return a target constant with the specified value.
112   inline SDValue getImm(const SDNode *Node, unsigned Imm) {
113     return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
114   }
115
116   void ProcessFunctionAfterISel(MachineFunction &MF);
117   bool ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI, const MachineInstr&);
118   void InitGlobalBaseReg(MachineFunction &MF);
119   void InitMips16SPAliasReg(MachineFunction &MF);
120
121   virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
122                                             char ConstraintCode,
123                                             std::vector<SDValue> &OutOps);
124 };
125
126 }
127
128 // Insert instructions to initialize the global base register in the
129 // first MBB of the function. When the ABI is O32 and the relocation model is
130 // PIC, the necessary instructions are emitted later to prevent optimization
131 // passes from moving them.
132 void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
133   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
134
135   if (!MipsFI->globalBaseRegSet())
136     return;
137
138   MachineBasicBlock &MBB = MF.front();
139   MachineBasicBlock::iterator I = MBB.begin();
140   MachineRegisterInfo &RegInfo = MF.getRegInfo();
141   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
142   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
143   unsigned V0, V1, V2, GlobalBaseReg = MipsFI->getGlobalBaseReg();
144   const TargetRegisterClass *RC;
145
146   if (Subtarget.isABI_N64())
147     RC = (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
148   else if (Subtarget.inMips16Mode())
149     RC = (const TargetRegisterClass*)&Mips::CPU16RegsRegClass;
150   else
151     RC = (const TargetRegisterClass*)&Mips::CPURegsRegClass;
152
153   V0 = RegInfo.createVirtualRegister(RC);
154   V1 = RegInfo.createVirtualRegister(RC);
155   V2 = RegInfo.createVirtualRegister(RC);
156
157   if (Subtarget.isABI_N64()) {
158     MF.getRegInfo().addLiveIn(Mips::T9_64);
159     MBB.addLiveIn(Mips::T9_64);
160
161     // lui $v0, %hi(%neg(%gp_rel(fname)))
162     // daddu $v1, $v0, $t9
163     // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
164     const GlobalValue *FName = MF.getFunction();
165     BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
166       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
167     BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
168       .addReg(Mips::T9_64);
169     BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
170       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
171     return;
172   }
173
174   if (Subtarget.inMips16Mode()) {
175     BuildMI(MBB, I, DL, TII.get(Mips::LiRxImmX16), V0)
176       .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
177     BuildMI(MBB, I, DL, TII.get(Mips::AddiuRxPcImmX16), V1)
178       .addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
179     BuildMI(MBB, I, DL, TII.get(Mips::SllX16), V2).addReg(V0).addImm(16);
180     BuildMI(MBB, I, DL, TII.get(Mips::AdduRxRyRz16), GlobalBaseReg)
181       .addReg(V1).addReg(V2);
182     return;
183   }
184
185   if (MF.getTarget().getRelocationModel() == Reloc::Static) {
186     // Set global register to __gnu_local_gp.
187     //
188     // lui   $v0, %hi(__gnu_local_gp)
189     // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
190     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
191       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
192     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
193       .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
194     return;
195   }
196
197   MF.getRegInfo().addLiveIn(Mips::T9);
198   MBB.addLiveIn(Mips::T9);
199
200   if (Subtarget.isABI_N32()) {
201     // lui $v0, %hi(%neg(%gp_rel(fname)))
202     // addu $v1, $v0, $t9
203     // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
204     const GlobalValue *FName = MF.getFunction();
205     BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
206       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
207     BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
208     BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
209       .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
210     return;
211   }
212
213   assert(Subtarget.isABI_O32());
214
215   // For O32 ABI, the following instruction sequence is emitted to initialize
216   // the global base register:
217   //
218   //  0. lui   $2, %hi(_gp_disp)
219   //  1. addiu $2, $2, %lo(_gp_disp)
220   //  2. addu  $globalbasereg, $2, $t9
221   //
222   // We emit only the last instruction here.
223   //
224   // GNU linker requires that the first two instructions appear at the beginning
225   // of a function and no instructions be inserted before or between them.
226   // The two instructions are emitted during lowering to MC layer in order to
227   // avoid any reordering.
228   //
229   // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
230   // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
231   // reads it.
232   MF.getRegInfo().addLiveIn(Mips::V0);
233   MBB.addLiveIn(Mips::V0);
234   BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
235     .addReg(Mips::V0).addReg(Mips::T9);
236 }
237
238 // Insert instructions to initialize the Mips16 SP Alias register in the
239 // first MBB of the function.
240 //
241 void MipsDAGToDAGISel::InitMips16SPAliasReg(MachineFunction &MF) {
242   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
243
244   if (!MipsFI->mips16SPAliasRegSet())
245     return;
246
247   MachineBasicBlock &MBB = MF.front();
248   MachineBasicBlock::iterator I = MBB.begin();
249   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
250   DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
251   unsigned Mips16SPAliasReg = MipsFI->getMips16SPAliasReg();
252
253   BuildMI(MBB, I, DL, TII.get(Mips::MoveR3216), Mips16SPAliasReg)
254     .addReg(Mips::SP);
255 }
256
257
258 bool MipsDAGToDAGISel::ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI,
259                                               const MachineInstr& MI) {
260   unsigned DstReg = 0, ZeroReg = 0;
261
262   // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
263   if ((MI.getOpcode() == Mips::ADDiu) &&
264       (MI.getOperand(1).getReg() == Mips::ZERO) &&
265       (MI.getOperand(2).getImm() == 0)) {
266     DstReg = MI.getOperand(0).getReg();
267     ZeroReg = Mips::ZERO;
268   } else if ((MI.getOpcode() == Mips::DADDiu) &&
269              (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
270              (MI.getOperand(2).getImm() == 0)) {
271     DstReg = MI.getOperand(0).getReg();
272     ZeroReg = Mips::ZERO_64;
273   }
274
275   if (!DstReg)
276     return false;
277
278   // Replace uses with ZeroReg.
279   for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
280        E = MRI->use_end(); U != E;) {
281     MachineOperand &MO = U.getOperand();
282     unsigned OpNo = U.getOperandNo();
283     MachineInstr *MI = MO.getParent();
284     ++U;
285
286     // Do not replace if it is a phi's operand or is tied to def operand.
287     if (MI->isPHI() || MI->isRegTiedToDefOperand(OpNo) || MI->isPseudo())
288       continue;
289
290     MO.setReg(ZeroReg);
291   }
292
293   return true;
294 }
295
296 void MipsDAGToDAGISel::ProcessFunctionAfterISel(MachineFunction &MF) {
297   InitGlobalBaseReg(MF);
298   InitMips16SPAliasReg(MF);
299
300   MachineRegisterInfo *MRI = &MF.getRegInfo();
301
302   for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
303        ++MFI)
304     for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
305       ReplaceUsesWithZeroReg(MRI, *I);
306 }
307
308 bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
309   bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
310
311   ProcessFunctionAfterISel(MF);
312
313   return Ret;
314 }
315
316 /// getGlobalBaseReg - Output the instructions required to put the
317 /// GOT address into a register.
318 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
319   unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
320   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
321 }
322
323 /// getMips16SPAliasReg - Output the instructions required to put the
324 /// SP into a Mips16 accessible aliased register.
325 SDValue MipsDAGToDAGISel::getMips16SPAliasReg() {
326   unsigned Mips16SPAliasReg =
327     MF->getInfo<MipsFunctionInfo>()->getMips16SPAliasReg();
328   return CurDAG->getRegister(Mips16SPAliasReg, TLI.getPointerTy());
329 }
330
331 /// ComplexPattern used on MipsInstrInfo
332 /// Used on Mips Load/Store instructions
333 bool MipsDAGToDAGISel::selectAddrRegImm(SDValue Addr, SDValue &Base,
334                                         SDValue &Offset) const {
335   EVT ValTy = Addr.getValueType();
336
337   // if Address is FI, get the TargetFrameIndex.
338   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
339     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
340     Offset = CurDAG->getTargetConstant(0, ValTy);
341     return true;
342   }
343
344   // on PIC code Load GA
345   if (Addr.getOpcode() == MipsISD::Wrapper) {
346     Base   = Addr.getOperand(0);
347     Offset = Addr.getOperand(1);
348     return true;
349   }
350
351   if (TM.getRelocationModel() != Reloc::PIC_) {
352     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
353         Addr.getOpcode() == ISD::TargetGlobalAddress))
354       return false;
355   }
356
357   // Addresses of the form FI+const or FI|const
358   if (CurDAG->isBaseWithConstantOffset(Addr)) {
359     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
360     if (isInt<16>(CN->getSExtValue())) {
361
362       // If the first operand is a FI, get the TargetFI Node
363       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
364                                   (Addr.getOperand(0)))
365         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
366       else
367         Base = Addr.getOperand(0);
368
369       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
370       return true;
371     }
372   }
373
374   // Operand is a result from an ADD.
375   if (Addr.getOpcode() == ISD::ADD) {
376     // When loading from constant pools, load the lower address part in
377     // the instruction itself. Example, instead of:
378     //  lui $2, %hi($CPI1_0)
379     //  addiu $2, $2, %lo($CPI1_0)
380     //  lwc1 $f0, 0($2)
381     // Generate:
382     //  lui $2, %hi($CPI1_0)
383     //  lwc1 $f0, %lo($CPI1_0)($2)
384     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
385         Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
386       SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
387       if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
388           isa<JumpTableSDNode>(Opnd0)) {
389         Base = Addr.getOperand(0);
390         Offset = Opnd0;
391         return true;
392       }
393     }
394   }
395
396   return false;
397 }
398
399 bool MipsDAGToDAGISel::selectAddrDefault(SDValue Addr, SDValue &Base,
400                                          SDValue &Offset) const {
401   Base = Addr;
402   Offset = CurDAG->getTargetConstant(0, Addr.getValueType());
403   return true;
404 }
405
406 bool MipsDAGToDAGISel::selectIntAddr(SDValue Addr, SDValue &Base,
407                                      SDValue &Offset) const {
408   return selectAddrRegImm(Addr, Base, Offset) ||
409     selectAddrDefault(Addr, Base, Offset);
410 }
411
412 void MipsDAGToDAGISel::getMips16SPRefReg(SDNode *Parent, SDValue &AliasReg) {
413   SDValue AliasFPReg = CurDAG->getRegister(Mips::S0, TLI.getPointerTy());
414   if (Parent) {
415     switch (Parent->getOpcode()) {
416       case ISD::LOAD: {
417         LoadSDNode *SD = dyn_cast<LoadSDNode>(Parent);
418         switch (SD->getMemoryVT().getSizeInBits()) {
419         case 8:
420         case 16:
421           AliasReg = TM.getFrameLowering()->hasFP(*MF)?
422             AliasFPReg: getMips16SPAliasReg();
423           return;
424         }
425         break;
426       }
427       case ISD::STORE: {
428         StoreSDNode *SD = dyn_cast<StoreSDNode>(Parent);
429         switch (SD->getMemoryVT().getSizeInBits()) {
430         case 8:
431         case 16:
432           AliasReg = TM.getFrameLowering()->hasFP(*MF)?
433             AliasFPReg: getMips16SPAliasReg();
434           return;
435         }
436         break;
437       }
438     }
439   }
440   AliasReg = CurDAG->getRegister(Mips::SP, TLI.getPointerTy());
441   return;
442
443 }
444 bool MipsDAGToDAGISel::SelectAddr16(
445   SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset,
446   SDValue &Alias) {
447   EVT ValTy = Addr.getValueType();
448
449   Alias = CurDAG->getTargetConstant(0, ValTy);
450
451   // if Address is FI, get the TargetFrameIndex.
452   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
453     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
454     Offset = CurDAG->getTargetConstant(0, ValTy);
455     getMips16SPRefReg(Parent, Alias);
456     return true;
457   }
458   // on PIC code Load GA
459   if (Addr.getOpcode() == MipsISD::Wrapper) {
460     Base   = Addr.getOperand(0);
461     Offset = Addr.getOperand(1);
462     return true;
463   }
464   if (TM.getRelocationModel() != Reloc::PIC_) {
465     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
466         Addr.getOpcode() == ISD::TargetGlobalAddress))
467       return false;
468   }
469   // Addresses of the form FI+const or FI|const
470   if (CurDAG->isBaseWithConstantOffset(Addr)) {
471     ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
472     if (isInt<16>(CN->getSExtValue())) {
473
474       // If the first operand is a FI, get the TargetFI Node
475       if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
476                                   (Addr.getOperand(0))) {
477         Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
478         getMips16SPRefReg(Parent, Alias);
479       }
480       else
481         Base = Addr.getOperand(0);
482
483       Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
484       return true;
485     }
486   }
487   // Operand is a result from an ADD.
488   if (Addr.getOpcode() == ISD::ADD) {
489     // When loading from constant pools, load the lower address part in
490     // the instruction itself. Example, instead of:
491     //  lui $2, %hi($CPI1_0)
492     //  addiu $2, $2, %lo($CPI1_0)
493     //  lwc1 $f0, 0($2)
494     // Generate:
495     //  lui $2, %hi($CPI1_0)
496     //  lwc1 $f0, %lo($CPI1_0)($2)
497     if (Addr.getOperand(1).getOpcode() == MipsISD::Lo ||
498         Addr.getOperand(1).getOpcode() == MipsISD::GPRel) {
499       SDValue Opnd0 = Addr.getOperand(1).getOperand(0);
500       if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
501           isa<JumpTableSDNode>(Opnd0)) {
502         Base = Addr.getOperand(0);
503         Offset = Opnd0;
504         return true;
505       }
506     }
507
508     // If an indexed floating point load/store can be emitted, return false.
509     const LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(Parent);
510
511     if (LS &&
512         (LS->getMemoryVT() == MVT::f32 || LS->getMemoryVT() == MVT::f64) &&
513         Subtarget.hasFPIdx())
514       return false;
515   }
516   Base   = Addr;
517   Offset = CurDAG->getTargetConstant(0, ValTy);
518   return true;
519 }
520
521 /// Select multiply instructions.
522 std::pair<SDNode*, SDNode*>
523 MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
524                              bool HasLo, bool HasHi) {
525   SDNode *Lo = 0, *Hi = 0;
526   SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
527                                        N->getOperand(1));
528   SDValue InFlag = SDValue(Mul, 0);
529
530   if (HasLo) {
531     unsigned Opcode = Subtarget.inMips16Mode() ? Mips::Mflo16 :
532       (Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64);
533     Lo = CurDAG->getMachineNode(Opcode, dl, Ty, MVT::Glue, InFlag);
534     InFlag = SDValue(Lo, 1);
535   }
536   if (HasHi) {
537     unsigned Opcode = Subtarget.inMips16Mode() ? Mips::Mfhi16 :
538       (Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64);
539     Hi = CurDAG->getMachineNode(Opcode, dl, Ty, InFlag);
540   }
541   return std::make_pair(Lo, Hi);
542 }
543
544
545 /// Select instructions not customized! Used for
546 /// expanded, promoted and normal instructions
547 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
548   unsigned Opcode = Node->getOpcode();
549   DebugLoc dl = Node->getDebugLoc();
550
551   // Dump information about the Node being selected
552   DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
553
554   // If we have a custom node, we already have selected!
555   if (Node->isMachineOpcode()) {
556     DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
557     return NULL;
558   }
559
560   ///
561   // Instruction Selection not handled by the auto-generated
562   // tablegen selection should be handled here.
563   ///
564   EVT NodeTy = Node->getValueType(0);
565   unsigned MultOpc;
566
567   switch(Opcode) {
568   default: break;
569
570   case ISD::SUBE:
571   case ISD::ADDE: {
572     bool inMips16Mode = Subtarget.inMips16Mode();
573     SDValue InFlag = Node->getOperand(2), CmpLHS;
574     unsigned Opc = InFlag.getOpcode(); (void)Opc;
575     assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
576             (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
577            "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
578
579     unsigned MOp;
580     if (Opcode == ISD::ADDE) {
581       CmpLHS = InFlag.getValue(0);
582       if (inMips16Mode)
583         MOp = Mips::AdduRxRyRz16;
584       else
585         MOp = Mips::ADDu;
586     } else {
587       CmpLHS = InFlag.getOperand(0);
588       if (inMips16Mode)
589         MOp = Mips::SubuRxRyRz16;
590       else
591         MOp = Mips::SUBu;
592     }
593
594     SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
595
596     SDValue LHS = Node->getOperand(0);
597     SDValue RHS = Node->getOperand(1);
598
599     EVT VT = LHS.getValueType();
600
601     unsigned Sltu_op = inMips16Mode? Mips::SltuRxRyRz16: Mips::SLTu;
602     SDNode *Carry = CurDAG->getMachineNode(Sltu_op, dl, VT, Ops, 2);
603     unsigned Addu_op = inMips16Mode? Mips::AdduRxRyRz16 : Mips::ADDu;
604     SDNode *AddCarry = CurDAG->getMachineNode(Addu_op, dl, VT,
605                                               SDValue(Carry,0), RHS);
606
607     return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
608                                 LHS, SDValue(AddCarry,0));
609   }
610
611   /// Mul with two results
612   case ISD::SMUL_LOHI:
613   case ISD::UMUL_LOHI: {
614     if (NodeTy == MVT::i32) {
615       if (Subtarget.inMips16Mode())
616         MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MultuRxRy16 :
617                    Mips::MultRxRy16);
618       else
619         MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
620     }
621     else
622       MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
623
624     std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
625                                                   true, true);
626
627     if (!SDValue(Node, 0).use_empty())
628       ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
629
630     if (!SDValue(Node, 1).use_empty())
631       ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
632
633     return NULL;
634   }
635
636   /// Special Muls
637   case ISD::MUL: {
638     // Mips32 has a 32-bit three operand mul instruction.
639     if (Subtarget.hasMips32() && NodeTy == MVT::i32)
640       break;
641     return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
642                       dl, NodeTy, true, false).first;
643   }
644   case ISD::MULHS:
645   case ISD::MULHU: {
646     if (NodeTy == MVT::i32) {
647       if (Subtarget.inMips16Mode())
648         MultOpc = (Opcode == ISD::MULHU ?
649                    Mips::MultuRxRy16 : Mips::MultRxRy16);
650       else
651         MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
652     }
653     else
654       MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
655
656     return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
657   }
658
659   // Get target GOT address.
660   case ISD::GLOBAL_OFFSET_TABLE:
661     return getGlobalBaseReg();
662
663   case ISD::ConstantFP: {
664     ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
665     if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
666       if (Subtarget.hasMips64()) {
667         SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
668                                               Mips::ZERO_64, MVT::i64);
669         return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
670       }
671
672       SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
673                                             Mips::ZERO, MVT::i32);
674       return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
675                                     Zero);
676     }
677     break;
678   }
679
680   case ISD::Constant: {
681     const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
682     unsigned Size = CN->getValueSizeInBits(0);
683
684     if (Size == 32)
685       break;
686
687     MipsAnalyzeImmediate AnalyzeImm;
688     int64_t Imm = CN->getSExtValue();
689
690     const MipsAnalyzeImmediate::InstSeq &Seq =
691       AnalyzeImm.Analyze(Imm, Size, false);
692
693     MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
694     DebugLoc DL = CN->getDebugLoc();
695     SDNode *RegOpnd;
696     SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
697                                                 MVT::i64);
698
699     // The first instruction can be a LUi which is different from other
700     // instructions (ADDiu, ORI and SLL) in that it does not have a register
701     // operand.
702     if (Inst->Opc == Mips::LUi64)
703       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
704     else
705       RegOpnd =
706         CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
707                                CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
708                                ImmOpnd);
709
710     // The remaining instructions in the sequence are handled here.
711     for (++Inst; Inst != Seq.end(); ++Inst) {
712       ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
713                                           MVT::i64);
714       RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
715                                        SDValue(RegOpnd, 0), ImmOpnd);
716     }
717
718     return RegOpnd;
719   }
720
721 #ifndef NDEBUG
722   case ISD::LOAD:
723   case ISD::STORE:
724     assert(cast<MemSDNode>(Node)->getMemoryVT().getSizeInBits() / 8 <=
725            cast<MemSDNode>(Node)->getAlignment() &&
726            "Unexpected unaligned loads/stores.");
727     break;
728 #endif
729
730   case MipsISD::ThreadPointer: {
731     EVT PtrVT = TLI.getPointerTy();
732     unsigned RdhwrOpc, SrcReg, DestReg;
733
734     if (PtrVT == MVT::i32) {
735       RdhwrOpc = Mips::RDHWR;
736       SrcReg = Mips::HWR29;
737       DestReg = Mips::V1;
738     } else {
739       RdhwrOpc = Mips::RDHWR64;
740       SrcReg = Mips::HWR29_64;
741       DestReg = Mips::V1_64;
742     }
743
744     SDNode *Rdhwr =
745       CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
746                              Node->getValueType(0),
747                              CurDAG->getRegister(SrcReg, PtrVT));
748     SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
749                                          SDValue(Rdhwr, 0));
750     SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
751     ReplaceUses(SDValue(Node, 0), ResNode);
752     return ResNode.getNode();
753   }
754   }
755
756   // Select the default instruction
757   SDNode *ResNode = SelectCode(Node);
758
759   DEBUG(errs() << "=> ");
760   if (ResNode == NULL || ResNode == Node)
761     DEBUG(Node->dump(CurDAG));
762   else
763     DEBUG(ResNode->dump(CurDAG));
764   DEBUG(errs() << "\n");
765   return ResNode;
766 }
767
768 bool MipsDAGToDAGISel::
769 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
770                              std::vector<SDValue> &OutOps) {
771   assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
772   OutOps.push_back(Op);
773   return false;
774 }
775
776 /// createMipsISelDag - This pass converts a legalized DAG into a
777 /// MIPS-specific DAG, ready for instruction scheduling.
778 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
779   return new MipsDAGToDAGISel(TM);
780 }