add the SETULT condition code
[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/Intrinsics.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/SelectionDAGISel.h"
25 #include "llvm/CodeGen/SSARegMap.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Support/Debug.h"
28 #include <iostream>
29 #include <queue>
30 #include <set>
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
48   //LLVM requires that a register class supports MVT::f64!
49   addRegisterClass(MVT::f64, ARM::IntRegsRegisterClass);
50
51   setOperationAction(ISD::RET,           MVT::Other, Custom);
52   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
53   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
54
55   setOperationAction(ISD::SETCC, MVT::i32, Expand);
56   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
57   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
58
59   setOperationAction(ISD::VASTART,       MVT::Other, Custom);
60   setOperationAction(ISD::VAEND,         MVT::Other, Expand);
61
62   setSchedulingPreference(SchedulingForRegPressure);
63   computeRegisterProperties();
64 }
65
66 namespace llvm {
67   namespace ARMISD {
68     enum NodeType {
69       // Start the numbering where the builting ops and target ops leave off.
70       FIRST_NUMBER = ISD::BUILTIN_OP_END+ARM::INSTRUCTION_LIST_END,
71       /// CALL - A direct function call.
72       CALL,
73
74       /// Return with a flag operand.
75       RET_FLAG,
76
77       CMP,
78
79       SELECT,
80
81       BR
82     };
83   }
84 }
85
86 /// DAGCCToARMCC - Convert a DAG integer condition code to an ARM CC
87 static ARMCC::CondCodes DAGCCToARMCC(ISD::CondCode CC) {
88   switch (CC) {
89   default: assert(0 && "Unknown condition code!");
90   case ISD::SETNE:  return ARMCC::NE;
91   case ISD::SETEQ:  return ARMCC::EQ;
92   case ISD::SETGE:  return ARMCC::GE;
93   case ISD::SETUGE: return ARMCC::CS;
94   case ISD::SETULT: return ARMCC::CC;
95   }
96 }
97
98 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
99   switch (Opcode) {
100   default: return 0;
101   case ARMISD::CALL:          return "ARMISD::CALL";
102   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
103   case ARMISD::SELECT:        return "ARMISD::SELECT";
104   case ARMISD::CMP:           return "ARMISD::CMP";
105   case ARMISD::BR:            return "ARMISD::BR";
106   }
107 }
108
109 // This transforms a ISD::CALL node into a
110 // callseq_star <- ARMISD:CALL <- callseq_end
111 // chain
112 static SDOperand LowerCALL(SDOperand Op, SelectionDAG &DAG) {
113   SDOperand Chain    = Op.getOperand(0);
114   unsigned CallConv  = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
115   assert(CallConv == CallingConv::C && "unknown calling convention");
116   bool isVarArg      = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
117   bool isTailCall    = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0;
118   assert(isTailCall == false && "tail call not supported");
119   SDOperand Callee   = Op.getOperand(4);
120   unsigned NumOps    = (Op.getNumOperands() - 5) / 2;
121
122   // Count how many bytes are to be pushed on the stack.
123   unsigned NumBytes = 0;
124
125   // Add up all the space actually used.
126   for (unsigned i = 4; i < NumOps; ++i)
127     NumBytes += MVT::getSizeInBits(Op.getOperand(5+2*i).getValueType())/8;
128
129   // Adjust the stack pointer for the new arguments...
130   // These operations are automatically eliminated by the prolog/epilog pass
131   Chain = DAG.getCALLSEQ_START(Chain,
132                                DAG.getConstant(NumBytes, MVT::i32));
133
134   SDOperand StackPtr = DAG.getRegister(ARM::R13, MVT::i32);
135
136   static const unsigned int num_regs = 4;
137   static const unsigned regs[num_regs] = {
138     ARM::R0, ARM::R1, ARM::R2, ARM::R3
139   };
140
141   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
142   std::vector<SDOperand> MemOpChains;
143
144   for (unsigned i = 0; i != NumOps; ++i) {
145     SDOperand Arg = Op.getOperand(5+2*i);
146     assert(Arg.getValueType() == MVT::i32);
147     if (i < num_regs)
148       RegsToPass.push_back(std::make_pair(regs[i], Arg));
149     else {
150       unsigned ArgOffset = (i - num_regs) * 4;
151       SDOperand PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
152       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
153       MemOpChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
154                                           Arg, PtrOff, DAG.getSrcValue(NULL)));
155     }
156   }
157   if (!MemOpChains.empty())
158     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
159                         &MemOpChains[0], MemOpChains.size());
160
161   // Build a sequence of copy-to-reg nodes chained together with token chain
162   // and flag operands which copy the outgoing args into the appropriate regs.
163   SDOperand InFlag;
164   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
165     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
166                              InFlag);
167     InFlag = Chain.getValue(1);
168   }
169
170   std::vector<MVT::ValueType> NodeTys;
171   NodeTys.push_back(MVT::Other);   // Returns a chain
172   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
173
174   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
175   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
176   // node so that legalize doesn't hack it.
177   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
178     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), Callee.getValueType());
179
180   // If this is a direct call, pass the chain and the callee.
181   assert (Callee.Val);
182   std::vector<SDOperand> Ops;
183   Ops.push_back(Chain);
184   Ops.push_back(Callee);
185
186   // Add argument registers to the end of the list so that they are known live
187   // into the call.
188   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
189     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
190                                   RegsToPass[i].second.getValueType()));
191
192   unsigned CallOpc = ARMISD::CALL;
193   if (InFlag.Val)
194     Ops.push_back(InFlag);
195   Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
196   InFlag = Chain.getValue(1);
197
198   std::vector<SDOperand> ResultVals;
199   NodeTys.clear();
200
201   // If the call has results, copy the values out of the ret val registers.
202   switch (Op.Val->getValueType(0)) {
203   default: assert(0 && "Unexpected ret value!");
204   case MVT::Other:
205     break;
206   case MVT::i32:
207     Chain = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag).getValue(1);
208     ResultVals.push_back(Chain.getValue(0));
209     NodeTys.push_back(MVT::i32);
210   }
211
212   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
213                       DAG.getConstant(NumBytes, MVT::i32));
214   NodeTys.push_back(MVT::Other);
215
216   if (ResultVals.empty())
217     return Chain;
218
219   ResultVals.push_back(Chain);
220   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, &ResultVals[0],
221                               ResultVals.size());
222   return Res.getValue(Op.ResNo);
223 }
224
225 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
226   SDOperand Copy;
227   SDOperand Chain = Op.getOperand(0);
228   switch(Op.getNumOperands()) {
229   default:
230     assert(0 && "Do not know how to return this many arguments!");
231     abort();
232   case 1: {
233     SDOperand LR = DAG.getRegister(ARM::R14, MVT::i32);
234     return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Chain);
235   }
236   case 3:
237     Copy = DAG.getCopyToReg(Chain, ARM::R0, Op.getOperand(1), SDOperand());
238     if (DAG.getMachineFunction().liveout_empty())
239       DAG.getMachineFunction().addLiveOut(ARM::R0);
240     break;
241   }
242
243   //We must use RET_FLAG instead of BRIND because BRIND doesn't have a flag
244   return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
245 }
246
247 static SDOperand LowerFORMAL_ARGUMENT(SDOperand Op, SelectionDAG &DAG,
248                                       unsigned *vRegs,
249                                       unsigned ArgNo) {
250   MachineFunction &MF = DAG.getMachineFunction();
251   MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
252   assert (ObjectVT == MVT::i32);
253   SDOperand Root = Op.getOperand(0);
254   SSARegMap *RegMap = MF.getSSARegMap();
255
256   unsigned num_regs = 4;
257   static const unsigned REGS[] = {
258     ARM::R0, ARM::R1, ARM::R2, ARM::R3
259   };
260
261   if(ArgNo < num_regs) {
262     unsigned VReg = RegMap->createVirtualRegister(&ARM::IntRegsRegClass);
263     MF.addLiveIn(REGS[ArgNo], VReg);
264     vRegs[ArgNo] = VReg;
265     return DAG.getCopyFromReg(Root, VReg, MVT::i32);
266   } else {
267     // If the argument is actually used, emit a load from the right stack
268       // slot.
269     if (!Op.Val->hasNUsesOfValue(0, ArgNo)) {
270       unsigned ArgOffset = (ArgNo - num_regs) * 4;
271
272       MachineFrameInfo *MFI = MF.getFrameInfo();
273       unsigned ObjSize = MVT::getSizeInBits(ObjectVT)/8;
274       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
275       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
276       return DAG.getLoad(ObjectVT, Root, FIN,
277                          DAG.getSrcValue(NULL));
278     } else {
279       // Don't emit a dead load.
280       return DAG.getNode(ISD::UNDEF, ObjectVT);
281     }
282   }
283 }
284
285 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
286   MVT::ValueType PtrVT = Op.getValueType();
287   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
288   Constant *C = CP->get();
289   SDOperand CPI = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment());
290
291   return CPI;
292 }
293
294 static SDOperand LowerGlobalAddress(SDOperand Op,
295                                     SelectionDAG &DAG) {
296   GlobalValue  *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
297   int alignment = 2;
298   SDOperand CPAddr = DAG.getConstantPool(GV, MVT::i32, alignment);
299   return DAG.getLoad(MVT::i32, DAG.getEntryNode(), CPAddr,
300                      DAG.getSrcValue(NULL));
301 }
302
303 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
304                               unsigned VarArgsFrameIndex) {
305   // vastart just stores the address of the VarArgsFrameIndex slot into the
306   // memory location argument.
307   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
308   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
309   return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
310                      Op.getOperand(1), Op.getOperand(2));
311 }
312
313 static SDOperand LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG,
314                                        int &VarArgsFrameIndex) {
315   std::vector<SDOperand> ArgValues;
316   SDOperand Root = Op.getOperand(0);
317   unsigned VRegs[4];
318
319   unsigned NumArgs = Op.Val->getNumValues()-1;
320   for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo) {
321     SDOperand ArgVal = LowerFORMAL_ARGUMENT(Op, DAG, VRegs, ArgNo);
322
323     ArgValues.push_back(ArgVal);
324   }
325
326   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
327   if (isVarArg) {
328     MachineFunction &MF = DAG.getMachineFunction();
329     SSARegMap *RegMap = MF.getSSARegMap();
330     MachineFrameInfo *MFI = MF.getFrameInfo();
331     VarArgsFrameIndex = MFI->CreateFixedObject(MVT::getSizeInBits(MVT::i32)/8,
332                                                -16 + NumArgs * 4);
333
334
335     static const unsigned REGS[] = {
336       ARM::R0, ARM::R1, ARM::R2, ARM::R3
337     };
338     // If this function is vararg, store r0-r3 to their spots on the stack
339     // so that they may be loaded by deferencing the result of va_next.
340     SmallVector<SDOperand, 4> MemOps;
341     for (unsigned ArgNo = 0; ArgNo < 4; ++ArgNo) {
342       int ArgOffset = - (4 - ArgNo) * 4;
343       int FI = MFI->CreateFixedObject(MVT::getSizeInBits(MVT::i32)/8,
344                                       ArgOffset);
345       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
346
347       unsigned VReg;
348       if (ArgNo < NumArgs)
349         VReg = VRegs[ArgNo];
350       else
351         VReg = RegMap->createVirtualRegister(&ARM::IntRegsRegClass);
352       if (ArgNo >= NumArgs)
353         MF.addLiveIn(REGS[ArgNo], VReg);
354
355       SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
356       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
357                                     Val, FIN, DAG.getSrcValue(NULL));
358       MemOps.push_back(Store);
359     }
360     Root = DAG.getNode(ISD::TokenFactor, MVT::Other,&MemOps[0],MemOps.size());
361   }
362
363   ArgValues.push_back(Root);
364
365   // Return the new list of results.
366   std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
367                                     Op.Val->value_end());
368   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
369 }
370
371 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG) {
372   SDOperand LHS = Op.getOperand(0);
373   SDOperand RHS = Op.getOperand(1);
374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
375   SDOperand TrueVal = Op.getOperand(2);
376   SDOperand FalseVal = Op.getOperand(3);
377   SDOperand    ARMCC = DAG.getConstant(DAGCCToARMCC(CC), MVT::i32);
378
379   SDOperand Cmp = DAG.getNode(ARMISD::CMP, MVT::Flag, LHS, RHS);
380   return DAG.getNode(ARMISD::SELECT, MVT::i32, FalseVal, TrueVal, ARMCC, Cmp);
381 }
382
383 static SDOperand LowerBR_CC(SDOperand Op, SelectionDAG &DAG) {
384   SDOperand  Chain = Op.getOperand(0);
385   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
386   SDOperand    LHS = Op.getOperand(2);
387   SDOperand    RHS = Op.getOperand(3);
388   SDOperand   Dest = Op.getOperand(4);
389   SDOperand  ARMCC = DAG.getConstant(DAGCCToARMCC(CC), MVT::i32);
390
391   SDOperand Cmp = DAG.getNode(ARMISD::CMP, MVT::Flag, LHS, RHS);
392   return DAG.getNode(ARMISD::BR, MVT::Other, Chain, Dest, ARMCC, Cmp);
393 }
394
395 SDOperand ARMTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
396   switch (Op.getOpcode()) {
397   default:
398     assert(0 && "Should not custom lower this!");
399     abort();
400   case ISD::ConstantPool:
401     return LowerConstantPool(Op, DAG);
402   case ISD::GlobalAddress:
403     return LowerGlobalAddress(Op, DAG);
404   case ISD::FORMAL_ARGUMENTS:
405     return LowerFORMAL_ARGUMENTS(Op, DAG, VarArgsFrameIndex);
406   case ISD::CALL:
407     return LowerCALL(Op, DAG);
408   case ISD::RET:
409     return LowerRET(Op, DAG);
410   case ISD::SELECT_CC:
411     return LowerSELECT_CC(Op, DAG);
412   case ISD::BR_CC:
413     return LowerBR_CC(Op, DAG);
414   case ISD::VASTART:
415     return LowerVASTART(Op, DAG, VarArgsFrameIndex);
416   }
417 }
418
419 //===----------------------------------------------------------------------===//
420 // Instruction Selector Implementation
421 //===----------------------------------------------------------------------===//
422
423 //===--------------------------------------------------------------------===//
424 /// ARMDAGToDAGISel - ARM specific code to select ARM machine
425 /// instructions for SelectionDAG operations.
426 ///
427 namespace {
428 class ARMDAGToDAGISel : public SelectionDAGISel {
429   ARMTargetLowering Lowering;
430
431 public:
432   ARMDAGToDAGISel(TargetMachine &TM)
433     : SelectionDAGISel(Lowering), Lowering(TM) {
434   }
435
436   SDNode *Select(SDOperand Op);
437   virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
438   bool SelectAddrRegImm(SDOperand N, SDOperand &Offset, SDOperand &Base);
439
440   // Include the pieces autogenerated from the target description.
441 #include "ARMGenDAGISel.inc"
442 };
443
444 void ARMDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
445   DEBUG(BB->dump());
446
447   DAG.setRoot(SelectRoot(DAG.getRoot()));
448   DAG.RemoveDeadNodes();
449
450   ScheduleAndEmitDAG(DAG);
451 }
452
453 static bool isInt12Immediate(SDNode *N, short &Imm) {
454   if (N->getOpcode() != ISD::Constant)
455     return false;
456
457   int32_t t = cast<ConstantSDNode>(N)->getValue();
458   int max = 2<<12 - 1;
459   int min = -max;
460   if (t > min && t < max) {
461     Imm = t;
462     return true;
463   }
464   else
465     return false;
466 }
467
468 static bool isInt12Immediate(SDOperand Op, short &Imm) {
469   return isInt12Immediate(Op.Val, Imm);
470 }
471
472 //register plus/minus 12 bit offset
473 bool ARMDAGToDAGISel::SelectAddrRegImm(SDOperand N, SDOperand &Offset,
474                                     SDOperand &Base) {
475   if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(N)) {
476     Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
477     Offset = CurDAG->getTargetConstant(0, MVT::i32);
478     return true;
479   }
480   if (N.getOpcode() == ISD::ADD) {
481     short imm = 0;
482     if (isInt12Immediate(N.getOperand(1), imm)) {
483       Offset = CurDAG->getTargetConstant(imm, MVT::i32);
484       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
485         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
486       } else {
487         Base = N.getOperand(0);
488       }
489       return true; // [r+i]
490     }
491   }
492
493   Offset = CurDAG->getTargetConstant(0, MVT::i32);
494   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
495     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), N.getValueType());
496   }
497   else
498     Base = N;
499   return true;      //any address fits in a register
500 }
501
502 SDNode *ARMDAGToDAGISel::Select(SDOperand Op) {
503   SDNode *N = Op.Val;
504
505   switch (N->getOpcode()) {
506   default:
507     return SelectCode(Op);
508     break;
509   }
510   return NULL;
511 }
512
513 }  // end anonymous namespace
514
515 /// createARMISelDag - This pass converts a legalized DAG into a
516 /// ARM-specific DAG, ready for instruction scheduling.
517 ///
518 FunctionPass *llvm::createARMISelDag(TargetMachine &TM) {
519   return new ARMDAGToDAGISel(TM);
520 }