initial support for fp compares. Unordered compares not implemented yet
[oota-llvm.git] / lib / Target / ARM / ARMISelDAGToDAG.cpp
1 //===-- ARMISelDAGToDAG.cpp - A dag to dag inst selector for ARM ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines an instruction selector for the ARM target.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM.h"
15 #include "ARMTargetMachine.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Constants.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Support/Debug.h"
29 #include <iostream>
30 #include <vector>
31 using namespace llvm;
32
33 namespace {
34   class ARMTargetLowering : public TargetLowering {
35     int VarArgsFrameIndex;            // FrameIndex for start of varargs area.
36   public:
37     ARMTargetLowering(TargetMachine &TM);
38     virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
39     virtual const char *getTargetNodeName(unsigned Opcode) const;
40   };
41
42 }
43
44 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
45   : TargetLowering(TM) {
46   addRegisterClass(MVT::i32, ARM::IntRegsRegisterClass);
47   addRegisterClass(MVT::f32, ARM::FPRegsRegisterClass);
48   addRegisterClass(MVT::f64, ARM::DFPRegsRegisterClass);
49
50   setLoadXAction(ISD::EXTLOAD, MVT::f32, Expand);
51
52   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
53
54   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
55
56   setOperationAction(ISD::RET,           MVT::Other, Custom);
57   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
58   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
59
60   setOperationAction(ISD::SELECT, MVT::i32, Expand);
61
62   setOperationAction(ISD::SETCC, MVT::i32, Expand);
63   setOperationAction(ISD::SETCC, MVT::f32, Expand);
64   setOperationAction(ISD::SETCC, MVT::f64, Expand);
65
66   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
67   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
68   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
69   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
70
71   setOperationAction(ISD::VASTART,       MVT::Other, Custom);
72   setOperationAction(ISD::VAEND,         MVT::Other, Expand);
73
74   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
75   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
76
77   setSchedulingPreference(SchedulingForRegPressure);
78   computeRegisterProperties();
79 }
80
81 namespace llvm {
82   namespace ARMISD {
83     enum NodeType {
84       // Start the numbering where the builting ops and target ops leave off.
85       FIRST_NUMBER = ISD::BUILTIN_OP_END+ARM::INSTRUCTION_LIST_END,
86       /// CALL - A direct function call.
87       CALL,
88
89       /// Return with a flag operand.
90       RET_FLAG,
91
92       CMP,
93
94       SELECT,
95
96       BR,
97
98       FSITOS,
99
100       FSITOD,
101
102       FUITOS,
103
104       FUITOD,
105
106       FMRRD,
107
108       FMDRR,
109
110       FMSTAT
111     };
112   }
113 }
114
115 /// DAGCCToARMCC - Convert a DAG integer condition code to an ARM CC
116 //Note: ARM doesn't have condition codes corresponding to the ordered
117 //condition codes of LLVM. We use exception raising instructions so
118 //that we can be sure that V == 0 and test only the rest of the expression.
119 static ARMCC::CondCodes DAGCCToARMCC(ISD::CondCode CC) {
120   switch (CC) {
121   default:
122     std::cerr << "CC = " << CC << "\n";
123     assert(0 && "Unknown condition code!");
124   case ISD::SETUGT: return ARMCC::HI;
125   case ISD::SETULE: return ARMCC::LS;
126   case ISD::SETLE:
127   case ISD::SETOLE: return ARMCC::LE;
128   case ISD::SETLT:
129   case ISD::SETOLT: return ARMCC::LT;
130   case ISD::SETGT:
131   case ISD::SETOGT: return ARMCC::GT;
132   case ISD::SETNE:  return ARMCC::NE;
133   case ISD::SETEQ:
134   case ISD::SETOEQ: return ARMCC::EQ;
135   case ISD::SETGE:
136   case ISD::SETOGE: return ARMCC::GE;
137   case ISD::SETUGE: return ARMCC::CS;
138   case ISD::SETULT: return ARMCC::CC;
139   }
140 }
141
142 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
143   switch (Opcode) {
144   default: return 0;
145   case ARMISD::CALL:          return "ARMISD::CALL";
146   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
147   case ARMISD::SELECT:        return "ARMISD::SELECT";
148   case ARMISD::CMP:           return "ARMISD::CMP";
149   case ARMISD::BR:            return "ARMISD::BR";
150   case ARMISD::FSITOS:        return "ARMISD::FSITOS";
151   case ARMISD::FSITOD:        return "ARMISD::FSITOD";
152   case ARMISD::FUITOS:        return "ARMISD::FUITOS";
153   case ARMISD::FUITOD:        return "ARMISD::FUITOD";
154   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
155   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
156   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
157   }
158 }
159
160 class ArgumentLayout {
161   std::vector<bool>           is_reg;
162   std::vector<unsigned>       pos;
163   std::vector<MVT::ValueType> types;
164 public:
165   ArgumentLayout(const std::vector<MVT::ValueType> &Types) {
166     types = Types;
167
168     unsigned      RegNum = 0;
169     unsigned StackOffset = 0;
170     for(std::vector<MVT::ValueType>::const_iterator I = Types.begin();
171         I != Types.end();
172         ++I) {
173       MVT::ValueType VT = *I;
174       assert(VT == MVT::i32 || VT == MVT::f32 || VT == MVT::f64);
175       unsigned     size = MVT::getSizeInBits(VT)/32;
176
177       RegNum = ((RegNum + size - 1) / size) * size;
178       if (RegNum < 4) {
179         pos.push_back(RegNum);
180         is_reg.push_back(true);
181         RegNum += size;
182       } else {
183         unsigned bytes = size * 32/8;
184         StackOffset = ((StackOffset + bytes - 1) / bytes) * bytes;
185         pos.push_back(StackOffset);
186         is_reg.push_back(false);
187         StackOffset += bytes;
188       }
189     }
190   }
191   unsigned getRegisterNum(unsigned argNum) {
192     assert(isRegister(argNum));
193     return pos[argNum];
194   }
195   unsigned getOffset(unsigned argNum) {
196     assert(isOffset(argNum));
197     return pos[argNum];
198   }
199   unsigned isRegister(unsigned argNum) {
200     assert(argNum < is_reg.size());
201     return is_reg[argNum];
202   }
203   unsigned isOffset(unsigned argNum) {
204     return !isRegister(argNum);
205   }
206   MVT::ValueType getType(unsigned argNum) {
207     assert(argNum < types.size());
208     return types[argNum];
209   }
210   unsigned getStackSize(void) {
211     int last = is_reg.size() - 1;
212     if (last < 0)
213       return 0;
214     if (isRegister(last))
215       return 0;
216     return getOffset(last) + MVT::getSizeInBits(getType(last))/8;
217   }
218   int lastRegArg(void) {
219     int size = is_reg.size();
220     int last = 0;
221     while(last < size && isRegister(last))
222       last++;
223     last--;
224     return last;
225   }
226   int lastRegNum(void) {
227     int            l = lastRegArg();
228     if (l < 0)
229       return -1;
230     unsigned       r = getRegisterNum(l);
231     MVT::ValueType t = getType(l);
232     assert(t == MVT::i32 || t == MVT::f32 || t == MVT::f64);
233     if (t == MVT::f64)
234       return r + 1;
235     return r;
236   }
237 };
238
239 // This transforms a ISD::CALL node into a
240 // callseq_star <- ARMISD:CALL <- callseq_end
241 // chain
242 static SDOperand LowerCALL(SDOperand Op, SelectionDAG &DAG) {
243   SDOperand Chain    = Op.getOperand(0);
244   unsigned CallConv  = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
245   assert(CallConv == CallingConv::C && "unknown calling convention");
246   bool isVarArg      = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
247   bool isTailCall    = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
248   assert(isTailCall == false && "tail call not supported");
249   SDOperand Callee   = Op.getOperand(4);
250   unsigned NumOps    = (Op.getNumOperands() - 5) / 2;
251   SDOperand StackPtr = DAG.getRegister(ARM::R13, MVT::i32);
252   static const unsigned regs[] = {
253     ARM::R0, ARM::R1, ARM::R2, ARM::R3
254   };
255
256   std::vector<MVT::ValueType> Types;
257   for (unsigned i = 0; i < NumOps; ++i) {
258     MVT::ValueType VT = Op.getOperand(5+2*i).getValueType();
259     Types.push_back(VT);
260   }
261   ArgumentLayout Layout(Types);
262
263   unsigned NumBytes = Layout.getStackSize();
264
265   Chain = DAG.getCALLSEQ_START(Chain,
266                                DAG.getConstant(NumBytes, MVT::i32));
267
268   //Build a sequence of stores
269   std::vector<SDOperand> MemOpChains;
270   for (unsigned i = Layout.lastRegArg() + 1; i < NumOps; ++i) {
271     SDOperand      Arg = Op.getOperand(5+2*i);
272     unsigned ArgOffset = Layout.getOffset(i);
273     SDOperand   PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
274     PtrOff             = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
275     MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff,
276                                        DAG.getSrcValue(NULL)));
277   }
278   if (!MemOpChains.empty())
279     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
280                         &MemOpChains[0], MemOpChains.size());
281
282   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
283   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
284   // node so that legalize doesn't hack it.
285   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
286     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
287
288   // If this is a direct call, pass the chain and the callee.
289   assert (Callee.Val);
290   std::vector<SDOperand> Ops;
291   Ops.push_back(Chain);
292   Ops.push_back(Callee);
293
294   // Build a sequence of copy-to-reg nodes chained together with token chain
295   // and flag operands which copy the outgoing args into the appropriate regs.
296   SDOperand InFlag;
297   for (int i = 0, e = Layout.lastRegArg(); i <= e; ++i) {
298     SDOperand     Arg = Op.getOperand(5+2*i);
299     unsigned   RegNum = Layout.getRegisterNum(i);
300     unsigned     Reg1 = regs[RegNum];
301     MVT::ValueType VT = Layout.getType(i);
302     assert(VT == Arg.getValueType());
303     assert(VT == MVT::i32 || VT == MVT::f32 || VT == MVT::f64);
304
305     // Add argument register to the end of the list so that it is known live
306     // into the call.
307     Ops.push_back(DAG.getRegister(Reg1, MVT::i32));
308     if (VT == MVT::f64) {
309       unsigned    Reg2 = regs[RegNum + 1];
310       SDOperand SDReg1 = DAG.getRegister(Reg1, MVT::i32);
311       SDOperand SDReg2 = DAG.getRegister(Reg2, MVT::i32);
312
313       Ops.push_back(DAG.getRegister(Reg2, MVT::i32));
314       SDVTList    VTs = DAG.getVTList(MVT::Other, MVT::Flag);
315       SDOperand Ops[] = {Chain, SDReg1, SDReg2, Arg, InFlag};
316       Chain = DAG.getNode(ARMISD::FMRRD, VTs, Ops, InFlag.Val ? 5 : 4);
317     } else {
318       if (VT == MVT::f32)
319         Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Arg);
320       Chain = DAG.getCopyToReg(Chain, Reg1, Arg, InFlag);
321     }
322     InFlag = Chain.getValue(1);
323   }
324
325   std::vector<MVT::ValueType> NodeTys;
326   NodeTys.push_back(MVT::Other);   // Returns a chain
327   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
328
329   unsigned CallOpc = ARMISD::CALL;
330   if (InFlag.Val)
331     Ops.push_back(InFlag);
332   Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
333   InFlag = Chain.getValue(1);
334
335   std::vector<SDOperand> ResultVals;
336   NodeTys.clear();
337
338   // If the call has results, copy the values out of the ret val registers.
339   MVT::ValueType VT = Op.Val->getValueType(0);
340   if (VT != MVT::Other) {
341     assert(VT == MVT::i32 || VT == MVT::f32 || VT == MVT::f64);
342     SDOperand Value;
343
344     SDOperand Value1 = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag);
345     Chain            = Value1.getValue(1);
346     InFlag           = Value1.getValue(2);
347     if (VT == MVT::i32)
348       Value = Value1;
349     if (VT == MVT::f32)
350       Value = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Value1);
351     if (VT == MVT::f64) {
352       SDOperand Value2 = DAG.getCopyFromReg(Chain, ARM::R1, MVT::i32, InFlag);
353       Chain            = Value2.getValue(1);
354       Value            = DAG.getNode(ARMISD::FMDRR, MVT::f64, Value1, Value2);
355     }
356     ResultVals.push_back(Value);
357     NodeTys.push_back(VT);
358   }
359
360   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
361                       DAG.getConstant(NumBytes, MVT::i32));
362   NodeTys.push_back(MVT::Other);
363
364   if (ResultVals.empty())
365     return Chain;
366
367   ResultVals.push_back(Chain);
368   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, &ResultVals[0],
369                               ResultVals.size());
370   return Res.getValue(Op.ResNo);
371 }
372
373 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
374   SDOperand Copy;
375   SDOperand Chain = Op.getOperand(0);
376   SDOperand    R0 = DAG.getRegister(ARM::R0, MVT::i32);
377   SDOperand    R1 = DAG.getRegister(ARM::R1, MVT::i32);
378
379   switch(Op.getNumOperands()) {
380   default:
381     assert(0 && "Do not know how to return this many arguments!");
382     abort();
383   case 1: {
384     SDOperand LR = DAG.getRegister(ARM::R14, MVT::i32);
385     return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Chain);
386   }
387   case 3: {
388     SDOperand Val = Op.getOperand(1);
389     assert(Val.getValueType() == MVT::i32 ||
390            Val.getValueType() == MVT::f32 ||
391            Val.getValueType() == MVT::f64);
392
393     if (Val.getValueType() == MVT::f64) {
394       SDVTList    VTs = DAG.getVTList(MVT::Other, MVT::Flag);
395       SDOperand Ops[] = {Chain, R0, R1, Val};
396       Copy  = DAG.getNode(ARMISD::FMRRD, VTs, Ops, 4);
397     } else {
398       if (Val.getValueType() == MVT::f32)
399         Val = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Val);
400       Copy = DAG.getCopyToReg(Chain, R0, Val, SDOperand());
401     }
402
403     if (DAG.getMachineFunction().liveout_empty()) {
404       DAG.getMachineFunction().addLiveOut(ARM::R0);
405       if (Val.getValueType() == MVT::f64)
406         DAG.getMachineFunction().addLiveOut(ARM::R1);
407     }
408     break;
409   }
410   case 5:
411     Copy = DAG.getCopyToReg(Chain, ARM::R1, Op.getOperand(3), SDOperand());
412     Copy = DAG.getCopyToReg(Copy, ARM::R0, Op.getOperand(1), Copy.getValue(1));
413     // If we haven't noted the R0+R1 are live out, do so now.
414     if (DAG.getMachineFunction().liveout_empty()) {
415       DAG.getMachineFunction().addLiveOut(ARM::R0);
416       DAG.getMachineFunction().addLiveOut(ARM::R1);
417     }
418     break;
419   }
420
421   //We must use RET_FLAG instead of BRIND because BRIND doesn't have a flag
422   return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
423 }
424
425 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
426   MVT::ValueType PtrVT = Op.getValueType();
427   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
428   Constant *C = CP->getConstVal();
429   SDOperand CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
430
431   return CPI;
432 }
433
434 static SDOperand LowerGlobalAddress(SDOperand Op,
435                                     SelectionDAG &DAG) {
436   GlobalValue  *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
437   int alignment = 2;
438   SDOperand CPAddr = DAG.getConstantPool(GV, MVT::i32, alignment);
439   return DAG.getLoad(MVT::i32, DAG.getEntryNode(), CPAddr, NULL, 0);
440 }
441
442 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
443                               unsigned VarArgsFrameIndex) {
444   // vastart just stores the address of the VarArgsFrameIndex slot into the
445   // memory location argument.
446   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
447   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
448   return DAG.getStore(Op.getOperand(0), FR, Op.getOperand(1), Op.getOperand(2));
449 }
450
451 static SDOperand LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG,
452                                        int &VarArgsFrameIndex) {
453   MachineFunction   &MF = DAG.getMachineFunction();
454   MachineFrameInfo *MFI = MF.getFrameInfo();
455   SSARegMap     *RegMap = MF.getSSARegMap();
456   unsigned      NumArgs = Op.Val->getNumValues()-1;
457   SDOperand        Root = Op.getOperand(0);
458   bool         isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
459   static const unsigned REGS[] = {
460     ARM::R0, ARM::R1, ARM::R2, ARM::R3
461   };
462
463   std::vector<MVT::ValueType> Types(Op.Val->value_begin(), Op.Val->value_end() - 1);
464   ArgumentLayout Layout(Types);
465
466   std::vector<SDOperand> ArgValues;
467   for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo) {
468     MVT::ValueType VT = Types[ArgNo];
469
470     SDOperand Value;
471     if (Layout.isRegister(ArgNo)) {
472       assert(VT == MVT::i32 || VT == MVT::f32 || VT == MVT::f64);
473       unsigned  RegNum = Layout.getRegisterNum(ArgNo);
474       unsigned    Reg1 = REGS[RegNum];
475       unsigned   VReg1 = RegMap->createVirtualRegister(&ARM::IntRegsRegClass);
476       SDOperand Value1 = DAG.getCopyFromReg(Root, VReg1, MVT::i32);
477       MF.addLiveIn(Reg1, VReg1);
478       if (VT == MVT::f64) {
479         unsigned    Reg2 = REGS[RegNum + 1];
480         unsigned   VReg2 = RegMap->createVirtualRegister(&ARM::IntRegsRegClass);
481         SDOperand Value2 = DAG.getCopyFromReg(Root, VReg2, MVT::i32);
482         MF.addLiveIn(Reg2, VReg2);
483         Value            = DAG.getNode(ARMISD::FMDRR, MVT::f64, Value1, Value2);
484       } else {
485         Value = Value1;
486         if (VT == MVT::f32)
487           Value = DAG.getNode(ISD::BIT_CONVERT, VT, Value);
488       }
489     } else {
490       // If the argument is actually used, emit a load from the right stack
491       // slot.
492       if (!Op.Val->hasNUsesOfValue(0, ArgNo)) {
493         unsigned Offset = Layout.getOffset(ArgNo);
494         unsigned   Size = MVT::getSizeInBits(VT)/8;
495         int          FI = MFI->CreateFixedObject(Size, Offset);
496         SDOperand   FIN = DAG.getFrameIndex(FI, VT);
497         Value = DAG.getLoad(VT, Root, FIN, NULL, 0);
498       } else {
499         Value = DAG.getNode(ISD::UNDEF, VT);
500       }
501     }
502     ArgValues.push_back(Value);
503   }
504
505   unsigned NextRegNum = Layout.lastRegNum() + 1;
506
507   if (isVarArg) {
508     //If this function is vararg we must store the remaing
509     //registers so that they can be acessed with va_start
510     VarArgsFrameIndex = MFI->CreateFixedObject(MVT::getSizeInBits(MVT::i32)/8,
511                                                -16 + NextRegNum * 4);
512
513     SmallVector<SDOperand, 4> MemOps;
514     for (unsigned RegNo = NextRegNum; RegNo < 4; ++RegNo) {
515       int RegOffset = - (4 - RegNo) * 4;
516       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(MVT::i32)/8,
517                                       RegOffset);
518       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
519
520       unsigned VReg = RegMap->createVirtualRegister(&ARM::IntRegsRegClass);
521       MF.addLiveIn(REGS[RegNo], VReg);
522
523       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
524       SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN,
525                                      DAG.getSrcValue(NULL));
526       MemOps.push_back(Store);
527     }
528     Root = DAG.getNode(ISD::TokenFactor, MVT::Other,&MemOps[0],MemOps.size());
529   }
530
531   ArgValues.push_back(Root);
532
533   // Return the new list of results.
534   std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
535                                     Op.Val->value_end());
536   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
537 }
538
539 static SDOperand GetCMP(ISD::CondCode CC, SDOperand LHS, SDOperand RHS,
540                         SelectionDAG &DAG) {
541   MVT::ValueType vt = LHS.getValueType();
542   assert(vt == MVT::i32 || vt == MVT::f32);
543   //Note: unordered floating point compares should use a non throwing
544   //compare.
545   bool isUnorderedFloat = vt == MVT::f32 &&
546     (CC >= ISD::SETUO && CC <= ISD::SETUNE);
547   assert(!isUnorderedFloat && "Unordered float compares are not supported");
548
549   SDOperand Cmp = DAG.getNode(ARMISD::CMP, MVT::Flag, LHS, RHS);
550   if (vt != MVT::i32)
551     Cmp = DAG.getNode(ARMISD::FMSTAT, MVT::Flag, Cmp);
552   return Cmp;
553 }
554
555 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) {
556   SDOperand LHS = Op.getOperand(0);
557   SDOperand RHS = Op.getOperand(1);
558   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
559   SDOperand TrueVal = Op.getOperand(2);
560   SDOperand FalseVal = Op.getOperand(3);
561   SDOperand      Cmp = GetCMP(CC, LHS, RHS, DAG);
562   SDOperand    ARMCC = DAG.getConstant(DAGCCToARMCC(CC), MVT::i32);
563   return DAG.getNode(ARMISD::SELECT, MVT::i32, TrueVal, FalseVal, ARMCC, Cmp);
564 }
565
566 static SDOperand LowerBR_CC(SDOperand Op, SelectionDAG &DAG) {
567   SDOperand  Chain = Op.getOperand(0);
568   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
569   SDOperand    LHS = Op.getOperand(2);
570   SDOperand    RHS = Op.getOperand(3);
571   SDOperand   Dest = Op.getOperand(4);
572   SDOperand    Cmp = GetCMP(CC, LHS, RHS, DAG);
573   SDOperand  ARMCC = DAG.getConstant(DAGCCToARMCC(CC), MVT::i32);
574   return DAG.getNode(ARMISD::BR, MVT::Other, Chain, Dest, ARMCC, Cmp);
575 }
576
577 static SDOperand LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
578   SDOperand IntVal  = Op.getOperand(0);
579   assert(IntVal.getValueType() == MVT::i32);
580   MVT::ValueType vt = Op.getValueType();
581   assert(vt == MVT::f32 ||
582          vt == MVT::f64);
583
584   SDOperand Tmp = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, IntVal);
585   ARMISD::NodeType op = vt == MVT::f32 ? ARMISD::FSITOS : ARMISD::FSITOD;
586   return DAG.getNode(op, vt, Tmp);
587 }
588
589 static SDOperand LowerUINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
590   SDOperand IntVal  = Op.getOperand(0);
591   assert(IntVal.getValueType() == MVT::i32);
592   MVT::ValueType vt = Op.getValueType();
593   assert(vt == MVT::f32 ||
594          vt == MVT::f64);
595
596   SDOperand Tmp = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, IntVal);
597   ARMISD::NodeType op = vt == MVT::f32 ? ARMISD::FUITOS : ARMISD::FUITOD;
598   return DAG.getNode(op, vt, Tmp);
599 }
600
601 SDOperand ARMTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
602   switch (Op.getOpcode()) {
603   default:
604     assert(0 && "Should not custom lower this!");
605     abort();
606   case ISD::ConstantPool:
607     return LowerConstantPool(Op, DAG);
608   case ISD::GlobalAddress:
609     return LowerGlobalAddress(Op, DAG);
610   case ISD::SINT_TO_FP:
611     return LowerSINT_TO_FP(Op, DAG);
612   case ISD::UINT_TO_FP:
613     return LowerUINT_TO_FP(Op, DAG);
614   case ISD::FORMAL_ARGUMENTS:
615     return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex);
616   case ISD::CALL:
617     return LowerCALL(Op, DAG);
618   case ISD::RET:
619     return LowerRET(Op, DAG);
620   case ISD::SELECT_CC:
621     return LowerSELECT_CC(Op, DAG);
622   case ISD::BR_CC:
623     return LowerBR_CC(Op, DAG);
624   case ISD::VASTART:
625     return LowerVASTART(Op, DAG, VarArgsFrameIndex);
626   }
627 }
628
629 //===----------------------------------------------------------------------===//
630 // Instruction Selector Implementation
631 //===----------------------------------------------------------------------===//
632
633 //===--------------------------------------------------------------------===//
634 /// ARMDAGToDAGISel - ARM specific code to select ARM machine
635 /// instructions for SelectionDAG operations.
636 ///
637 namespace {
638 class ARMDAGToDAGISel : public SelectionDAGISel {
639   ARMTargetLowering Lowering;
640
641 public:
642   ARMDAGToDAGISel(TargetMachine &TM)
643     : SelectionDAGISel(Lowering), Lowering(TM) {
644   }
645
646   SDNode *Select(SDOperand Op);
647   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
648   bool SelectAddrRegImm(SDOperand N, SDOperand &Offset, SDOperand &Base);
649   bool SelectAddrMode1(SDOperand N, SDOperand &Arg, SDOperand &Shift,
650                        SDOperand &ShiftType);
651
652   // Include the pieces autogenerated from the target description.
653 #include "ARMGenDAGISel.inc"
654 };
655
656 void ARMDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
657   DEBUG(BB->dump());
658
659   DAG.setRoot(SelectRoot(DAG.getRoot()));
660   DAG.RemoveDeadNodes();
661
662   ScheduleAndEmitDAG(DAG);
663 }
664
665 static bool isInt12Immediate(SDNode *N, short &Imm) {
666   if (N->getOpcode() != ISD::Constant)
667     return false;
668
669   int32_t t = cast<ConstantSDNode>(N)->getValue();
670   int max = 1<<12;
671   int min = -max;
672   if (t > min && t < max) {
673     Imm = t;
674     return true;
675   }
676   else
677     return false;
678 }
679
680 static bool isInt12Immediate(SDOperand Op, short &Imm) {
681   return isInt12Immediate(Op.Val, Imm);
682 }
683
684 static uint32_t rotateL(uint32_t x) {
685   uint32_t bit31 = (x & (1 << 31)) >> 31;
686   uint32_t     t = x << 1;
687   return t | bit31;
688 }
689
690 static bool isUInt8Immediate(uint32_t x) {
691   return x < (1 << 8);
692 }
693
694 static bool isRotInt8Immediate(uint32_t x) {
695   int r;
696   for (r = 0; r < 16; r++) {
697     if (isUInt8Immediate(x))
698       return true;
699     x = rotateL(rotateL(x));
700   }
701   return false;
702 }
703
704 bool ARMDAGToDAGISel::SelectAddrMode1(SDOperand N,
705                                       SDOperand &Arg,
706                                       SDOperand &Shift,
707                                       SDOperand &ShiftType) {
708   switch(N.getOpcode()) {
709   case ISD::Constant: {
710     uint32_t val = cast<ConstantSDNode>(N)->getValue();
711     if(!isRotInt8Immediate(val)) {
712       const Type  *t =  MVT::getTypeForValueType(MVT::i32);
713       Constant    *C = ConstantUInt::get(t, val);
714       int  alignment = 2;
715       SDOperand Addr = CurDAG->getTargetConstantPool(C, MVT::i32, alignment);
716       SDOperand    Z = CurDAG->getTargetConstant(0,     MVT::i32);
717       SDNode      *n = CurDAG->getTargetNode(ARM::ldr,  MVT::i32, Z, Addr);
718       Arg            = SDOperand(n, 0);
719     } else
720       Arg            = CurDAG->getTargetConstant(val,    MVT::i32);
721
722     Shift     = CurDAG->getTargetConstant(0,             MVT::i32);
723     ShiftType = CurDAG->getTargetConstant(ARMShift::LSL, MVT::i32);
724     return true;
725   }
726   case ISD::SRA:
727     Arg       = N.getOperand(0);
728     Shift     = N.getOperand(1);
729     ShiftType = CurDAG->getTargetConstant(ARMShift::ASR, MVT::i32);
730     return true;
731   case ISD::SRL:
732     Arg       = N.getOperand(0);
733     Shift     = N.getOperand(1);
734     ShiftType = CurDAG->getTargetConstant(ARMShift::LSR, MVT::i32);
735     return true;
736   case ISD::SHL:
737     Arg       = N.getOperand(0);
738     Shift     = N.getOperand(1);
739     ShiftType = CurDAG->getTargetConstant(ARMShift::LSL, MVT::i32);
740     return true;
741   }
742
743   Arg       = N;
744   Shift     = CurDAG->getTargetConstant(0, MVT::i32);
745   ShiftType = CurDAG->getTargetConstant(ARMShift::LSL, MVT::i32);
746   return true;
747 }
748
749 //register plus/minus 12 bit offset
750 bool ARMDAGToDAGISel::SelectAddrRegImm(SDOperand N, SDOperand &Offset,
751                                     SDOperand &Base) {
752   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(N)) {
753     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
754     Offset = CurDAG->getTargetConstant(0, MVT::i32);
755     return true;
756   }
757   if (N.getOpcode() == ISD::ADD) {
758     short imm = 0;
759     if (isInt12Immediate(N.getOperand(1), imm)) {
760       Offset = CurDAG->getTargetConstant(imm, MVT::i32);
761       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
762         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
763       } else {
764         Base = N.getOperand(0);
765       }
766       return true; // [r+i]
767     }
768   }
769
770   Offset = CurDAG->getTargetConstant(0, MVT::i32);
771   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
772     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
773   }
774   else
775     Base = N;
776   return true;      //any address fits in a register
777 }
778
779 SDNode *ARMDAGToDAGISel::Select(SDOperand Op) {
780   SDNode *N = Op.Val;
781
782   switch (N->getOpcode()) {
783   default:
784     return SelectCode(Op);
785     break;
786   }
787   return NULL;
788 }
789
790 }  // end anonymous namespace
791
792 /// createARMISelDag - This pass converts a legalized DAG into a
793 /// ARM-specific DAG, ready for instruction scheduling.
794 ///
795 FunctionPass *llvm::createARMISelDag(TargetMachine &TM) {
796   return new ARMDAGToDAGISel(TM);
797 }