It really helps to be returning to the correct place
[oota-llvm.git] / lib / Target / Alpha / AlphaISelDAGToDAG.cpp
1 //===-- AlphaISelDAGToDAG.cpp - Alpha pattern matching inst selector ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Andrew Lenharth and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for Alpha,
11 // converting from a legalized dag to a Alpha dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "Alpha.h"
16 #include "AlphaTargetMachine.h"
17 #include "AlphaISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include <algorithm>
32 #include <iostream>
33 #include <set>
34 using namespace llvm;
35
36 namespace {
37
38   //===--------------------------------------------------------------------===//
39   /// AlphaDAGToDAGISel - Alpha specific code to select Alpha machine
40   /// instructions for SelectionDAG operations.
41   class AlphaDAGToDAGISel : public SelectionDAGISel {
42     AlphaTargetLowering AlphaLowering;
43
44     static const int64_t IMM_LOW  = -32768;
45     static const int64_t IMM_HIGH = 32767;
46     static const int64_t IMM_MULT = 65536;
47     static const int64_t IMM_FULLHIGH = IMM_HIGH + IMM_HIGH * IMM_MULT;
48     static const int64_t IMM_FULLLOW = IMM_LOW + IMM_LOW  * IMM_MULT;
49
50     static int64_t get_ldah16(int64_t x) {
51       int64_t y = x / IMM_MULT;
52       if (x % IMM_MULT > IMM_HIGH)
53         ++y;
54       return y;
55     }
56
57     static int64_t get_lda16(int64_t x) {
58       return x - get_ldah16(x) * IMM_MULT;
59     }
60
61     static uint64_t get_zapImm(uint64_t x) {
62       unsigned int build = 0;
63       for(int i = 0; i < 8; ++i)
64         {
65           if ((x & 0x00FF) == 0x00FF)
66             build |= 1 << i;
67           else if ((x & 0x00FF) != 0)
68             { build = 0; break; }
69           x >>= 8;
70         }
71       return build;
72     }
73
74     static uint64_t getNearPower2(uint64_t x) {
75       if (!x) return 0;
76       unsigned at = CountLeadingZeros_64(x);
77       uint64_t complow = 1 << (63 - at);
78       uint64_t comphigh = 1 << (64 - at);
79       //std::cerr << x << ":" << complow << ":" << comphigh << "\n";
80       if (abs(complow - x) <= abs(comphigh - x))
81         return complow;
82       else
83         return comphigh;
84     }
85
86     static bool isFPZ(SDOperand N) {
87       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
88       return (CN && (CN->isExactlyValue(+0.0) || CN->isExactlyValue(-0.0)));
89     }
90     static bool isFPZn(SDOperand N) {
91       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
92       return (CN && CN->isExactlyValue(-0.0));
93     }
94     static bool isFPZp(SDOperand N) {
95       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
96       return (CN && CN->isExactlyValue(+0.0));
97     }
98
99   public:
100     AlphaDAGToDAGISel(TargetMachine &TM)
101       : SelectionDAGISel(AlphaLowering), AlphaLowering(TM) 
102     {}
103
104     /// getI64Imm - Return a target constant with the specified value, of type
105     /// i64.
106     inline SDOperand getI64Imm(int64_t Imm) {
107       return CurDAG->getTargetConstant(Imm, MVT::i64);
108     }
109
110     // Select - Convert the specified operand from a target-independent to a
111     // target-specific node if it hasn't already been changed.
112     void Select(SDOperand &Result, SDOperand Op);
113     
114     /// InstructionSelectBasicBlock - This callback is invoked by
115     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
116     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
117     
118     virtual const char *getPassName() const {
119       return "Alpha DAG->DAG Pattern Instruction Selection";
120     } 
121
122 // Include the pieces autogenerated from the target description.
123 #include "AlphaGenDAGISel.inc"
124     
125 private:
126     SDOperand getGlobalBaseReg();
127     SDOperand getGlobalRetAddr();
128     SDOperand SelectCALL(SDOperand Op);
129
130   };
131 }
132
133 /// getGlobalBaseReg - Output the instructions required to put the
134 /// GOT address into a register.
135 ///
136 SDOperand AlphaDAGToDAGISel::getGlobalBaseReg() {
137   return CurDAG->getCopyFromReg(CurDAG->getEntryNode(), 
138                                 AlphaLowering.getVRegGP(), 
139                                 MVT::i64);
140 }
141
142 /// getRASaveReg - Grab the return address
143 ///
144 SDOperand AlphaDAGToDAGISel::getGlobalRetAddr() {
145   return CurDAG->getCopyFromReg(CurDAG->getEntryNode(),
146                                 AlphaLowering.getVRegRA(), 
147                                 MVT::i64);
148 }
149
150 /// InstructionSelectBasicBlock - This callback is invoked by
151 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
152 void AlphaDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
153   DEBUG(BB->dump());
154   
155   // Select target instructions for the DAG.
156   DAG.setRoot(SelectRoot(DAG.getRoot()));
157   assert(InFlightSet.empty() && "ISel InFlightSet has not been emptied!");
158   CodeGenMap.clear();
159   HandleMap.clear();
160   ReplaceMap.clear();
161   DAG.RemoveDeadNodes();
162   
163   // Emit machine code to BB. 
164   ScheduleAndEmitDAG(DAG);
165 }
166
167 // Select - Convert the specified operand from a target-independent to a
168 // target-specific node if it hasn't already been changed.
169 void AlphaDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
170   SDNode *N = Op.Val;
171   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
172       N->getOpcode() < AlphaISD::FIRST_NUMBER) {
173     Result = Op;
174     return;   // Already selected.
175   }
176
177   // If this has already been converted, use it.
178   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
179   if (CGMI != CodeGenMap.end()) {
180     Result = CGMI->second;
181     return;
182   }
183
184   switch (N->getOpcode()) {
185   default: break;
186   case AlphaISD::CALL:
187     Result = SelectCALL(Op);
188     return;
189
190   case ISD::FrameIndex: {
191     int FI = cast<FrameIndexSDNode>(N)->getIndex();
192     Result = CurDAG->SelectNodeTo(N, Alpha::LDA, MVT::i64,
193                                   CurDAG->getTargetFrameIndex(FI, MVT::i32),
194                                   getI64Imm(0));
195     return;
196   }
197   case AlphaISD::GlobalBaseReg: 
198     Result = getGlobalBaseReg();
199     return;
200   case AlphaISD::GlobalRetAddr:
201     Result = getGlobalRetAddr();
202     return;
203   
204   case AlphaISD::DivCall: {
205     SDOperand Chain = CurDAG->getEntryNode();
206     SDOperand N0, N1, N2;
207     Select(N0, Op.getOperand(0));
208     Select(N1, Op.getOperand(1));
209     Select(N2, Op.getOperand(2));
210     Chain = CurDAG->getCopyToReg(Chain, Alpha::R24, N1, 
211                                  SDOperand(0,0));
212     Chain = CurDAG->getCopyToReg(Chain, Alpha::R25, N2, 
213                                  Chain.getValue(1));
214     Chain = CurDAG->getCopyToReg(Chain, Alpha::R27, N0, 
215                                  Chain.getValue(1));
216     SDNode *CNode =
217       CurDAG->getTargetNode(Alpha::JSRs, MVT::Other, MVT::Flag, 
218                             Chain, Chain.getValue(1));
219     Chain = CurDAG->getCopyFromReg(Chain, Alpha::R27, MVT::i64, 
220                                   SDOperand(CNode, 1));
221     Result = CurDAG->SelectNodeTo(N, Alpha::BIS, MVT::i64, Chain, Chain);
222     return;
223   }
224
225   case ISD::READCYCLECOUNTER: {
226     SDOperand Chain;
227     Select(Chain, N->getOperand(0)); //Select chain
228     Result = CurDAG->SelectNodeTo(N, Alpha::RPCC, MVT::i64, Chain);
229     return;
230   }
231
232   case ISD::Constant: {
233     uint64_t uval = cast<ConstantSDNode>(N)->getValue();
234     
235     if (uval == 0) {
236       Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), Alpha::R31,
237                                       MVT::i64);
238       return;
239     }
240
241     int64_t val = (int64_t)uval;
242     int32_t val32 = (int32_t)val;
243     if (val <= IMM_HIGH + IMM_HIGH * IMM_MULT &&
244         val >= IMM_LOW  + IMM_LOW  * IMM_MULT)
245       break; //(LDAH (LDA))
246     if ((uval >> 32) == 0 && //empty upper bits
247         val32 <= IMM_HIGH + IMM_HIGH * IMM_MULT)
248       //        val32 >= IMM_LOW  + IMM_LOW  * IMM_MULT) //always true
249       break; //(zext (LDAH (LDA)))
250     //Else use the constant pool
251     MachineConstantPool *CP = BB->getParent()->getConstantPool();
252     ConstantUInt *C =
253       ConstantUInt::get(Type::getPrimitiveType(Type::ULongTyID) , uval);
254     SDOperand CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
255     SDNode *Tmp = CurDAG->getTargetNode(Alpha::LDAHr, MVT::i64, CPI,
256                                         getGlobalBaseReg());
257     Result = CurDAG->SelectNodeTo(N, Alpha::LDQr, MVT::i64, MVT::Other, 
258                                   CPI, SDOperand(Tmp, 0), CurDAG->getEntryNode());
259     return;
260   }
261   case ISD::TargetConstantFP: {
262     ConstantFPSDNode *CN = cast<ConstantFPSDNode>(N);
263     bool isDouble = N->getValueType(0) == MVT::f64;
264     MVT::ValueType T = isDouble ? MVT::f64 : MVT::f32;
265     if (CN->isExactlyValue(+0.0)) {
266       Result = CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYST : Alpha::CPYSS,
267                                     T, CurDAG->getRegister(Alpha::F31, T),
268                                     CurDAG->getRegister(Alpha::F31, T));
269       return;
270     } else if ( CN->isExactlyValue(-0.0)) {
271       Result = CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYSNT : Alpha::CPYSNS,
272                                     T, CurDAG->getRegister(Alpha::F31, T),
273                                     CurDAG->getRegister(Alpha::F31, T));
274       return;
275     } else {
276       abort();
277     }
278     break;
279   }
280
281   case ISD::SETCC:
282     if (MVT::isFloatingPoint(N->getOperand(0).Val->getValueType(0))) {
283       unsigned Opc = Alpha::WTF;
284       ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
285       bool rev = false;
286       bool isNE = false;
287       switch(CC) {
288       default: N->dump(); assert(0 && "Unknown FP comparison!");
289       case ISD::SETEQ: Opc = Alpha::CMPTEQ; break;
290       case ISD::SETLT: Opc = Alpha::CMPTLT; break;
291       case ISD::SETLE: Opc = Alpha::CMPTLE; break;
292       case ISD::SETGT: Opc = Alpha::CMPTLT; rev = true; break;
293       case ISD::SETGE: Opc = Alpha::CMPTLE; rev = true; break;
294       case ISD::SETNE: Opc = Alpha::CMPTEQ; isNE = true; break;
295       };
296       SDOperand tmp1, tmp2;
297       Select(tmp1, N->getOperand(0));
298       Select(tmp2, N->getOperand(1));
299       SDNode *cmp = CurDAG->getTargetNode(Opc, MVT::f64, 
300                                           rev?tmp2:tmp1,
301                                           rev?tmp1:tmp2);
302       if (isNE) 
303         cmp = CurDAG->getTargetNode(Alpha::CMPTEQ, MVT::f64, SDOperand(cmp, 0), 
304                                     CurDAG->getRegister(Alpha::F31, MVT::f64));
305       
306       SDOperand LD;
307       if (AlphaLowering.hasITOF()) {
308         LD = CurDAG->getNode(AlphaISD::FTOIT_, MVT::i64, SDOperand(cmp, 0));
309       } else {
310         int FrameIdx =
311           CurDAG->getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
312         SDOperand FI = CurDAG->getFrameIndex(FrameIdx, MVT::i64);
313         SDOperand ST =
314           SDOperand(CurDAG->getTargetNode(Alpha::STT, MVT::Other, 
315                                           SDOperand(cmp, 0), FI,
316                                           CurDAG->getRegister(Alpha::R31, MVT::i64)), 0);
317         LD = SDOperand(CurDAG->getTargetNode(Alpha::LDQ, MVT::i64, FI, 
318                                              CurDAG->getRegister(Alpha::R31, MVT::i64),
319                                              ST), 0);
320       }
321       Result = SDOperand(CurDAG->getTargetNode(Alpha::CMPULT, MVT::i64, 
322                                                CurDAG->getRegister(Alpha::R31, MVT::i64),
323                                                LD), 0);
324       return;
325     }
326     break;
327
328   case ISD::SELECT:
329     if (MVT::isFloatingPoint(N->getValueType(0)) &&
330         (N->getOperand(0).getOpcode() != ISD::SETCC ||
331          !MVT::isFloatingPoint(N->getOperand(0).getOperand(1).getValueType()))) {
332       //This should be the condition not covered by the Patterns
333       //FIXME: Don't have SelectCode die, but rather return something testable
334       // so that things like this can be caught in fall though code
335       //move int to fp
336       bool isDouble = N->getValueType(0) == MVT::f64;
337       SDOperand LD, cond, TV, FV;
338       Select(cond, N->getOperand(0));
339       Select(TV, N->getOperand(1));
340       Select(FV, N->getOperand(2));
341       
342       if (AlphaLowering.hasITOF()) {
343         LD = CurDAG->getNode(AlphaISD::ITOFT_, MVT::f64, cond);
344       } else {
345         int FrameIdx =
346           CurDAG->getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
347         SDOperand FI = CurDAG->getFrameIndex(FrameIdx, MVT::i64);
348         SDOperand ST =
349           SDOperand(CurDAG->getTargetNode(Alpha::STQ, MVT::Other,
350                                           cond, FI, CurDAG->getRegister(Alpha::R31, MVT::i64)), 0);
351         LD = SDOperand(CurDAG->getTargetNode(Alpha::LDT, MVT::f64, FI,
352                                              CurDAG->getRegister(Alpha::R31, MVT::i64),
353                                              ST), 0);
354       }
355       Result = SDOperand(CurDAG->getTargetNode(isDouble?Alpha::FCMOVNET:Alpha::FCMOVNES,
356                                                MVT::f64, FV, TV, LD), 0);
357       return;
358     }
359     break;
360
361   case ISD::AND: {
362     ConstantSDNode* SC = NULL;
363     ConstantSDNode* MC = NULL;
364     if (N->getOperand(0).getOpcode() == ISD::SRL &&
365         (MC = dyn_cast<ConstantSDNode>(N->getOperand(1))) &&
366         (SC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1))))
367       {
368         uint64_t sval = SC->getValue();
369         uint64_t mval = MC->getValue();
370         if (get_zapImm(mval)) //the result is a zap, let the autogened stuff deal
371           break;
372         // given mask X, and shift S, we want to see if there is any zap in the mask
373         // if we play around with the botton S bits
374         uint64_t dontcare = (~0ULL) >> (64 - sval);
375         uint64_t mask = mval << sval;
376
377         if (get_zapImm(mask | dontcare))
378           mask = mask | dontcare;
379
380         if (get_zapImm(mask)) {
381           SDOperand Src;
382           Select(Src, N->getOperand(0).getOperand(0));
383           SDOperand Z = 
384             SDOperand(CurDAG->getTargetNode(Alpha::ZAPNOTi, MVT::i64, Src, 
385                                             getI64Imm(get_zapImm(mask))), 0);
386           Result = SDOperand(CurDAG->getTargetNode(Alpha::SRL, MVT::i64, Z, 
387                                                    getI64Imm(sval)), 0);
388           return;
389         }
390       }
391     break;
392   }
393
394   }
395
396   SelectCode(Result, Op);
397 }
398
399 SDOperand AlphaDAGToDAGISel::SelectCALL(SDOperand Op) {
400   //TODO: add flag stuff to prevent nondeturministic breakage!
401
402   SDNode *N = Op.Val;
403   SDOperand Chain;
404   SDOperand Addr = N->getOperand(1);
405   SDOperand InFlag(0,0);  // Null incoming flag value.
406   Select(Chain, N->getOperand(0));
407
408    std::vector<SDOperand> CallOperands;
409    std::vector<MVT::ValueType> TypeOperands;
410   
411    //grab the arguments
412    for(int i = 2, e = N->getNumOperands(); i < e; ++i) {
413      SDOperand Tmp;
414      TypeOperands.push_back(N->getOperand(i).getValueType());
415      Select(Tmp, N->getOperand(i));
416      CallOperands.push_back(Tmp);
417    }
418    int count = N->getNumOperands() - 2;
419
420    static const unsigned args_int[] = {Alpha::R16, Alpha::R17, Alpha::R18,
421                                        Alpha::R19, Alpha::R20, Alpha::R21};
422    static const unsigned args_float[] = {Alpha::F16, Alpha::F17, Alpha::F18,
423                                          Alpha::F19, Alpha::F20, Alpha::F21};
424    
425    for (int i = 6; i < count; ++i) {
426      unsigned Opc = Alpha::WTF;
427      if (MVT::isInteger(TypeOperands[i])) {
428        Opc = Alpha::STQ;
429      } else if (TypeOperands[i] == MVT::f32) {
430        Opc = Alpha::STS;
431      } else if (TypeOperands[i] == MVT::f64) {
432        Opc = Alpha::STT;
433      } else
434        assert(0 && "Unknown operand"); 
435      Chain = SDOperand(CurDAG->getTargetNode(Opc, MVT::Other, CallOperands[i], 
436                                              getI64Imm((i - 6) * 8), 
437                                              CurDAG->getCopyFromReg(Chain, Alpha::R30, MVT::i64),
438                                              Chain), 0);
439    }
440    for (int i = 0; i < std::min(6, count); ++i) {
441      if (MVT::isInteger(TypeOperands[i])) {
442        Chain = CurDAG->getCopyToReg(Chain, args_int[i], CallOperands[i], InFlag);
443        InFlag = Chain.getValue(1);
444      } else if (TypeOperands[i] == MVT::f32 || TypeOperands[i] == MVT::f64) {
445        Chain = CurDAG->getCopyToReg(Chain, args_float[i], CallOperands[i], InFlag);
446        InFlag = Chain.getValue(1);
447      } else
448        assert(0 && "Unknown operand"); 
449    }
450
451    // Finally, once everything is in registers to pass to the call, emit the
452    // call itself.
453    if (Addr.getOpcode() == AlphaISD::GPRelLo) {
454      SDOperand GOT = getGlobalBaseReg();
455      Chain = CurDAG->getCopyToReg(Chain, Alpha::R29, GOT, InFlag);
456      InFlag = Chain.getValue(1);
457      Chain = SDOperand(CurDAG->getTargetNode(Alpha::BSR, MVT::Other, MVT::Flag, 
458                                              Addr.getOperand(0), Chain, InFlag), 0);
459    } else {
460      Select(Addr, Addr);
461      Chain = CurDAG->getCopyToReg(Chain, Alpha::R27, Addr, InFlag);
462      InFlag = Chain.getValue(1);
463      Chain = SDOperand(CurDAG->getTargetNode(Alpha::JSR, MVT::Other, MVT::Flag, 
464                                              Chain, InFlag), 0);
465    }
466    InFlag = Chain.getValue(1);
467
468    std::vector<SDOperand> CallResults;
469   
470    switch (N->getValueType(0)) {
471    default: assert(0 && "Unexpected ret value!");
472      case MVT::Other: break;
473    case MVT::i64:
474      Chain = CurDAG->getCopyFromReg(Chain, Alpha::R0, MVT::i64, InFlag).getValue(1);
475      CallResults.push_back(Chain.getValue(0));
476      break;
477    case MVT::f32:
478      Chain = CurDAG->getCopyFromReg(Chain, Alpha::F0, MVT::f32, InFlag).getValue(1);
479      CallResults.push_back(Chain.getValue(0));
480      break;
481    case MVT::f64:
482      Chain = CurDAG->getCopyFromReg(Chain, Alpha::F0, MVT::f64, InFlag).getValue(1);
483      CallResults.push_back(Chain.getValue(0));
484      break;
485    }
486
487    CallResults.push_back(Chain);
488    for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
489      CodeGenMap[Op.getValue(i)] = CallResults[i];
490    return CallResults[Op.ResNo];
491 }
492
493
494 /// createAlphaISelDag - This pass converts a legalized DAG into a 
495 /// Alpha-specific DAG, ready for instruction scheduling.
496 ///
497 FunctionPass *llvm::createAlphaISelDag(TargetMachine &TM) {
498   return new AlphaDAGToDAGISel(TM);
499 }