e3f631a1f5be4f31732edd3207cb4f6cf170ac3b
[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 is distributed under the University of Illinois Open Source
6 // 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/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/DerivedTypes.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/MathExtras.h"
32 #include <algorithm>
33 using namespace llvm;
34
35 namespace {
36
37   //===--------------------------------------------------------------------===//
38   /// AlphaDAGToDAGISel - Alpha specific code to select Alpha machine
39   /// instructions for SelectionDAG operations.
40   class AlphaDAGToDAGISel : public SelectionDAGISel {
41     static const int64_t IMM_LOW  = -32768;
42     static const int64_t IMM_HIGH = 32767;
43     static const int64_t IMM_MULT = 65536;
44     static const int64_t IMM_FULLHIGH = IMM_HIGH + IMM_HIGH * IMM_MULT;
45     static const int64_t IMM_FULLLOW = IMM_LOW + IMM_LOW  * IMM_MULT;
46
47     static int64_t get_ldah16(int64_t x) {
48       int64_t y = x / IMM_MULT;
49       if (x % IMM_MULT > IMM_HIGH)
50         ++y;
51       return y;
52     }
53
54     static int64_t get_lda16(int64_t x) {
55       return x - get_ldah16(x) * IMM_MULT;
56     }
57
58     /// get_zapImm - Return a zap mask if X is a valid immediate for a zapnot
59     /// instruction (if not, return 0).  Note that this code accepts partial
60     /// zap masks.  For example (and LHS, 1) is a valid zap, as long we know
61     /// that the bits 1-7 of LHS are already zero.  If LHS is non-null, we are
62     /// in checking mode.  If LHS is null, we assume that the mask has already
63     /// been validated before.
64     uint64_t get_zapImm(SDValue LHS, uint64_t Constant) {
65       uint64_t BitsToCheck = 0;
66       unsigned Result = 0;
67       for (unsigned i = 0; i != 8; ++i) {
68         if (((Constant >> 8*i) & 0xFF) == 0) {
69           // nothing to do.
70         } else {
71           Result |= 1 << i;
72           if (((Constant >> 8*i) & 0xFF) == 0xFF) {
73             // If the entire byte is set, zapnot the byte.
74           } else if (LHS.getNode() == 0) {
75             // Otherwise, if the mask was previously validated, we know its okay
76             // to zapnot this entire byte even though all the bits aren't set.
77           } else {
78             // Otherwise we don't know that the it's okay to zapnot this entire
79             // byte.  Only do this iff we can prove that the missing bits are
80             // already null, so the bytezap doesn't need to really null them.
81             BitsToCheck |= ~Constant & (0xFF << 8*i);
82           }
83         }
84       }
85       
86       // If there are missing bits in a byte (for example, X & 0xEF00), check to
87       // see if the missing bits (0x1000) are already known zero if not, the zap
88       // isn't okay to do, as it won't clear all the required bits.
89       if (BitsToCheck &&
90           !CurDAG->MaskedValueIsZero(LHS,
91                                      APInt(LHS.getValueSizeInBits(),
92                                            BitsToCheck)))
93         return 0;
94       
95       return Result;
96     }
97     
98     static uint64_t get_zapImm(uint64_t x) {
99       unsigned build = 0;
100       for(int i = 0; i != 8; ++i) {
101         if ((x & 0x00FF) == 0x00FF)
102           build |= 1 << i;
103         else if ((x & 0x00FF) != 0)
104           return 0;
105         x >>= 8;
106       }
107       return build;
108     }
109       
110     
111     static uint64_t getNearPower2(uint64_t x) {
112       if (!x) return 0;
113       unsigned at = CountLeadingZeros_64(x);
114       uint64_t complow = 1 << (63 - at);
115       uint64_t comphigh = 1 << (64 - at);
116       //cerr << x << ":" << complow << ":" << comphigh << "\n";
117       if (abs(complow - x) <= abs(comphigh - x))
118         return complow;
119       else
120         return comphigh;
121     }
122
123     static bool chkRemNearPower2(uint64_t x, uint64_t r, bool swap) {
124       uint64_t y = getNearPower2(x);
125       if (swap)
126         return (y - x) == r;
127       else
128         return (x - y) == r;
129     }
130
131     static bool isFPZ(SDValue N) {
132       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
133       return (CN && (CN->getValueAPF().isZero()));
134     }
135     static bool isFPZn(SDValue N) {
136       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
137       return (CN && CN->getValueAPF().isNegZero());
138     }
139     static bool isFPZp(SDValue N) {
140       ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N);
141       return (CN && CN->getValueAPF().isPosZero());
142     }
143
144   public:
145     explicit AlphaDAGToDAGISel(AlphaTargetMachine &TM)
146       : SelectionDAGISel(TM)
147     {}
148
149     /// getI64Imm - Return a target constant with the specified value, of type
150     /// i64.
151     inline SDValue getI64Imm(int64_t Imm) {
152       return CurDAG->getTargetConstant(Imm, MVT::i64);
153     }
154
155     // Select - Convert the specified operand from a target-independent to a
156     // target-specific node if it hasn't already been changed.
157     SDNode *Select(SDValue Op);
158     
159     /// InstructionSelect - This callback is invoked by
160     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
161     virtual void InstructionSelect();
162     
163     virtual const char *getPassName() const {
164       return "Alpha DAG->DAG Pattern Instruction Selection";
165     } 
166
167     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
168     /// inline asm expressions.
169     virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
170                                               char ConstraintCode,
171                                               std::vector<SDValue> &OutOps) {
172       SDValue Op0;
173       switch (ConstraintCode) {
174       default: return true;
175       case 'm':   // memory
176         Op0 = Op;
177         break;
178       }
179       
180       OutOps.push_back(Op0);
181       return false;
182     }
183     
184 // Include the pieces autogenerated from the target description.
185 #include "AlphaGenDAGISel.inc"
186     
187 private:
188     /// getTargetMachine - Return a reference to the TargetMachine, casted
189     /// to the target-specific type.
190     const AlphaTargetMachine &getTargetMachine() {
191       return static_cast<const AlphaTargetMachine &>(TM);
192     }
193
194     /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
195     /// to the target-specific type.
196     const AlphaInstrInfo *getInstrInfo() {
197       return getTargetMachine().getInstrInfo();
198     }
199
200     SDNode *getGlobalBaseReg();
201     SDNode *getGlobalRetAddr();
202     void SelectCALL(SDValue Op);
203
204   };
205 }
206
207 /// getGlobalBaseReg - Output the instructions required to put the
208 /// GOT address into a register.
209 ///
210 SDNode *AlphaDAGToDAGISel::getGlobalBaseReg() {
211   MachineFunction *MF = BB->getParent();
212   unsigned GlobalBaseReg = getInstrInfo()->getGlobalBaseReg(MF);
213   return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
214 }
215
216 /// getGlobalRetAddr - Grab the return address.
217 ///
218 SDNode *AlphaDAGToDAGISel::getGlobalRetAddr() {
219   MachineFunction *MF = BB->getParent();
220   unsigned GlobalRetAddr = getInstrInfo()->getGlobalRetAddr(MF);
221   return CurDAG->getRegister(GlobalRetAddr, TLI.getPointerTy()).getNode();
222 }
223
224 /// InstructionSelect - This callback is invoked by
225 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
226 void AlphaDAGToDAGISel::InstructionSelect() {
227   DEBUG(BB->dump());
228   
229   // Select target instructions for the DAG.
230   SelectRoot(*CurDAG);
231   CurDAG->RemoveDeadNodes();
232 }
233
234 // Select - Convert the specified operand from a target-independent to a
235 // target-specific node if it hasn't already been changed.
236 SDNode *AlphaDAGToDAGISel::Select(SDValue Op) {
237   SDNode *N = Op.getNode();
238   if (N->isMachineOpcode()) {
239     return NULL;   // Already selected.
240   }
241   DebugLoc dl = N->getDebugLoc();
242
243   switch (N->getOpcode()) {
244   default: break;
245   case AlphaISD::CALL:
246     SelectCALL(Op);
247     return NULL;
248
249   case ISD::FrameIndex: {
250     int FI = cast<FrameIndexSDNode>(N)->getIndex();
251     return CurDAG->SelectNodeTo(N, Alpha::LDA, MVT::i64,
252                                 CurDAG->getTargetFrameIndex(FI, MVT::i32),
253                                 getI64Imm(0));
254   }
255   case ISD::GLOBAL_OFFSET_TABLE:
256     return getGlobalBaseReg();
257   case AlphaISD::GlobalRetAddr:
258     return getGlobalRetAddr();
259   
260   case AlphaISD::DivCall: {
261     SDValue Chain = CurDAG->getEntryNode();
262     SDValue N0 = Op.getOperand(0);
263     SDValue N1 = Op.getOperand(1);
264     SDValue N2 = Op.getOperand(2);
265     Chain = CurDAG->getCopyToReg(Chain, dl, Alpha::R24, N1, 
266                                  SDValue(0,0));
267     Chain = CurDAG->getCopyToReg(Chain, dl, Alpha::R25, N2, 
268                                  Chain.getValue(1));
269     Chain = CurDAG->getCopyToReg(Chain, dl, Alpha::R27, N0, 
270                                  Chain.getValue(1));
271     SDNode *CNode =
272       CurDAG->getTargetNode(Alpha::JSRs, dl, MVT::Other, MVT::Flag, 
273                             Chain, Chain.getValue(1));
274     Chain = CurDAG->getCopyFromReg(Chain, dl, Alpha::R27, MVT::i64, 
275                                    SDValue(CNode, 1));
276     return CurDAG->SelectNodeTo(N, Alpha::BISr, MVT::i64, Chain, Chain);
277   }
278
279   case ISD::READCYCLECOUNTER: {
280     SDValue Chain = N->getOperand(0);
281     return CurDAG->getTargetNode(Alpha::RPCC, dl, MVT::i64, MVT::Other,
282                                  Chain);
283   }
284
285   case ISD::Constant: {
286     uint64_t uval = cast<ConstantSDNode>(N)->getZExtValue();
287     
288     if (uval == 0) {
289       SDValue Result = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
290                                                 Alpha::R31, MVT::i64);
291       ReplaceUses(Op, Result);
292       return NULL;
293     }
294
295     int64_t val = (int64_t)uval;
296     int32_t val32 = (int32_t)val;
297     if (val <= IMM_HIGH + IMM_HIGH * IMM_MULT &&
298         val >= IMM_LOW  + IMM_LOW  * IMM_MULT)
299       break; //(LDAH (LDA))
300     if ((uval >> 32) == 0 && //empty upper bits
301         val32 <= IMM_HIGH + IMM_HIGH * IMM_MULT)
302       // val32 >= IMM_LOW  + IMM_LOW  * IMM_MULT) //always true
303       break; //(zext (LDAH (LDA)))
304     //Else use the constant pool
305     ConstantInt *C = ConstantInt::get(Type::Int64Ty, uval);
306     SDValue CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
307     SDNode *Tmp = CurDAG->getTargetNode(Alpha::LDAHr, dl, MVT::i64, CPI,
308                                         SDValue(getGlobalBaseReg(), 0));
309     return CurDAG->SelectNodeTo(N, Alpha::LDQr, MVT::i64, MVT::Other, 
310                                 CPI, SDValue(Tmp, 0), CurDAG->getEntryNode());
311   }
312   case ISD::TargetConstantFP:
313   case ISD::ConstantFP: {
314     ConstantFPSDNode *CN = cast<ConstantFPSDNode>(N);
315     bool isDouble = N->getValueType(0) == MVT::f64;
316     MVT T = isDouble ? MVT::f64 : MVT::f32;
317     if (CN->getValueAPF().isPosZero()) {
318       return CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYST : Alpha::CPYSS,
319                                   T, CurDAG->getRegister(Alpha::F31, T),
320                                   CurDAG->getRegister(Alpha::F31, T));
321     } else if (CN->getValueAPF().isNegZero()) {
322       return CurDAG->SelectNodeTo(N, isDouble ? Alpha::CPYSNT : Alpha::CPYSNS,
323                                   T, CurDAG->getRegister(Alpha::F31, T),
324                                   CurDAG->getRegister(Alpha::F31, T));
325     } else {
326       abort();
327     }
328     break;
329   }
330
331   case ISD::SETCC:
332     if (N->getOperand(0).getNode()->getValueType(0).isFloatingPoint()) {
333       ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
334
335       unsigned Opc = Alpha::WTF;
336       bool rev = false;
337       bool inv = false;
338       switch(CC) {
339       default: DEBUG(N->dump(CurDAG)); assert(0 && "Unknown FP comparison!");
340       case ISD::SETEQ: case ISD::SETOEQ: case ISD::SETUEQ:
341         Opc = Alpha::CMPTEQ; break;
342       case ISD::SETLT: case ISD::SETOLT: case ISD::SETULT: 
343         Opc = Alpha::CMPTLT; break;
344       case ISD::SETLE: case ISD::SETOLE: case ISD::SETULE: 
345         Opc = Alpha::CMPTLE; break;
346       case ISD::SETGT: case ISD::SETOGT: case ISD::SETUGT: 
347         Opc = Alpha::CMPTLT; rev = true; break;
348       case ISD::SETGE: case ISD::SETOGE: case ISD::SETUGE: 
349         Opc = Alpha::CMPTLE; rev = true; break;
350       case ISD::SETNE: case ISD::SETONE: case ISD::SETUNE:
351         Opc = Alpha::CMPTEQ; inv = true; break;
352       case ISD::SETO:
353         Opc = Alpha::CMPTUN; inv = true; break;
354       case ISD::SETUO:
355         Opc = Alpha::CMPTUN; break;
356       };
357       SDValue tmp1 = N->getOperand(rev?1:0);
358       SDValue tmp2 = N->getOperand(rev?0:1);
359       SDNode *cmp = CurDAG->getTargetNode(Opc, dl, MVT::f64, tmp1, tmp2);
360       if (inv) 
361         cmp = CurDAG->getTargetNode(Alpha::CMPTEQ, dl, 
362                                     MVT::f64, SDValue(cmp, 0), 
363                                     CurDAG->getRegister(Alpha::F31, MVT::f64));
364       switch(CC) {
365       case ISD::SETUEQ: case ISD::SETULT: case ISD::SETULE:
366       case ISD::SETUNE: case ISD::SETUGT: case ISD::SETUGE:
367        {
368          SDNode* cmp2 = CurDAG->getTargetNode(Alpha::CMPTUN, dl, MVT::f64,
369                                               tmp1, tmp2);
370          cmp = CurDAG->getTargetNode(Alpha::ADDT, dl, MVT::f64, 
371                                      SDValue(cmp2, 0), SDValue(cmp, 0));
372          break;
373        }
374       default: break;
375       }
376
377       SDNode* LD = CurDAG->getTargetNode(Alpha::FTOIT, dl,
378                                          MVT::i64, SDValue(cmp, 0));
379       return CurDAG->getTargetNode(Alpha::CMPULT, dl, MVT::i64, 
380                                    CurDAG->getRegister(Alpha::R31, MVT::i64),
381                                    SDValue(LD,0));
382     }
383     break;
384
385   case ISD::SELECT:
386     if (N->getValueType(0).isFloatingPoint() &&
387         (N->getOperand(0).getOpcode() != ISD::SETCC ||
388          !N->getOperand(0).getOperand(1).getValueType().isFloatingPoint())) {
389       //This should be the condition not covered by the Patterns
390       //FIXME: Don't have SelectCode die, but rather return something testable
391       // so that things like this can be caught in fall though code
392       //move int to fp
393       bool isDouble = N->getValueType(0) == MVT::f64;
394       SDValue cond = N->getOperand(0);
395       SDValue TV = N->getOperand(1);
396       SDValue FV = N->getOperand(2);
397       
398       SDNode* LD = CurDAG->getTargetNode(Alpha::ITOFT, dl, MVT::f64, cond);
399       return CurDAG->getTargetNode(isDouble?Alpha::FCMOVNET:Alpha::FCMOVNES,
400                                    dl, MVT::f64, FV, TV, SDValue(LD,0));
401     }
402     break;
403
404   case ISD::AND: {
405     ConstantSDNode* SC = NULL;
406     ConstantSDNode* MC = NULL;
407     if (N->getOperand(0).getOpcode() == ISD::SRL &&
408         (MC = dyn_cast<ConstantSDNode>(N->getOperand(1))) &&
409         (SC = dyn_cast<ConstantSDNode>(N->getOperand(0).getOperand(1)))) {
410       uint64_t sval = SC->getZExtValue();
411       uint64_t mval = MC->getZExtValue();
412       // If the result is a zap, let the autogened stuff handle it.
413       if (get_zapImm(N->getOperand(0), mval))
414         break;
415       // given mask X, and shift S, we want to see if there is any zap in the
416       // mask if we play around with the botton S bits
417       uint64_t dontcare = (~0ULL) >> (64 - sval);
418       uint64_t mask = mval << sval;
419       
420       if (get_zapImm(mask | dontcare))
421         mask = mask | dontcare;
422       
423       if (get_zapImm(mask)) {
424         SDValue Z = 
425           SDValue(CurDAG->getTargetNode(Alpha::ZAPNOTi, dl, MVT::i64,
426                                           N->getOperand(0).getOperand(0),
427                                           getI64Imm(get_zapImm(mask))), 0);
428         return CurDAG->getTargetNode(Alpha::SRLr, dl, MVT::i64, Z, 
429                                      getI64Imm(sval));
430       }
431     }
432     break;
433   }
434
435   }
436
437   return SelectCode(Op);
438 }
439
440 void AlphaDAGToDAGISel::SelectCALL(SDValue Op) {
441   //TODO: add flag stuff to prevent nondeturministic breakage!
442
443   SDNode *N = Op.getNode();
444   SDValue Chain = N->getOperand(0);
445   SDValue Addr = N->getOperand(1);
446   SDValue InFlag(0,0);  // Null incoming flag value.
447   DebugLoc dl = N->getDebugLoc();
448
449    std::vector<SDValue> CallOperands;
450    std::vector<MVT> TypeOperands;
451   
452    //grab the arguments
453    for(int i = 2, e = N->getNumOperands(); i < e; ++i) {
454      TypeOperands.push_back(N->getOperand(i).getValueType());
455      CallOperands.push_back(N->getOperand(i));
456    }
457    int count = N->getNumOperands() - 2;
458
459    static const unsigned args_int[] = {Alpha::R16, Alpha::R17, Alpha::R18,
460                                        Alpha::R19, Alpha::R20, Alpha::R21};
461    static const unsigned args_float[] = {Alpha::F16, Alpha::F17, Alpha::F18,
462                                          Alpha::F19, Alpha::F20, Alpha::F21};
463    
464    for (int i = 6; i < count; ++i) {
465      unsigned Opc = Alpha::WTF;
466      if (TypeOperands[i].isInteger()) {
467        Opc = Alpha::STQ;
468      } else if (TypeOperands[i] == MVT::f32) {
469        Opc = Alpha::STS;
470      } else if (TypeOperands[i] == MVT::f64) {
471        Opc = Alpha::STT;
472      } else
473        assert(0 && "Unknown operand"); 
474
475      SDValue Ops[] = { CallOperands[i],  getI64Imm((i - 6) * 8), 
476                        CurDAG->getCopyFromReg(Chain, dl, Alpha::R30, MVT::i64),
477                        Chain };
478      Chain = SDValue(CurDAG->getTargetNode(Opc, dl, MVT::Other, Ops, 4), 0);
479    }
480    for (int i = 0; i < std::min(6, count); ++i) {
481      if (TypeOperands[i].isInteger()) {
482        Chain = CurDAG->getCopyToReg(Chain, dl, args_int[i], 
483                                     CallOperands[i], InFlag);
484        InFlag = Chain.getValue(1);
485      } else if (TypeOperands[i] == MVT::f32 || TypeOperands[i] == MVT::f64) {
486        Chain = CurDAG->getCopyToReg(Chain, dl, args_float[i], 
487                                     CallOperands[i], InFlag);
488        InFlag = Chain.getValue(1);
489      } else
490        assert(0 && "Unknown operand"); 
491    }
492
493    // Finally, once everything is in registers to pass to the call, emit the
494    // call itself.
495    if (Addr.getOpcode() == AlphaISD::GPRelLo) {
496      SDValue GOT = SDValue(getGlobalBaseReg(), 0);
497      Chain = CurDAG->getCopyToReg(Chain, dl, Alpha::R29, GOT, InFlag);
498      InFlag = Chain.getValue(1);
499      Chain = SDValue(CurDAG->getTargetNode(Alpha::BSR, dl, MVT::Other, 
500                                            MVT::Flag, Addr.getOperand(0), 
501                                            Chain, InFlag), 0);
502    } else {
503      Chain = CurDAG->getCopyToReg(Chain, dl, Alpha::R27, Addr, InFlag);
504      InFlag = Chain.getValue(1);
505      Chain = SDValue(CurDAG->getTargetNode(Alpha::JSR, dl, MVT::Other,
506                                              MVT::Flag, Chain, InFlag), 0);
507    }
508    InFlag = Chain.getValue(1);
509
510    std::vector<SDValue> CallResults;
511   
512    switch (N->getValueType(0).getSimpleVT()) {
513    default: assert(0 && "Unexpected ret value!");
514      case MVT::Other: break;
515    case MVT::i64:
516      Chain = CurDAG->getCopyFromReg(Chain, dl, 
517                                     Alpha::R0, MVT::i64, InFlag).getValue(1);
518      CallResults.push_back(Chain.getValue(0));
519      break;
520    case MVT::f32:
521      Chain = CurDAG->getCopyFromReg(Chain, dl, 
522                                     Alpha::F0, MVT::f32, InFlag).getValue(1);
523      CallResults.push_back(Chain.getValue(0));
524      break;
525    case MVT::f64:
526      Chain = CurDAG->getCopyFromReg(Chain, dl,
527                                     Alpha::F0, MVT::f64, InFlag).getValue(1);
528      CallResults.push_back(Chain.getValue(0));
529      break;
530    }
531
532    CallResults.push_back(Chain);
533    for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
534      ReplaceUses(Op.getValue(i), CallResults[i]);
535 }
536
537
538 /// createAlphaISelDag - This pass converts a legalized DAG into a 
539 /// Alpha-specific DAG, ready for instruction scheduling.
540 ///
541 FunctionPass *llvm::createAlphaISelDag(AlphaTargetMachine &TM) {
542   return new AlphaDAGToDAGISel(TM);
543 }