Reapply 91184 with fixes and an addition to the testcase to cover the problem
[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 "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsRegisterInfo.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "llvm/GlobalValue.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/Support/CFG.h"
25 #include "llvm/Type.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 using namespace llvm;
37
38 //===----------------------------------------------------------------------===//
39 // Instruction Selector Implementation
40 //===----------------------------------------------------------------------===//
41
42 //===----------------------------------------------------------------------===//
43 // MipsDAGToDAGISel - MIPS specific code to select MIPS machine
44 // instructions for SelectionDAG operations.
45 //===----------------------------------------------------------------------===//
46 namespace {
47
48 class MipsDAGToDAGISel : public SelectionDAGISel {
49
50   /// TM - Keep a reference to MipsTargetMachine.
51   MipsTargetMachine &TM;
52
53   /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
54   /// make the right decision when generating code for different targets.
55   const MipsSubtarget &Subtarget;
56  
57 public:
58   explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
59   SelectionDAGISel(tm),
60   TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
61   
62   virtual void InstructionSelect();
63
64   // Pass Name
65   virtual const char *getPassName() const {
66     return "MIPS DAG->DAG Pattern Instruction Selection";
67   } 
68   
69
70 private:  
71   // Include the pieces autogenerated from the target description.
72   #include "MipsGenDAGISel.inc"
73
74   /// getTargetMachine - Return a reference to the TargetMachine, casted
75   /// to the target-specific type.
76   const MipsTargetMachine &getTargetMachine() {
77     return static_cast<const MipsTargetMachine &>(TM);
78   }
79
80   /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
81   /// to the target-specific type.
82   const MipsInstrInfo *getInstrInfo() {
83     return getTargetMachine().getInstrInfo();
84   }
85
86   SDNode *getGlobalBaseReg();
87   SDNode *Select(SDValue N);
88
89   // Complex Pattern.
90   bool SelectAddr(SDValue Op, SDValue N, 
91                   SDValue &Base, SDValue &Offset);
92
93   SDNode *SelectLoadFp64(SDValue N);
94   SDNode *SelectStoreFp64(SDValue N);
95
96   // getI32Imm - Return a target constant with the specified
97   // value, of type i32.
98   inline SDValue getI32Imm(unsigned Imm) {
99     return CurDAG->getTargetConstant(Imm, MVT::i32);
100   }
101
102
103   #ifndef NDEBUG
104   unsigned Indent;
105   #endif
106 };
107
108 }
109
110 /// InstructionSelect - This callback is invoked by
111 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
112 void MipsDAGToDAGISel::InstructionSelect() {
113   // Codegen the basic block.
114   DEBUG(errs() << "===== Instruction selection begins:\n");
115   DEBUG(Indent = 0);
116
117   // Select target instructions for the DAG.
118   SelectRoot(*CurDAG);
119
120   DEBUG(errs() << "===== Instruction selection ends:\n");
121
122   CurDAG->RemoveDeadNodes();
123 }
124
125 /// getGlobalBaseReg - Output the instructions required to put the
126 /// GOT address into a register.
127 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
128   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
129   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
130 }
131
132 /// ComplexPattern used on MipsInstrInfo
133 /// Used on Mips Load/Store instructions
134 bool MipsDAGToDAGISel::
135 SelectAddr(SDValue Op, SDValue Addr, SDValue &Offset, SDValue &Base)
136 {
137   // if Address is FI, get the TargetFrameIndex.
138   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
139     Base   = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
140     Offset = CurDAG->getTargetConstant(0, MVT::i32);
141     return true;
142   }
143     
144   // on PIC code Load GA
145   if (TM.getRelocationModel() == Reloc::PIC_) {
146     if ((Addr.getOpcode() == ISD::TargetGlobalAddress) || 
147         (Addr.getOpcode() == ISD::TargetConstantPool) || 
148         (Addr.getOpcode() == ISD::TargetJumpTable)){
149       Base   = CurDAG->getRegister(Mips::GP, MVT::i32);
150       Offset = Addr;
151       return true;
152     }
153   } else {
154     if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
155         Addr.getOpcode() == ISD::TargetGlobalAddress))
156       return false;
157   }    
158   
159   // Operand is a result from an ADD.
160   if (Addr.getOpcode() == ISD::ADD) {
161     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) {
162       if (Predicate_immSExt16(CN)) {
163
164         // If the first operand is a FI, get the TargetFI Node
165         if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
166                                     (Addr.getOperand(0))) {
167           Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
168         } else {
169           Base = Addr.getOperand(0);
170         }
171
172         Offset = CurDAG->getTargetConstant(CN->getZExtValue(), MVT::i32);
173         return true;
174       }
175     }
176
177     // When loading from constant pools, load the lower address part in
178     // the instruction itself. Example, instead of:
179     //  lui $2, %hi($CPI1_0)
180     //  addiu $2, $2, %lo($CPI1_0)
181     //  lwc1 $f0, 0($2)
182     // Generate:
183     //  lui $2, %hi($CPI1_0)
184     //  lwc1 $f0, %lo($CPI1_0)($2)
185     if ((Addr.getOperand(0).getOpcode() == MipsISD::Hi || 
186          Addr.getOperand(0).getOpcode() == ISD::LOAD) &&
187         Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
188       SDValue LoVal = Addr.getOperand(1); 
189       if (dyn_cast<ConstantPoolSDNode>(LoVal.getOperand(0))) {
190         Base = Addr.getOperand(0);
191         Offset = LoVal.getOperand(0);
192         return true;
193       }
194     }
195   }
196
197   Base   = Addr;
198   Offset = CurDAG->getTargetConstant(0, MVT::i32);
199   return true;
200 }
201
202 SDNode *MipsDAGToDAGISel::SelectLoadFp64(SDValue N) {
203   MVT::SimpleValueType NVT = 
204     N.getNode()->getValueType(0).getSimpleVT().SimpleTy;
205
206   if (!Subtarget.isMips1() || NVT != MVT::f64)
207     return NULL;
208
209   if (!Predicate_unindexedload(N.getNode()) ||
210       !Predicate_load(N.getNode()))
211     return NULL;
212
213   SDValue Chain = N.getOperand(0);
214   SDValue N1 = N.getOperand(1);
215   SDValue Offset0, Offset1, Base;
216
217   if (!SelectAddr(N, N1, Offset0, Base) ||
218       N1.getValueType() != MVT::i32)
219     return NULL;
220
221   MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
222   MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
223   DebugLoc dl = N.getDebugLoc();
224
225   // The second load should start after for 4 bytes. 
226   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Offset0))
227     Offset1 = CurDAG->getTargetConstant(C->getSExtValue()+4, MVT::i32);
228   else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Offset0))
229     Offset1 = CurDAG->getTargetConstantPool(CP->getConstVal(), 
230                                             MVT::i32, 
231                                             CP->getAlignment(), 
232                                             CP->getOffset()+4, 
233                                             CP->getTargetFlags());
234   else
235     return NULL;
236
237   // Choose the offsets depending on the endianess
238   if (TM.getTargetData()->isBigEndian())
239     std::swap(Offset0, Offset1);
240
241   // Instead of:
242   //    ldc $f0, X($3)
243   // Generate:
244   //    lwc $f0, X($3)
245   //    lwc $f1, X+4($3)
246   SDNode *LD0 = CurDAG->getMachineNode(Mips::LWC1, dl, MVT::f32, 
247                                     MVT::Other, Offset0, Base, Chain);
248   SDValue Undef = SDValue(CurDAG->getMachineNode(TargetInstrInfo::IMPLICIT_DEF,
249                                                  dl, NVT), 0);
250   SDValue I0 = CurDAG->getTargetInsertSubreg(Mips::SUBREG_FPEVEN, dl, 
251                             MVT::f64, Undef, SDValue(LD0, 0));
252
253   SDNode *LD1 = CurDAG->getMachineNode(Mips::LWC1, dl, MVT::f32,
254                           MVT::Other, Offset1, Base, SDValue(LD0, 1));
255   SDValue I1 = CurDAG->getTargetInsertSubreg(Mips::SUBREG_FPODD, dl, 
256                             MVT::f64, I0, SDValue(LD1, 0));
257
258   ReplaceUses(N, I1);
259   ReplaceUses(N.getValue(1), Chain);
260   cast<MachineSDNode>(LD0)->setMemRefs(MemRefs0, MemRefs0 + 1);
261   cast<MachineSDNode>(LD1)->setMemRefs(MemRefs0, MemRefs0 + 1);
262   return I1.getNode();
263 }
264
265 SDNode *MipsDAGToDAGISel::SelectStoreFp64(SDValue N) {
266
267   if (!Subtarget.isMips1() || 
268       N.getOperand(1).getValueType() != MVT::f64)
269     return NULL;
270
271   SDValue Chain = N.getOperand(0);
272
273   if (!Predicate_unindexedstore(N.getNode()) ||
274       !Predicate_store(N.getNode()))
275     return NULL;
276
277   SDValue N1 = N.getOperand(1);
278   SDValue N2 = N.getOperand(2);
279   SDValue Offset0, Offset1, Base;
280
281   if (!SelectAddr(N, N2, Offset0, Base) ||
282       N1.getValueType() != MVT::f64 ||
283       N2.getValueType() != MVT::i32)
284     return NULL;
285
286   MachineSDNode::mmo_iterator MemRefs0 = MF->allocateMemRefsArray(1);
287   MemRefs0[0] = cast<MemSDNode>(N)->getMemOperand();
288   DebugLoc dl = N.getDebugLoc();
289
290   // Get the even and odd part from the f64 register
291   SDValue FPOdd = CurDAG->getTargetExtractSubreg(Mips::SUBREG_FPODD, 
292                                                  dl, MVT::f32, N1);
293   SDValue FPEven = CurDAG->getTargetExtractSubreg(Mips::SUBREG_FPEVEN,
294                                                  dl, MVT::f32, N1);
295
296   // The second store should start after for 4 bytes. 
297   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Offset0))
298     Offset1 = CurDAG->getTargetConstant(C->getSExtValue()+4, MVT::i32);
299   else
300     return NULL;
301
302   // Choose the offsets depending on the endianess
303   if (TM.getTargetData()->isBigEndian())
304     std::swap(Offset0, Offset1);
305
306   // Instead of:
307   //    sdc $f0, X($3)
308   // Generate:
309   //    swc $f0, X($3)
310   //    swc $f1, X+4($3)
311   SDValue Ops0[] = { FPEven, Offset0, Base, Chain };
312   Chain = SDValue(CurDAG->getMachineNode(Mips::SWC1, dl,
313                                        MVT::Other, Ops0, 4), 0);
314   cast<MachineSDNode>(Chain.getNode())->setMemRefs(MemRefs0, MemRefs0 + 1);
315
316   SDValue Ops1[] = { FPOdd, Offset1, Base, Chain };
317   Chain = SDValue(CurDAG->getMachineNode(Mips::SWC1, dl,
318                                        MVT::Other, Ops1, 4), 0);
319   cast<MachineSDNode>(Chain.getNode())->setMemRefs(MemRefs0, MemRefs0 + 1);
320
321   ReplaceUses(N.getValue(0), Chain);
322   return Chain.getNode();
323 }
324
325 /// Select instructions not customized! Used for
326 /// expanded, promoted and normal instructions
327 SDNode* MipsDAGToDAGISel::Select(SDValue N) {
328   SDNode *Node = N.getNode();
329   unsigned Opcode = Node->getOpcode();
330   DebugLoc dl = Node->getDebugLoc();
331
332   // Dump information about the Node being selected
333   DEBUG(errs().indent(Indent) << "Selecting: ";
334         Node->dump(CurDAG);
335         errs() << "\n");
336   DEBUG(Indent += 2);
337
338   // If we have a custom node, we already have selected!
339   if (Node->isMachineOpcode()) {
340     DEBUG(errs().indent(Indent-2) << "== ";
341           Node->dump(CurDAG);
342           errs() << "\n");
343     DEBUG(Indent -= 2);
344     return NULL;
345   }
346
347   ///
348   // Instruction Selection not handled by the auto-generated 
349   // tablegen selection should be handled here.
350   /// 
351   switch(Opcode) {
352
353     default: break;
354
355     case ISD::SUBE: 
356     case ISD::ADDE: {
357       SDValue InFlag = Node->getOperand(2), CmpLHS;
358       unsigned Opc = InFlag.getOpcode(); Opc=Opc;
359       assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) || 
360               (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&  
361              "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
362
363       unsigned MOp;
364       if (Opcode == ISD::ADDE) {
365         CmpLHS = InFlag.getValue(0);
366         MOp = Mips::ADDu;
367       } else { 
368         CmpLHS = InFlag.getOperand(0);
369         MOp = Mips::SUBu;
370       }
371
372       SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
373
374       SDValue LHS = Node->getOperand(0);
375       SDValue RHS = Node->getOperand(1);
376
377       EVT VT = LHS.getValueType();
378       SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
379       SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT, 
380                                                 SDValue(Carry,0), RHS);
381
382       return CurDAG->SelectNodeTo(N.getNode(), MOp, VT, MVT::Flag,
383                                   LHS, SDValue(AddCarry,0));
384     }
385
386     /// Mul/Div with two results
387     case ISD::SDIVREM:
388     case ISD::UDIVREM:
389     case ISD::SMUL_LOHI:
390     case ISD::UMUL_LOHI: {
391       SDValue Op1 = Node->getOperand(0);
392       SDValue Op2 = Node->getOperand(1);
393
394       unsigned Op;
395       if (Opcode == ISD::UMUL_LOHI || Opcode == ISD::SMUL_LOHI)
396         Op = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
397       else
398         Op = (Opcode == ISD::UDIVREM ? Mips::DIVu : Mips::DIV);
399
400       SDNode *Node = CurDAG->getMachineNode(Op, dl, MVT::Flag, Op1, Op2);
401
402       SDValue InFlag = SDValue(Node, 0);
403       SDNode *Lo = CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32, 
404                                           MVT::Flag, InFlag);
405       InFlag = SDValue(Lo,1);
406       SDNode *Hi = CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
407
408       if (!N.getValue(0).use_empty()) 
409         ReplaceUses(N.getValue(0), SDValue(Lo,0));
410
411       if (!N.getValue(1).use_empty()) 
412         ReplaceUses(N.getValue(1), SDValue(Hi,0));
413
414       return NULL;
415     }
416
417     /// Special Muls
418     case ISD::MUL: 
419     case ISD::MULHS:
420     case ISD::MULHU: {
421       SDValue MulOp1 = Node->getOperand(0);
422       SDValue MulOp2 = Node->getOperand(1);
423
424       unsigned MulOp  = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
425       SDNode *MulNode = CurDAG->getMachineNode(MulOp, dl, 
426                                                MVT::Flag, MulOp1, MulOp2);
427
428       SDValue InFlag = SDValue(MulNode, 0);
429
430       if (MulOp == ISD::MUL)
431         return CurDAG->getMachineNode(Mips::MFLO, dl, MVT::i32, InFlag);
432       else
433         return CurDAG->getMachineNode(Mips::MFHI, dl, MVT::i32, InFlag);
434     }
435
436     /// Div/Rem operations
437     case ISD::SREM:
438     case ISD::UREM:
439     case ISD::SDIV: 
440     case ISD::UDIV: {
441       SDValue Op1 = Node->getOperand(0);
442       SDValue Op2 = Node->getOperand(1);
443
444       unsigned Op, MOp;
445       if (Opcode == ISD::SDIV || Opcode == ISD::UDIV) {
446         Op  = (Opcode == ISD::SDIV ? Mips::DIV : Mips::DIVu);
447         MOp = Mips::MFLO;
448       } else {
449         Op  = (Opcode == ISD::SREM ? Mips::DIV : Mips::DIVu);
450         MOp = Mips::MFHI;
451       }
452       SDNode *Node = CurDAG->getMachineNode(Op, dl, MVT::Flag, Op1, Op2);
453
454       SDValue InFlag = SDValue(Node, 0);
455       return CurDAG->getMachineNode(MOp, dl, MVT::i32, InFlag);
456     }
457
458     // Get target GOT address.
459     case ISD::GLOBAL_OFFSET_TABLE:
460       return getGlobalBaseReg();
461
462     case ISD::ConstantFP: {
463       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
464       if (N.getValueType() == MVT::f64 && CN->isExactlyValue(+0.0)) { 
465         SDValue Zero = CurDAG->getRegister(Mips::ZERO, MVT::i32);
466         ReplaceUses(N, Zero);
467         return Zero.getNode();
468       }
469       break;
470     }
471
472     case ISD::LOAD:
473       if (SDNode *ResNode = SelectLoadFp64(N))
474         return ResNode;
475       // Other cases are autogenerated.
476       break;
477
478     case ISD::STORE:
479       if (SDNode *ResNode = SelectStoreFp64(N))
480         return ResNode;
481       // Other cases are autogenerated.
482       break;
483
484     /// Handle direct and indirect calls when using PIC. On PIC, when 
485     /// GOT is smaller than about 64k (small code) the GA target is 
486     /// loaded with only one instruction. Otherwise GA's target must 
487     /// be loaded with 3 instructions. 
488     case MipsISD::JmpLink: {
489       if (TM.getRelocationModel() == Reloc::PIC_) {
490         SDValue Chain  = Node->getOperand(0);
491         SDValue Callee = Node->getOperand(1);
492         SDValue T9Reg = CurDAG->getRegister(Mips::T9, MVT::i32);
493         SDValue InFlag(0, 0);
494
495         if ( (isa<GlobalAddressSDNode>(Callee)) ||
496              (isa<ExternalSymbolSDNode>(Callee)) )
497         {
498           /// Direct call for global addresses and external symbols
499           SDValue GPReg = CurDAG->getRegister(Mips::GP, MVT::i32);
500
501           // Use load to get GOT target
502           SDValue Ops[] = { Callee, GPReg, Chain };
503           SDValue Load = SDValue(CurDAG->getMachineNode(Mips::LW, dl, MVT::i32, 
504                                      MVT::Other, Ops, 3), 0);
505           Chain = Load.getValue(1);
506
507           // Call target must be on T9
508           Chain = CurDAG->getCopyToReg(Chain, dl, T9Reg, Load, InFlag);
509         } else 
510           /// Indirect call
511           Chain = CurDAG->getCopyToReg(Chain, dl, T9Reg, Callee, InFlag);
512
513         // Emit Jump and Link Register
514         SDNode *ResNode = CurDAG->getMachineNode(Mips::JALR, dl, MVT::Other,
515                                   MVT::Flag, T9Reg, Chain);
516         Chain  = SDValue(ResNode, 0);
517         InFlag = SDValue(ResNode, 1);
518         ReplaceUses(SDValue(Node, 0), Chain);
519         ReplaceUses(SDValue(Node, 1), InFlag);
520         return ResNode;
521       } 
522     }
523   }
524
525   // Select the default instruction
526   SDNode *ResNode = SelectCode(N);
527
528   DEBUG(errs().indent(Indent-2) << "=> ");
529   if (ResNode == NULL || ResNode == N.getNode())
530     DEBUG(N.getNode()->dump(CurDAG));
531   else
532     DEBUG(ResNode->dump(CurDAG));
533   DEBUG(errs() << "\n");
534   DEBUG(Indent -= 2);
535
536   return ResNode;
537 }
538
539 /// createMipsISelDag - This pass converts a legalized DAG into a 
540 /// MIPS-specific DAG, ready for instruction scheduling.
541 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
542   return new MipsDAGToDAGISel(TM);
543 }