In TargetLowering::LowerCallTo, don't assert that
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
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 the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMRegisterInfo.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Instruction.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/ADT/VectorExtras.h"
36 #include "llvm/Support/MathExtras.h"
37 using namespace llvm;
38
39 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
40     : TargetLowering(TM), ARMPCLabelIndex(0) {
41   Subtarget = &TM.getSubtarget<ARMSubtarget>();
42
43   if (Subtarget->isTargetDarwin()) {
44     // Don't have these.
45     setLibcallName(RTLIB::UINTTOFP_I64_F32, NULL);
46     setLibcallName(RTLIB::UINTTOFP_I64_F64, NULL);
47
48     // Uses VFP for Thumb libfuncs if available.
49     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
50       // Single-precision floating-point arithmetic.
51       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
52       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
53       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
54       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
55
56       // Double-precision floating-point arithmetic.
57       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
58       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
59       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
60       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
61
62       // Single-precision comparisons.
63       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
64       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
65       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
66       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
67       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
68       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
69       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
70       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
71
72       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
73       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
74       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
75       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
76       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
77       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
78       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
79       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
80
81       // Double-precision comparisons.
82       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
83       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
84       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
85       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
86       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
87       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
88       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
89       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
90
91       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
92       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
93       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
94       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
95       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
96       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
97       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
98       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
99
100       // Floating-point to integer conversions.
101       // i64 conversions are done via library routines even when generating VFP
102       // instructions, so use the same ones.
103       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
104       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
105       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
106       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
107
108       // Conversions between floating types.
109       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
110       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
111
112       // Integer to floating-point conversions.
113       // i64 conversions are done via library routines even when generating VFP
114       // instructions, so use the same ones.
115       // FIXME: There appears to be some naming inconsistency in ARM libgcc: e.g.
116       // __floatunsidf vs. __floatunssidfvfp.
117       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
118       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
119       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
120       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
121     }
122   }
123
124   addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
125   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
126     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
127     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
128     
129     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
130   }
131   computeRegisterProperties();
132
133   // ARM does not have f32 extending load.
134   setLoadXAction(ISD::EXTLOAD, MVT::f32, Expand);
135
136   // ARM does not have i1 sign extending load.
137   setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
138
139   // ARM supports all 4 flavors of integer indexed load / store.
140   for (unsigned im = (unsigned)ISD::PRE_INC;
141        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
142     setIndexedLoadAction(im,  MVT::i1,  Legal);
143     setIndexedLoadAction(im,  MVT::i8,  Legal);
144     setIndexedLoadAction(im,  MVT::i16, Legal);
145     setIndexedLoadAction(im,  MVT::i32, Legal);
146     setIndexedStoreAction(im, MVT::i1,  Legal);
147     setIndexedStoreAction(im, MVT::i8,  Legal);
148     setIndexedStoreAction(im, MVT::i16, Legal);
149     setIndexedStoreAction(im, MVT::i32, Legal);
150   }
151
152   // i64 operation support.
153   if (Subtarget->isThumb()) {
154     setOperationAction(ISD::MUL,     MVT::i64, Expand);
155     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
156     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
157     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
158     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
159   } else {
160     setOperationAction(ISD::MUL,     MVT::i64, Expand);
161     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
162     if (!Subtarget->hasV6Ops())
163       setOperationAction(ISD::MULHS, MVT::i32, Expand);
164   }
165   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
166   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
167   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
168   setOperationAction(ISD::SRL,       MVT::i64, Custom);
169   setOperationAction(ISD::SRA,       MVT::i64, Custom);
170
171   // ARM does not have ROTL.
172   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
173   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
174   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
175   if (!Subtarget->hasV5TOps() || Subtarget->isThumb())
176     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
177
178   // Only ARMv6 has BSWAP.
179   if (!Subtarget->hasV6Ops())
180     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
181
182   // These are expanded into libcalls.
183   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
184   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
185   setOperationAction(ISD::SREM,  MVT::i32, Expand);
186   setOperationAction(ISD::UREM,  MVT::i32, Expand);
187   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
188   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
189   
190   // Support label based line numbers.
191   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
192   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
193
194   setOperationAction(ISD::RET,           MVT::Other, Custom);
195   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
196   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
197   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
198   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
199
200   // Expand mem operations genericly.
201   setOperationAction(ISD::MEMSET          , MVT::Other, Expand);
202   setOperationAction(ISD::MEMCPY          , MVT::Other, Custom);
203   setOperationAction(ISD::MEMMOVE         , MVT::Other, Expand);
204
205   // Use the default implementation.
206   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
207   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
208   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
209   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
210   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand); 
211   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
212   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
213
214   if (!Subtarget->hasV6Ops()) {
215     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
216     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
217   }
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
219
220   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb())
221     // Turn f64->i64 into FMRRD iff target supports vfp2.
222     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
223
224   // We want to custom lower some of our intrinsics.
225   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
226
227   setOperationAction(ISD::SETCC    , MVT::i32, Expand);
228   setOperationAction(ISD::SETCC    , MVT::f32, Expand);
229   setOperationAction(ISD::SETCC    , MVT::f64, Expand);
230   setOperationAction(ISD::SELECT   , MVT::i32, Expand);
231   setOperationAction(ISD::SELECT   , MVT::f32, Expand);
232   setOperationAction(ISD::SELECT   , MVT::f64, Expand);
233   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
234   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
235   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
236
237   setOperationAction(ISD::BRCOND   , MVT::Other, Expand);
238   setOperationAction(ISD::BR_CC    , MVT::i32,   Custom);
239   setOperationAction(ISD::BR_CC    , MVT::f32,   Custom);
240   setOperationAction(ISD::BR_CC    , MVT::f64,   Custom);
241   setOperationAction(ISD::BR_JT    , MVT::Other, Custom);
242
243   // We don't support sin/cos/fmod/copysign/pow
244   setOperationAction(ISD::FSIN     , MVT::f64, Expand);
245   setOperationAction(ISD::FSIN     , MVT::f32, Expand);
246   setOperationAction(ISD::FCOS     , MVT::f32, Expand);
247   setOperationAction(ISD::FCOS     , MVT::f64, Expand);
248   setOperationAction(ISD::FREM     , MVT::f64, Expand);
249   setOperationAction(ISD::FREM     , MVT::f32, Expand);
250   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
251   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
252   setOperationAction(ISD::FPOW     , MVT::f64, Expand);
253   setOperationAction(ISD::FPOW     , MVT::f32, Expand);
254   
255   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
258   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
259   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
260
261   // We have target-specific dag combine patterns for the following nodes:
262   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
263   
264   setStackPointerRegisterToSaveRestore(ARM::SP);
265   setSchedulingPreference(SchedulingForRegPressure);
266   setIfCvtBlockSizeLimit(Subtarget->isThumb() ? 0 : 10);
267   setIfCvtDupBlockSizeLimit(Subtarget->isThumb() ? 0 : 2);
268
269   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
270 }
271
272
273 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
274   switch (Opcode) {
275   default: return 0;
276   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
277   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
278   case ARMISD::CALL:          return "ARMISD::CALL";
279   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
280   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
281   case ARMISD::tCALL:         return "ARMISD::tCALL";
282   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
283   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
284   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
285   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
286   case ARMISD::CMP:           return "ARMISD::CMP";
287   case ARMISD::CMPNZ:         return "ARMISD::CMPNZ";
288   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
289   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
290   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
291   case ARMISD::CMOV:          return "ARMISD::CMOV";
292   case ARMISD::CNEG:          return "ARMISD::CNEG";
293     
294   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
295   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
296   case ARMISD::SITOF:         return "ARMISD::SITOF";
297   case ARMISD::UITOF:         return "ARMISD::UITOF";
298
299   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
300   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
301   case ARMISD::RRX:           return "ARMISD::RRX";
302       
303   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
304   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
305
306   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
307   }
308 }
309
310 //===----------------------------------------------------------------------===//
311 // Lowering Code
312 //===----------------------------------------------------------------------===//
313
314
315 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
316 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
317   switch (CC) {
318   default: assert(0 && "Unknown condition code!");
319   case ISD::SETNE:  return ARMCC::NE;
320   case ISD::SETEQ:  return ARMCC::EQ;
321   case ISD::SETGT:  return ARMCC::GT;
322   case ISD::SETGE:  return ARMCC::GE;
323   case ISD::SETLT:  return ARMCC::LT;
324   case ISD::SETLE:  return ARMCC::LE;
325   case ISD::SETUGT: return ARMCC::HI;
326   case ISD::SETUGE: return ARMCC::HS;
327   case ISD::SETULT: return ARMCC::LO;
328   case ISD::SETULE: return ARMCC::LS;
329   }
330 }
331
332 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
333 /// returns true if the operands should be inverted to form the proper
334 /// comparison.
335 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
336                         ARMCC::CondCodes &CondCode2) {
337   bool Invert = false;
338   CondCode2 = ARMCC::AL;
339   switch (CC) {
340   default: assert(0 && "Unknown FP condition!");
341   case ISD::SETEQ:
342   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
343   case ISD::SETGT:
344   case ISD::SETOGT: CondCode = ARMCC::GT; break;
345   case ISD::SETGE:
346   case ISD::SETOGE: CondCode = ARMCC::GE; break;
347   case ISD::SETOLT: CondCode = ARMCC::MI; break;
348   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
349   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
350   case ISD::SETO:   CondCode = ARMCC::VC; break;
351   case ISD::SETUO:  CondCode = ARMCC::VS; break;
352   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
353   case ISD::SETUGT: CondCode = ARMCC::HI; break;
354   case ISD::SETUGE: CondCode = ARMCC::PL; break;
355   case ISD::SETLT:
356   case ISD::SETULT: CondCode = ARMCC::LT; break;
357   case ISD::SETLE:
358   case ISD::SETULE: CondCode = ARMCC::LE; break;
359   case ISD::SETNE:
360   case ISD::SETUNE: CondCode = ARMCC::NE; break;
361   }
362   return Invert;
363 }
364
365 static void
366 HowToPassArgument(MVT::ValueType ObjectVT, unsigned NumGPRs,
367                   unsigned StackOffset, unsigned &NeededGPRs,
368                   unsigned &NeededStackSize, unsigned &GPRPad,
369                   unsigned &StackPad, unsigned Flags) {
370   NeededStackSize = 0;
371   NeededGPRs = 0;
372   StackPad = 0;
373   GPRPad = 0;
374   unsigned align = (Flags >> ISD::ParamFlags::OrigAlignmentOffs);
375   GPRPad = NumGPRs % ((align + 3)/4);
376   StackPad = StackOffset % align;
377   unsigned firstGPR = NumGPRs + GPRPad;
378   switch (ObjectVT) {
379   default: assert(0 && "Unhandled argument type!");
380   case MVT::i32:
381   case MVT::f32:
382     if (firstGPR < 4)
383       NeededGPRs = 1;
384     else
385       NeededStackSize = 4;
386     break;
387   case MVT::i64:
388   case MVT::f64:
389     if (firstGPR < 3)
390       NeededGPRs = 2;
391     else if (firstGPR == 3) {
392       NeededGPRs = 1;
393       NeededStackSize = 4;
394     } else
395       NeededStackSize = 8;
396   }
397 }
398
399 /// LowerCALL - Lowering a ISD::CALL node into a callseq_start <-
400 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
401 /// nodes.
402 SDOperand ARMTargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
403   MVT::ValueType RetVT= Op.Val->getValueType(0);
404   SDOperand Chain    = Op.getOperand(0);
405   unsigned CallConv  = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
406   assert((CallConv == CallingConv::C ||
407           CallConv == CallingConv::Fast) && "unknown calling convention");
408   SDOperand Callee   = Op.getOperand(4);
409   unsigned NumOps    = (Op.getNumOperands() - 5) / 2;
410   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
411   unsigned NumGPRs = 0;     // GPRs used for parameter passing.
412
413   // Count how many bytes are to be pushed on the stack.
414   unsigned NumBytes = 0;
415
416   // Add up all the space actually used.
417   for (unsigned i = 0; i < NumOps; ++i) {
418     unsigned ObjSize;
419     unsigned ObjGPRs;
420     unsigned StackPad;
421     unsigned GPRPad;
422     MVT::ValueType ObjectVT = Op.getOperand(5+2*i).getValueType();
423     unsigned Flags = Op.getConstantOperandVal(5+2*i+1);
424     HowToPassArgument(ObjectVT, NumGPRs, NumBytes, ObjGPRs, ObjSize,
425                       GPRPad, StackPad, Flags);
426     NumBytes += ObjSize + StackPad;
427     NumGPRs += ObjGPRs + GPRPad;
428   }
429
430   // Adjust the stack pointer for the new arguments...
431   // These operations are automatically eliminated by the prolog/epilog pass
432   Chain = DAG.getCALLSEQ_START(Chain,
433                                DAG.getConstant(NumBytes, MVT::i32));
434
435   SDOperand StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
436
437   static const unsigned GPRArgRegs[] = {
438     ARM::R0, ARM::R1, ARM::R2, ARM::R3
439   };
440
441   NumGPRs = 0;
442   std::vector<std::pair<unsigned, SDOperand> > RegsToPass;
443   std::vector<SDOperand> MemOpChains;
444   for (unsigned i = 0; i != NumOps; ++i) {
445     SDOperand Arg = Op.getOperand(5+2*i);
446     unsigned Flags = Op.getConstantOperandVal(5+2*i+1);
447     MVT::ValueType ArgVT = Arg.getValueType();
448
449     unsigned ObjSize;
450     unsigned ObjGPRs;
451     unsigned GPRPad;
452     unsigned StackPad;
453     HowToPassArgument(ArgVT, NumGPRs, ArgOffset, ObjGPRs,
454                       ObjSize, GPRPad, StackPad, Flags);
455     NumGPRs += GPRPad;
456     ArgOffset += StackPad;
457     if (ObjGPRs > 0) {
458       switch (ArgVT) {
459       default: assert(0 && "Unexpected ValueType for argument!");
460       case MVT::i32:
461         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Arg));
462         break;
463       case MVT::f32:
464         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs],
465                                  DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Arg)));
466         break;
467       case MVT::i64: {
468         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Arg,
469                                    DAG.getConstant(0, getPointerTy()));
470         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Arg,
471                                    DAG.getConstant(1, getPointerTy()));
472         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Lo));
473         if (ObjGPRs == 2)
474           RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs+1], Hi));
475         else {
476           SDOperand PtrOff= DAG.getConstant(ArgOffset, StackPtr.getValueType());
477           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
478           MemOpChains.push_back(DAG.getStore(Chain, Hi, PtrOff, NULL, 0));
479         }
480         break;
481       }
482       case MVT::f64: {
483         SDOperand Cvt = DAG.getNode(ARMISD::FMRRD,
484                                     DAG.getVTList(MVT::i32, MVT::i32),
485                                     &Arg, 1);
486         RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs], Cvt));
487         if (ObjGPRs == 2)
488           RegsToPass.push_back(std::make_pair(GPRArgRegs[NumGPRs+1],
489                                               Cvt.getValue(1)));
490         else {
491           SDOperand PtrOff= DAG.getConstant(ArgOffset, StackPtr.getValueType());
492           PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
493           MemOpChains.push_back(DAG.getStore(Chain, Cvt.getValue(1), PtrOff,
494                                              NULL, 0));
495         }
496         break;
497       }
498       }
499     } else {
500       assert(ObjSize != 0);
501       SDOperand PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
502       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
503       MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, NULL, 0));
504     }
505
506     NumGPRs += ObjGPRs;
507     ArgOffset += ObjSize;
508   }
509
510   if (!MemOpChains.empty())
511     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
512                         &MemOpChains[0], MemOpChains.size());
513
514   // Build a sequence of copy-to-reg nodes chained together with token chain
515   // and flag operands which copy the outgoing args into the appropriate regs.
516   SDOperand InFlag;
517   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
518     Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
519                              InFlag);
520     InFlag = Chain.getValue(1);
521   }
522
523   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
524   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
525   // node so that legalize doesn't hack it.
526   bool isDirect = false;
527   bool isARMFunc = false;
528   bool isLocalARMFunc = false;
529   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
530     GlobalValue *GV = G->getGlobal();
531     isDirect = true;
532     bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
533                   GV->hasLinkOnceLinkage());
534     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
535                    getTargetMachine().getRelocationModel() != Reloc::Static;
536     isARMFunc = !Subtarget->isThumb() || isStub;
537     // ARM call to a local ARM function is predicable.
538     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
539     // tBX takes a register source operand.
540     if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
541       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
542                                                            ARMCP::CPStub, 4);
543       SDOperand CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 2);
544       CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
545       Callee = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), CPAddr, NULL, 0); 
546       SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
547       Callee = DAG.getNode(ARMISD::PIC_ADD, getPointerTy(), Callee, PICLabel);
548    } else
549       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
550   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
551     isDirect = true;
552     bool isStub = Subtarget->isTargetDarwin() &&
553                   getTargetMachine().getRelocationModel() != Reloc::Static;
554     isARMFunc = !Subtarget->isThumb() || isStub;
555     // tBX takes a register source operand.
556     const char *Sym = S->getSymbol();
557     if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
558       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(Sym, ARMPCLabelIndex,
559                                                            ARMCP::CPStub, 4);
560       SDOperand CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 2);
561       CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
562       Callee = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), CPAddr, NULL, 0); 
563       SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
564       Callee = DAG.getNode(ARMISD::PIC_ADD, getPointerTy(), Callee, PICLabel);
565     } else
566       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
567   }
568
569   // FIXME: handle tail calls differently.
570   unsigned CallOpc;
571   if (Subtarget->isThumb()) {
572     if (!Subtarget->hasV5TOps() && (!isDirect || isARMFunc))
573       CallOpc = ARMISD::CALL_NOLINK;
574     else
575       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
576   } else {
577     CallOpc = (isDirect || Subtarget->hasV5TOps())
578       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
579       : ARMISD::CALL_NOLINK;
580   }
581   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb()) {
582     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
583     Chain = DAG.getCopyToReg(Chain, ARM::LR,
584                              DAG.getNode(ISD::UNDEF, MVT::i32), InFlag);
585     InFlag = Chain.getValue(1);
586   }
587
588   std::vector<MVT::ValueType> NodeTys;
589   NodeTys.push_back(MVT::Other);   // Returns a chain
590   NodeTys.push_back(MVT::Flag);    // Returns a flag for retval copy to use.
591
592   std::vector<SDOperand> Ops;
593   Ops.push_back(Chain);
594   Ops.push_back(Callee);
595
596   // Add argument registers to the end of the list so that they are known live
597   // into the call.
598   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
599     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
600                                   RegsToPass[i].second.getValueType()));
601
602   if (InFlag.Val)
603     Ops.push_back(InFlag);
604   Chain = DAG.getNode(CallOpc, NodeTys, &Ops[0], Ops.size());
605   InFlag = Chain.getValue(1);
606
607   Chain = DAG.getCALLSEQ_END(Chain,
608                              DAG.getConstant(NumBytes, MVT::i32),
609                              DAG.getConstant(0, MVT::i32),
610                              InFlag);
611   if (RetVT != MVT::Other)
612     InFlag = Chain.getValue(1);
613
614   std::vector<SDOperand> ResultVals;
615   NodeTys.clear();
616
617   // If the call has results, copy the values out of the ret val registers.
618   switch (RetVT) {
619   default: assert(0 && "Unexpected ret value!");
620   case MVT::Other:
621     break;
622   case MVT::i32:
623     Chain = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag).getValue(1);
624     ResultVals.push_back(Chain.getValue(0));
625     if (Op.Val->getValueType(1) == MVT::i32) {
626       // Returns a i64 value.
627       Chain = DAG.getCopyFromReg(Chain, ARM::R1, MVT::i32,
628                                  Chain.getValue(2)).getValue(1);
629       ResultVals.push_back(Chain.getValue(0));
630       NodeTys.push_back(MVT::i32);
631     }
632     NodeTys.push_back(MVT::i32);
633     break;
634   case MVT::f32:
635     Chain = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag).getValue(1);
636     ResultVals.push_back(DAG.getNode(ISD::BIT_CONVERT, MVT::f32,
637                                      Chain.getValue(0)));
638     NodeTys.push_back(MVT::f32);
639     break;
640   case MVT::f64: {
641     SDOperand Lo = DAG.getCopyFromReg(Chain, ARM::R0, MVT::i32, InFlag);
642     SDOperand Hi = DAG.getCopyFromReg(Lo, ARM::R1, MVT::i32, Lo.getValue(2));
643     ResultVals.push_back(DAG.getNode(ARMISD::FMDRR, MVT::f64, Lo, Hi));
644     NodeTys.push_back(MVT::f64);
645     break;
646   }
647   }
648
649   NodeTys.push_back(MVT::Other);
650
651   if (ResultVals.empty())
652     return Chain;
653
654   ResultVals.push_back(Chain);
655   SDOperand Res = DAG.getNode(ISD::MERGE_VALUES, NodeTys, &ResultVals[0],
656                               ResultVals.size());
657   return Res.getValue(Op.ResNo);
658 }
659
660 static SDOperand LowerRET(SDOperand Op, SelectionDAG &DAG) {
661   SDOperand Copy;
662   SDOperand Chain = Op.getOperand(0);
663   switch(Op.getNumOperands()) {
664   default:
665     assert(0 && "Do not know how to return this many arguments!");
666     abort();
667   case 1: {
668     SDOperand LR = DAG.getRegister(ARM::LR, MVT::i32);
669     return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Chain);
670   }
671   case 3:
672     Op = Op.getOperand(1);
673     if (Op.getValueType() == MVT::f32) {
674       Op = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
675     } else if (Op.getValueType() == MVT::f64) {
676       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
677       // available.
678       Op = DAG.getNode(ARMISD::FMRRD, DAG.getVTList(MVT::i32, MVT::i32), &Op,1);
679       SDOperand Sign = DAG.getConstant(0, MVT::i32);
680       return DAG.getNode(ISD::RET, MVT::Other, Chain, Op, Sign, 
681                          Op.getValue(1), Sign);
682     }
683     Copy = DAG.getCopyToReg(Chain, ARM::R0, Op, SDOperand());
684     if (DAG.getMachineFunction().getRegInfo().liveout_empty())
685       DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
686     break;
687   case 5:
688     Copy = DAG.getCopyToReg(Chain, ARM::R1, Op.getOperand(3), SDOperand());
689     Copy = DAG.getCopyToReg(Copy, ARM::R0, Op.getOperand(1), Copy.getValue(1));
690     // If we haven't noted the R0+R1 are live out, do so now.
691     if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
692       DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R0);
693       DAG.getMachineFunction().getRegInfo().addLiveOut(ARM::R1);
694     }
695     break;
696   }
697
698   //We must use RET_FLAG instead of BRIND because BRIND doesn't have a flag
699   return DAG.getNode(ARMISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
700 }
701
702 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as 
703 // their target countpart wrapped in the ARMISD::Wrapper node. Suppose N is
704 // one of the above mentioned nodes. It has to be wrapped because otherwise
705 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
706 // be used to form addressing mode. These wrapped nodes will be selected
707 // into MOVi.
708 static SDOperand LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
709   MVT::ValueType PtrVT = Op.getValueType();
710   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
711   SDOperand Res;
712   if (CP->isMachineConstantPoolEntry())
713     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
714                                     CP->getAlignment());
715   else
716     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
717                                     CP->getAlignment());
718   return DAG.getNode(ARMISD::Wrapper, MVT::i32, Res);
719 }
720
721 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
722 SDOperand
723 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
724                                                  SelectionDAG &DAG) {
725   MVT::ValueType PtrVT = getPointerTy();
726   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
727   ARMConstantPoolValue *CPV =
728     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
729                              PCAdj, "tlsgd", true);
730   SDOperand Argument = DAG.getTargetConstantPool(CPV, PtrVT, 2);
731   Argument = DAG.getNode(ARMISD::Wrapper, MVT::i32, Argument);
732   Argument = DAG.getLoad(PtrVT, DAG.getEntryNode(), Argument, NULL, 0);
733   SDOperand Chain = Argument.getValue(1);
734
735   SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
736   Argument = DAG.getNode(ARMISD::PIC_ADD, PtrVT, Argument, PICLabel);
737
738   // call __tls_get_addr.
739   ArgListTy Args;
740   ArgListEntry Entry;
741   Entry.Node = Argument;
742   Entry.Ty = (const Type *) Type::Int32Ty;
743   Args.push_back(Entry);
744   std::pair<SDOperand, SDOperand> CallResult =
745     LowerCallTo(Chain, (const Type *) Type::Int32Ty, false, false, false,
746                 CallingConv::C, false,
747                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG);
748   return CallResult.first;
749 }
750
751 // Lower ISD::GlobalTLSAddress using the "initial exec" or
752 // "local exec" model.
753 SDOperand
754 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
755                                             SelectionDAG &DAG) {
756   GlobalValue *GV = GA->getGlobal();
757   SDOperand Offset;
758   SDOperand Chain = DAG.getEntryNode();
759   MVT::ValueType PtrVT = getPointerTy();
760   // Get the Thread Pointer
761   SDOperand ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, PtrVT);
762
763   if (GV->isDeclaration()){
764     // initial exec model
765     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
766     ARMConstantPoolValue *CPV =
767       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
768                                PCAdj, "gottpoff", true);
769     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 2);
770     Offset = DAG.getNode(ARMISD::Wrapper, MVT::i32, Offset);
771     Offset = DAG.getLoad(PtrVT, Chain, Offset, NULL, 0);
772     Chain = Offset.getValue(1);
773
774     SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
775     Offset = DAG.getNode(ARMISD::PIC_ADD, PtrVT, Offset, PICLabel);
776
777     Offset = DAG.getLoad(PtrVT, Chain, Offset, NULL, 0);
778   } else {
779     // local exec model
780     ARMConstantPoolValue *CPV =
781       new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
782     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 2);
783     Offset = DAG.getNode(ARMISD::Wrapper, MVT::i32, Offset);
784     Offset = DAG.getLoad(PtrVT, Chain, Offset, NULL, 0);
785   }
786
787   // The address of the thread local variable is the add of the thread
788   // pointer with the offset of the variable.
789   return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
790 }
791
792 SDOperand
793 ARMTargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
794   // TODO: implement the "local dynamic" model
795   assert(Subtarget->isTargetELF() &&
796          "TLS not implemented for non-ELF targets");
797   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
798   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
799   // otherwise use the "Local Exec" TLS Model
800   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
801     return LowerToTLSGeneralDynamicModel(GA, DAG);
802   else
803     return LowerToTLSExecModels(GA, DAG);
804 }
805
806 SDOperand ARMTargetLowering::LowerGlobalAddressELF(SDOperand Op,
807                                                    SelectionDAG &DAG) {
808   MVT::ValueType PtrVT = getPointerTy();
809   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
810   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
811   if (RelocM == Reloc::PIC_) {
812     bool UseGOTOFF = GV->hasInternalLinkage() || GV->hasHiddenVisibility();
813     ARMConstantPoolValue *CPV =
814       new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
815     SDOperand CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 2);
816     CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
817     SDOperand Result = DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
818     SDOperand Chain = Result.getValue(1);
819     SDOperand GOT = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PtrVT);
820     Result = DAG.getNode(ISD::ADD, PtrVT, Result, GOT);
821     if (!UseGOTOFF)
822       Result = DAG.getLoad(PtrVT, Chain, Result, NULL, 0);
823     return Result;
824   } else {
825     SDOperand CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 2);
826     CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
827     return DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
828   }
829 }
830
831 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
832 /// even in non-static mode.
833 static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
834   return RelocM != Reloc::Static &&
835     (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage() ||
836      (GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode()));
837 }
838
839 SDOperand ARMTargetLowering::LowerGlobalAddressDarwin(SDOperand Op,
840                                                       SelectionDAG &DAG) {
841   MVT::ValueType PtrVT = getPointerTy();
842   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
843   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
844   bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
845   SDOperand CPAddr;
846   if (RelocM == Reloc::Static)
847     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 2);
848   else {
849     unsigned PCAdj = (RelocM != Reloc::PIC_)
850       ? 0 : (Subtarget->isThumb() ? 4 : 8);
851     ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
852       : ARMCP::CPValue;
853     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
854                                                          Kind, PCAdj);
855     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 2);
856   }
857   CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
858
859   SDOperand Result = DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
860   SDOperand Chain = Result.getValue(1);
861
862   if (RelocM == Reloc::PIC_) {
863     SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
864     Result = DAG.getNode(ARMISD::PIC_ADD, PtrVT, Result, PICLabel);
865   }
866   if (IsIndirect)
867     Result = DAG.getLoad(PtrVT, Chain, Result, NULL, 0);
868
869   return Result;
870 }
871
872 SDOperand ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDOperand Op,
873                                                       SelectionDAG &DAG){
874   assert(Subtarget->isTargetELF() &&
875          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
876   MVT::ValueType PtrVT = getPointerTy();
877   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
878   ARMConstantPoolValue *CPV = new ARMConstantPoolValue("_GLOBAL_OFFSET_TABLE_",
879                                                        ARMPCLabelIndex,
880                                                        ARMCP::CPValue, PCAdj);
881   SDOperand CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 2);
882   CPAddr = DAG.getNode(ARMISD::Wrapper, MVT::i32, CPAddr);
883   SDOperand Result = DAG.getLoad(PtrVT, DAG.getEntryNode(), CPAddr, NULL, 0);
884   SDOperand PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
885   return DAG.getNode(ARMISD::PIC_ADD, PtrVT, Result, PICLabel);
886 }
887
888 static SDOperand LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
889   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
890   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
891   switch (IntNo) {
892   default: return SDOperand();    // Don't custom lower most intrinsics.
893   case Intrinsic::arm_thread_pointer:
894       return DAG.getNode(ARMISD::THREAD_POINTER, PtrVT);
895   }
896 }
897
898 static SDOperand LowerVASTART(SDOperand Op, SelectionDAG &DAG,
899                               unsigned VarArgsFrameIndex) {
900   // vastart just stores the address of the VarArgsFrameIndex slot into the
901   // memory location argument.
902   MVT::ValueType PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
903   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
904   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
905   return DAG.getStore(Op.getOperand(0), FR, Op.getOperand(1), SV, 0);
906 }
907
908 static SDOperand LowerFORMAL_ARGUMENT(SDOperand Op, SelectionDAG &DAG,
909                                       unsigned ArgNo, unsigned &NumGPRs,
910                                       unsigned &ArgOffset) {
911   MachineFunction &MF = DAG.getMachineFunction();
912   MVT::ValueType ObjectVT = Op.getValue(ArgNo).getValueType();
913   SDOperand Root = Op.getOperand(0);
914   std::vector<SDOperand> ArgValues;
915   MachineRegisterInfo &RegInfo = MF.getRegInfo();
916
917   static const unsigned GPRArgRegs[] = {
918     ARM::R0, ARM::R1, ARM::R2, ARM::R3
919   };
920
921   unsigned ObjSize;
922   unsigned ObjGPRs;
923   unsigned GPRPad;
924   unsigned StackPad;
925   unsigned Flags = Op.getConstantOperandVal(ArgNo + 3);
926   HowToPassArgument(ObjectVT, NumGPRs, ArgOffset, ObjGPRs,
927                     ObjSize, GPRPad, StackPad, Flags);
928   NumGPRs += GPRPad;
929   ArgOffset += StackPad;
930
931   SDOperand ArgValue;
932   if (ObjGPRs == 1) {
933     unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
934     RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
935     ArgValue = DAG.getCopyFromReg(Root, VReg, MVT::i32);
936     if (ObjectVT == MVT::f32)
937       ArgValue = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, ArgValue);
938   } else if (ObjGPRs == 2) {
939     unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
940     RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
941     ArgValue = DAG.getCopyFromReg(Root, VReg, MVT::i32);
942
943     VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
944     RegInfo.addLiveIn(GPRArgRegs[NumGPRs+1], VReg);
945     SDOperand ArgValue2 = DAG.getCopyFromReg(Root, VReg, MVT::i32);
946
947     assert(ObjectVT != MVT::i64 && "i64 should already be lowered");
948     ArgValue = DAG.getNode(ARMISD::FMDRR, MVT::f64, ArgValue, ArgValue2);
949   }
950   NumGPRs += ObjGPRs;
951
952   if (ObjSize) {
953     MachineFrameInfo *MFI = MF.getFrameInfo();
954     int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
955     SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
956     if (ObjGPRs == 0)
957       ArgValue = DAG.getLoad(ObjectVT, Root, FIN, NULL, 0);
958     else {
959       SDOperand ArgValue2 = DAG.getLoad(MVT::i32, Root, FIN, NULL, 0);
960       assert(ObjectVT != MVT::i64 && "i64 should already be lowered");
961       ArgValue = DAG.getNode(ARMISD::FMDRR, MVT::f64, ArgValue, ArgValue2);
962     }
963
964     ArgOffset += ObjSize;   // Move on to the next argument.
965   }
966
967   return ArgValue;
968 }
969
970 SDOperand
971 ARMTargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
972   std::vector<SDOperand> ArgValues;
973   SDOperand Root = Op.getOperand(0);
974   unsigned ArgOffset = 0;   // Frame mechanisms handle retaddr slot
975   unsigned NumGPRs = 0;     // GPRs used for parameter passing.
976
977   unsigned NumArgs = Op.Val->getNumValues()-1;
978   for (unsigned ArgNo = 0; ArgNo < NumArgs; ++ArgNo)
979     ArgValues.push_back(LowerFORMAL_ARGUMENT(Op, DAG, ArgNo,
980                                              NumGPRs, ArgOffset));
981
982   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
983   if (isVarArg) {
984     static const unsigned GPRArgRegs[] = {
985       ARM::R0, ARM::R1, ARM::R2, ARM::R3
986     };
987
988     MachineFunction &MF = DAG.getMachineFunction();
989     MachineRegisterInfo &RegInfo = MF.getRegInfo();
990     MachineFrameInfo *MFI = MF.getFrameInfo();
991     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
992     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
993     unsigned VARegSize = (4 - NumGPRs) * 4;
994     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
995     if (VARegSaveSize) {
996       // If this function is vararg, store any remaining integer argument regs
997       // to their spots on the stack so that they may be loaded by deferencing
998       // the result of va_next.
999       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1000       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1001                                                  VARegSaveSize - VARegSize);
1002       SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1003
1004       SmallVector<SDOperand, 4> MemOps;
1005       for (; NumGPRs < 4; ++NumGPRs) {
1006         unsigned VReg = RegInfo.createVirtualRegister(&ARM::GPRRegClass);
1007         RegInfo.addLiveIn(GPRArgRegs[NumGPRs], VReg);
1008         SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i32);
1009         SDOperand Store = DAG.getStore(Val.getValue(1), Val, FIN, NULL, 0);
1010         MemOps.push_back(Store);
1011         FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1012                           DAG.getConstant(4, getPointerTy()));
1013       }
1014       if (!MemOps.empty())
1015         Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1016                            &MemOps[0], MemOps.size());
1017     } else
1018       // This will point to the next argument passed via stack.
1019       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1020   }
1021
1022   ArgValues.push_back(Root);
1023
1024   // Return the new list of results.
1025   std::vector<MVT::ValueType> RetVT(Op.Val->value_begin(),
1026                                     Op.Val->value_end());
1027   return DAG.getNode(ISD::MERGE_VALUES, RetVT, &ArgValues[0], ArgValues.size());
1028 }
1029
1030 /// isFloatingPointZero - Return true if this is +0.0.
1031 static bool isFloatingPointZero(SDOperand Op) {
1032   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1033     return CFP->getValueAPF().isPosZero();
1034   else if (ISD::isEXTLoad(Op.Val) || ISD::isNON_EXTLoad(Op.Val)) {
1035     // Maybe this has already been legalized into the constant pool?
1036     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1037       SDOperand WrapperOp = Op.getOperand(1).getOperand(0);
1038       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1039         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1040           return CFP->getValueAPF().isPosZero();
1041     }
1042   }
1043   return false;
1044 }
1045
1046 static bool isLegalCmpImmediate(unsigned C, bool isThumb) {
1047   return ( isThumb && (C & ~255U) == 0) ||
1048          (!isThumb && ARM_AM::getSOImmVal(C) != -1);
1049 }
1050
1051 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1052 /// the given operands.
1053 static SDOperand getARMCmp(SDOperand LHS, SDOperand RHS, ISD::CondCode CC,
1054                            SDOperand &ARMCC, SelectionDAG &DAG, bool isThumb) {
1055   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.Val)) {
1056     unsigned C = RHSC->getValue();
1057     if (!isLegalCmpImmediate(C, isThumb)) {
1058       // Constant does not fit, try adjusting it by one?
1059       switch (CC) {
1060       default: break;
1061       case ISD::SETLT:
1062       case ISD::SETGE:
1063         if (isLegalCmpImmediate(C-1, isThumb)) {
1064           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1065           RHS = DAG.getConstant(C-1, MVT::i32);
1066         }
1067         break;
1068       case ISD::SETULT:
1069       case ISD::SETUGE:
1070         if (C > 0 && isLegalCmpImmediate(C-1, isThumb)) {
1071           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1072           RHS = DAG.getConstant(C-1, MVT::i32);
1073         }
1074         break;
1075       case ISD::SETLE:
1076       case ISD::SETGT:
1077         if (isLegalCmpImmediate(C+1, isThumb)) {
1078           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1079           RHS = DAG.getConstant(C+1, MVT::i32);
1080         }
1081         break;
1082       case ISD::SETULE:
1083       case ISD::SETUGT:
1084         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb)) {
1085           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1086           RHS = DAG.getConstant(C+1, MVT::i32);
1087         }
1088         break;
1089       }
1090     }
1091   }
1092
1093   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1094   ARMISD::NodeType CompareType;
1095   switch (CondCode) {
1096   default:
1097     CompareType = ARMISD::CMP;
1098     break;
1099   case ARMCC::EQ:
1100   case ARMCC::NE:
1101   case ARMCC::MI:
1102   case ARMCC::PL:
1103     // Uses only N and Z Flags
1104     CompareType = ARMISD::CMPNZ;
1105     break;
1106   }
1107   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1108   return DAG.getNode(CompareType, MVT::Flag, LHS, RHS);
1109 }
1110
1111 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1112 static SDOperand getVFPCmp(SDOperand LHS, SDOperand RHS, SelectionDAG &DAG) {
1113   SDOperand Cmp;
1114   if (!isFloatingPointZero(RHS))
1115     Cmp = DAG.getNode(ARMISD::CMPFP, MVT::Flag, LHS, RHS);
1116   else
1117     Cmp = DAG.getNode(ARMISD::CMPFPw0, MVT::Flag, LHS);
1118   return DAG.getNode(ARMISD::FMSTAT, MVT::Flag, Cmp);
1119 }
1120
1121 static SDOperand LowerSELECT_CC(SDOperand Op, SelectionDAG &DAG,
1122                                 const ARMSubtarget *ST) {
1123   MVT::ValueType VT = Op.getValueType();
1124   SDOperand LHS = Op.getOperand(0);
1125   SDOperand RHS = Op.getOperand(1);
1126   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1127   SDOperand TrueVal = Op.getOperand(2);
1128   SDOperand FalseVal = Op.getOperand(3);
1129
1130   if (LHS.getValueType() == MVT::i32) {
1131     SDOperand ARMCC;
1132     SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1133     SDOperand Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb());
1134     return DAG.getNode(ARMISD::CMOV, VT, FalseVal, TrueVal, ARMCC, CCR, Cmp);
1135   }
1136
1137   ARMCC::CondCodes CondCode, CondCode2;
1138   if (FPCCToARMCC(CC, CondCode, CondCode2))
1139     std::swap(TrueVal, FalseVal);
1140
1141   SDOperand ARMCC = DAG.getConstant(CondCode, MVT::i32);
1142   SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1143   SDOperand Cmp = getVFPCmp(LHS, RHS, DAG);
1144   SDOperand Result = DAG.getNode(ARMISD::CMOV, VT, FalseVal, TrueVal,
1145                                  ARMCC, CCR, Cmp);
1146   if (CondCode2 != ARMCC::AL) {
1147     SDOperand ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1148     // FIXME: Needs another CMP because flag can have but one use.
1149     SDOperand Cmp2 = getVFPCmp(LHS, RHS, DAG);
1150     Result = DAG.getNode(ARMISD::CMOV, VT, Result, TrueVal, ARMCC2, CCR, Cmp2);
1151   }
1152   return Result;
1153 }
1154
1155 static SDOperand LowerBR_CC(SDOperand Op, SelectionDAG &DAG,
1156                             const ARMSubtarget *ST) {
1157   SDOperand  Chain = Op.getOperand(0);
1158   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1159   SDOperand    LHS = Op.getOperand(2);
1160   SDOperand    RHS = Op.getOperand(3);
1161   SDOperand   Dest = Op.getOperand(4);
1162
1163   if (LHS.getValueType() == MVT::i32) {
1164     SDOperand ARMCC;
1165     SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1166     SDOperand Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb());
1167     return DAG.getNode(ARMISD::BRCOND, MVT::Other, Chain, Dest, ARMCC, CCR,Cmp);
1168   }
1169
1170   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1171   ARMCC::CondCodes CondCode, CondCode2;
1172   if (FPCCToARMCC(CC, CondCode, CondCode2))
1173     // Swap the LHS/RHS of the comparison if needed.
1174     std::swap(LHS, RHS);
1175   
1176   SDOperand Cmp = getVFPCmp(LHS, RHS, DAG);
1177   SDOperand ARMCC = DAG.getConstant(CondCode, MVT::i32);
1178   SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1179   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1180   SDOperand Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1181   SDOperand Res = DAG.getNode(ARMISD::BRCOND, VTList, Ops, 5);
1182   if (CondCode2 != ARMCC::AL) {
1183     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1184     SDOperand Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1185     Res = DAG.getNode(ARMISD::BRCOND, VTList, Ops, 5);
1186   }
1187   return Res;
1188 }
1189
1190 SDOperand ARMTargetLowering::LowerBR_JT(SDOperand Op, SelectionDAG &DAG) {
1191   SDOperand Chain = Op.getOperand(0);
1192   SDOperand Table = Op.getOperand(1);
1193   SDOperand Index = Op.getOperand(2);
1194
1195   MVT::ValueType PTy = getPointerTy();
1196   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1197   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1198   SDOperand UId =  DAG.getConstant(AFI->createJumpTableUId(), PTy);
1199   SDOperand JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1200   Table = DAG.getNode(ARMISD::WrapperJT, MVT::i32, JTI, UId);
1201   Index = DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(4, PTy));
1202   SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
1203   bool isPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1204   Addr = DAG.getLoad(isPIC ? (MVT::ValueType)MVT::i32 : PTy,
1205                      Chain, Addr, NULL, 0);
1206   Chain = Addr.getValue(1);
1207   if (isPIC)
1208     Addr = DAG.getNode(ISD::ADD, PTy, Addr, Table);
1209   return DAG.getNode(ARMISD::BR_JT, MVT::Other, Chain, Addr, JTI, UId);
1210 }
1211
1212 static SDOperand LowerFP_TO_INT(SDOperand Op, SelectionDAG &DAG) {
1213   unsigned Opc =
1214     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1215   Op = DAG.getNode(Opc, MVT::f32, Op.getOperand(0));
1216   return DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
1217 }
1218
1219 static SDOperand LowerINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
1220   MVT::ValueType VT = Op.getValueType();
1221   unsigned Opc =
1222     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1223
1224   Op = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Op.getOperand(0));
1225   return DAG.getNode(Opc, VT, Op);
1226 }
1227
1228 static SDOperand LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
1229   // Implement fcopysign with a fabs and a conditional fneg.
1230   SDOperand Tmp0 = Op.getOperand(0);
1231   SDOperand Tmp1 = Op.getOperand(1);
1232   MVT::ValueType VT = Op.getValueType();
1233   MVT::ValueType SrcVT = Tmp1.getValueType();
1234   SDOperand AbsVal = DAG.getNode(ISD::FABS, VT, Tmp0);
1235   SDOperand Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG);
1236   SDOperand ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1237   SDOperand CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1238   return DAG.getNode(ARMISD::CNEG, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1239 }
1240
1241 SDOperand ARMTargetLowering::LowerMEMCPYInline(SDOperand Chain,
1242                                                SDOperand Dest,
1243                                                SDOperand Source,
1244                                                unsigned Size,
1245                                                unsigned Align,
1246                                                SelectionDAG &DAG) {
1247   // Do repeated 4-byte loads and stores. To be improved.
1248   assert((Align & 3) == 0 && "Expected 4-byte aligned addresses!");
1249   unsigned BytesLeft = Size & 3;
1250   unsigned NumMemOps = Size >> 2;
1251   unsigned EmittedNumMemOps = 0;
1252   unsigned SrcOff = 0, DstOff = 0;
1253   MVT::ValueType VT = MVT::i32;
1254   unsigned VTSize = 4;
1255   unsigned i = 0;
1256   const unsigned MAX_LOADS_IN_LDM = 6;
1257   SDOperand TFOps[MAX_LOADS_IN_LDM];
1258   SDOperand Loads[MAX_LOADS_IN_LDM];
1259
1260   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1261   // same number of stores.  The loads and stores will get combined into
1262   // ldm/stm later on.
1263   while (EmittedNumMemOps < NumMemOps) {
1264     for (i = 0;
1265          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1266       Loads[i] = DAG.getLoad(VT, Chain,
1267                              DAG.getNode(ISD::ADD, MVT::i32, Source,
1268                                          DAG.getConstant(SrcOff, MVT::i32)),
1269                              NULL, 0);
1270       TFOps[i] = Loads[i].getValue(1);
1271       SrcOff += VTSize;
1272     }
1273     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1274
1275     for (i = 0;
1276          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1277       TFOps[i] = DAG.getStore(Chain, Loads[i],
1278                            DAG.getNode(ISD::ADD, MVT::i32, Dest, 
1279                                        DAG.getConstant(DstOff, MVT::i32)),
1280                            NULL, 0);
1281       DstOff += VTSize;
1282     }
1283     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1284
1285     EmittedNumMemOps += i;
1286   }
1287
1288   if (BytesLeft == 0) 
1289     return Chain;
1290
1291   // Issue loads / stores for the trailing (1 - 3) bytes.
1292   unsigned BytesLeftSave = BytesLeft;
1293   i = 0;
1294   while (BytesLeft) {
1295     if (BytesLeft >= 2) {
1296       VT = MVT::i16;
1297       VTSize = 2;
1298     } else {
1299       VT = MVT::i8;
1300       VTSize = 1;
1301     }
1302
1303     Loads[i] = DAG.getLoad(VT, Chain,
1304                            DAG.getNode(ISD::ADD, MVT::i32, Source,
1305                                        DAG.getConstant(SrcOff, MVT::i32)),
1306                            NULL, 0);
1307     TFOps[i] = Loads[i].getValue(1);
1308     ++i;
1309     SrcOff += VTSize;
1310     BytesLeft -= VTSize;
1311   }
1312   Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1313
1314   i = 0;
1315   BytesLeft = BytesLeftSave;
1316   while (BytesLeft) {
1317     if (BytesLeft >= 2) {
1318       VT = MVT::i16;
1319       VTSize = 2;
1320     } else {
1321       VT = MVT::i8;
1322       VTSize = 1;
1323     }
1324
1325     TFOps[i] = DAG.getStore(Chain, Loads[i],
1326                             DAG.getNode(ISD::ADD, MVT::i32, Dest, 
1327                                         DAG.getConstant(DstOff, MVT::i32)),
1328                             NULL, 0);
1329     ++i;
1330     DstOff += VTSize;
1331     BytesLeft -= VTSize;
1332   }
1333   return DAG.getNode(ISD::TokenFactor, MVT::Other, &TFOps[0], i);
1334 }
1335
1336 static SDNode *ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1337   // Turn f64->i64 into FMRRD.
1338   assert(N->getValueType(0) == MVT::i64 &&
1339          N->getOperand(0).getValueType() == MVT::f64);
1340   
1341   SDOperand Op = N->getOperand(0);
1342   SDOperand Cvt = DAG.getNode(ARMISD::FMRRD, DAG.getVTList(MVT::i32, MVT::i32),
1343                               &Op, 1);
1344   
1345   // Merge the pieces into a single i64 value.
1346   return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Cvt, Cvt.getValue(1)).Val;
1347 }
1348
1349 static SDNode *ExpandSRx(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST) {
1350   assert(N->getValueType(0) == MVT::i64 &&
1351          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
1352          "Unknown shift to lower!");
1353   
1354   // We only lower SRA, SRL of 1 here, all others use generic lowering.
1355   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
1356       cast<ConstantSDNode>(N->getOperand(1))->getValue() != 1)
1357     return 0;
1358   
1359   // If we are in thumb mode, we don't have RRX.
1360   if (ST->isThumb()) return 0;
1361   
1362   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
1363   SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
1364                              DAG.getConstant(0, MVT::i32));
1365   SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, N->getOperand(0),
1366                              DAG.getConstant(1, MVT::i32));
1367   
1368   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
1369   // captures the result into a carry flag.
1370   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
1371   Hi = DAG.getNode(Opc, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
1372   
1373   // The low part is an ARMISD::RRX operand, which shifts the carry in.
1374   Lo = DAG.getNode(ARMISD::RRX, MVT::i32, Lo, Hi.getValue(1));
1375   
1376   // Merge the pieces into a single i64 value.
1377  return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Lo, Hi).Val;
1378 }
1379
1380
1381 SDOperand ARMTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1382   switch (Op.getOpcode()) {
1383   default: assert(0 && "Don't know how to custom lower this!"); abort();
1384   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
1385   case ISD::GlobalAddress:
1386     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
1387       LowerGlobalAddressELF(Op, DAG);
1388   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
1389   case ISD::CALL:          return LowerCALL(Op, DAG);
1390   case ISD::RET:           return LowerRET(Op, DAG);
1391   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
1392   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
1393   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
1394   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
1395   case ISD::SINT_TO_FP:
1396   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
1397   case ISD::FP_TO_SINT:
1398   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
1399   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
1400   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
1401   case ISD::RETURNADDR:    break;
1402   case ISD::FRAMEADDR:     break;
1403   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
1404   case ISD::MEMCPY:        return LowerMEMCPY(Op, DAG);
1405   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1406       
1407       
1408   // FIXME: Remove these when LegalizeDAGTypes lands.
1409   case ISD::BIT_CONVERT:   return SDOperand(ExpandBIT_CONVERT(Op.Val, DAG), 0);
1410   case ISD::SRL:
1411   case ISD::SRA:           return SDOperand(ExpandSRx(Op.Val, DAG,Subtarget),0);
1412   }
1413   return SDOperand();
1414 }
1415
1416
1417 /// ExpandOperationResult - Provide custom lowering hooks for expanding
1418 /// operations.
1419 SDNode *ARMTargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
1420   switch (N->getOpcode()) {
1421   default: assert(0 && "Don't know how to custom expand this!"); abort();
1422   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(N, DAG);
1423   case ISD::SRL:
1424   case ISD::SRA:           return ExpandSRx(N, DAG, Subtarget);
1425   }
1426 }
1427   
1428
1429 //===----------------------------------------------------------------------===//
1430 //                           ARM Scheduler Hooks
1431 //===----------------------------------------------------------------------===//
1432
1433 MachineBasicBlock *
1434 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1435                                            MachineBasicBlock *BB) {
1436   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1437   switch (MI->getOpcode()) {
1438   default: assert(false && "Unexpected instr type to insert");
1439   case ARM::tMOVCCr: {
1440     // To "insert" a SELECT_CC instruction, we actually have to insert the
1441     // diamond control-flow pattern.  The incoming instruction knows the
1442     // destination vreg to set, the condition code register to branch on, the
1443     // true/false values to select between, and a branch opcode to use.
1444     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1445     ilist<MachineBasicBlock>::iterator It = BB;
1446     ++It;
1447
1448     //  thisMBB:
1449     //  ...
1450     //   TrueVal = ...
1451     //   cmpTY ccX, r1, r2
1452     //   bCC copy1MBB
1453     //   fallthrough --> copy0MBB
1454     MachineBasicBlock *thisMBB  = BB;
1455     MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
1456     MachineBasicBlock *sinkMBB  = new MachineBasicBlock(LLVM_BB);
1457     BuildMI(BB, TII->get(ARM::tBcc)).addMBB(sinkMBB)
1458       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
1459     MachineFunction *F = BB->getParent();
1460     F->getBasicBlockList().insert(It, copy0MBB);
1461     F->getBasicBlockList().insert(It, sinkMBB);
1462     // Update machine-CFG edges by first adding all successors of the current
1463     // block to the new block which will contain the Phi node for the select.
1464     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
1465         e = BB->succ_end(); i != e; ++i)
1466       sinkMBB->addSuccessor(*i);
1467     // Next, remove all successors of the current block, and add the true
1468     // and fallthrough blocks as its successors.
1469     while(!BB->succ_empty())
1470       BB->removeSuccessor(BB->succ_begin());
1471     BB->addSuccessor(copy0MBB);
1472     BB->addSuccessor(sinkMBB);
1473
1474     //  copy0MBB:
1475     //   %FalseValue = ...
1476     //   # fallthrough to sinkMBB
1477     BB = copy0MBB;
1478
1479     // Update machine-CFG edges
1480     BB->addSuccessor(sinkMBB);
1481
1482     //  sinkMBB:
1483     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1484     //  ...
1485     BB = sinkMBB;
1486     BuildMI(BB, TII->get(ARM::PHI), MI->getOperand(0).getReg())
1487       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1488       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1489
1490     delete MI;   // The pseudo instruction is gone now.
1491     return BB;
1492   }
1493   }
1494 }
1495
1496 //===----------------------------------------------------------------------===//
1497 //                           ARM Optimization Hooks
1498 //===----------------------------------------------------------------------===//
1499
1500 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
1501 static SDOperand PerformFMRRDCombine(SDNode *N, 
1502                                      TargetLowering::DAGCombinerInfo &DCI) {
1503   // fmrrd(fmdrr x, y) -> x,y
1504   SDOperand InDouble = N->getOperand(0);
1505   if (InDouble.getOpcode() == ARMISD::FMDRR)
1506     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
1507   return SDOperand();
1508 }
1509
1510 SDOperand ARMTargetLowering::PerformDAGCombine(SDNode *N,
1511                                                DAGCombinerInfo &DCI) const {
1512   switch (N->getOpcode()) {
1513   default: break;
1514   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
1515   }
1516   
1517   return SDOperand();
1518 }
1519
1520
1521 /// isLegalAddressImmediate - Return true if the integer value can be used
1522 /// as the offset of the target addressing mode for load / store of the
1523 /// given type.
1524 static bool isLegalAddressImmediate(int64_t V, MVT::ValueType VT,
1525                                     const ARMSubtarget *Subtarget) {
1526   if (V == 0)
1527     return true;
1528
1529   if (Subtarget->isThumb()) {
1530     if (V < 0)
1531       return false;
1532
1533     unsigned Scale = 1;
1534     switch (VT) {
1535     default: return false;
1536     case MVT::i1:
1537     case MVT::i8:
1538       // Scale == 1;
1539       break;
1540     case MVT::i16:
1541       // Scale == 2;
1542       Scale = 2;
1543       break;
1544     case MVT::i32:
1545       // Scale == 4;
1546       Scale = 4;
1547       break;
1548     }
1549
1550     if ((V & (Scale - 1)) != 0)
1551       return false;
1552     V /= Scale;
1553     return V == V & ((1LL << 5) - 1);
1554   }
1555
1556   if (V < 0)
1557     V = - V;
1558   switch (VT) {
1559   default: return false;
1560   case MVT::i1:
1561   case MVT::i8:
1562   case MVT::i32:
1563     // +- imm12
1564     return V == V & ((1LL << 12) - 1);
1565   case MVT::i16:
1566     // +- imm8
1567     return V == V & ((1LL << 8) - 1);
1568   case MVT::f32:
1569   case MVT::f64:
1570     if (!Subtarget->hasVFP2())
1571       return false;
1572     if ((V & 3) != 0)
1573       return false;
1574     V >>= 2;
1575     return V == V & ((1LL << 8) - 1);
1576   }
1577 }
1578
1579 /// isLegalAddressingMode - Return true if the addressing mode represented
1580 /// by AM is legal for this target, for a load/store of the specified type.
1581 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM, 
1582                                               const Type *Ty) const {
1583   if (!isLegalAddressImmediate(AM.BaseOffs, getValueType(Ty), Subtarget))
1584     return false;
1585   
1586   // Can never fold addr of global into load/store.
1587   if (AM.BaseGV) 
1588     return false;
1589   
1590   switch (AM.Scale) {
1591   case 0:  // no scale reg, must be "r+i" or "r", or "i".
1592     break;
1593   case 1:
1594     if (Subtarget->isThumb())
1595       return false;
1596     // FALL THROUGH.
1597   default:
1598     // ARM doesn't support any R+R*scale+imm addr modes.
1599     if (AM.BaseOffs)
1600       return false;
1601     
1602     int Scale = AM.Scale;
1603     switch (getValueType(Ty)) {
1604     default: return false;
1605     case MVT::i1:
1606     case MVT::i8:
1607     case MVT::i32:
1608     case MVT::i64:
1609       // This assumes i64 is legalized to a pair of i32. If not (i.e.
1610       // ldrd / strd are used, then its address mode is same as i16.
1611       // r + r
1612       if (Scale < 0) Scale = -Scale;
1613       if (Scale == 1)
1614         return true;
1615       // r + r << imm
1616       return isPowerOf2_32(Scale & ~1);
1617     case MVT::i16:
1618       // r + r
1619       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
1620         return true;
1621       return false;
1622       
1623     case MVT::isVoid:
1624       // Note, we allow "void" uses (basically, uses that aren't loads or
1625       // stores), because arm allows folding a scale into many arithmetic
1626       // operations.  This should be made more precise and revisited later.
1627       
1628       // Allow r << imm, but the imm has to be a multiple of two.
1629       if (AM.Scale & 1) return false;
1630       return isPowerOf2_32(AM.Scale);
1631     }
1632     break;
1633   }
1634   return true;
1635 }
1636
1637
1638 static bool getIndexedAddressParts(SDNode *Ptr, MVT::ValueType VT,
1639                                    bool isSEXTLoad, SDOperand &Base,
1640                                    SDOperand &Offset, bool &isInc,
1641                                    SelectionDAG &DAG) {
1642   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
1643     return false;
1644
1645   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
1646     // AddressingMode 3
1647     Base = Ptr->getOperand(0);
1648     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1649       int RHSC = (int)RHS->getValue();
1650       if (RHSC < 0 && RHSC > -256) {
1651         isInc = false;
1652         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1653         return true;
1654       }
1655     }
1656     isInc = (Ptr->getOpcode() == ISD::ADD);
1657     Offset = Ptr->getOperand(1);
1658     return true;
1659   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
1660     // AddressingMode 2
1661     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1662       int RHSC = (int)RHS->getValue();
1663       if (RHSC < 0 && RHSC > -0x1000) {
1664         isInc = false;
1665         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1666         Base = Ptr->getOperand(0);
1667         return true;
1668       }
1669     }
1670
1671     if (Ptr->getOpcode() == ISD::ADD) {
1672       isInc = true;
1673       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
1674       if (ShOpcVal != ARM_AM::no_shift) {
1675         Base = Ptr->getOperand(1);
1676         Offset = Ptr->getOperand(0);
1677       } else {
1678         Base = Ptr->getOperand(0);
1679         Offset = Ptr->getOperand(1);
1680       }
1681       return true;
1682     }
1683
1684     isInc = (Ptr->getOpcode() == ISD::ADD);
1685     Base = Ptr->getOperand(0);
1686     Offset = Ptr->getOperand(1);
1687     return true;
1688   }
1689
1690   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
1691   return false;
1692 }
1693
1694 /// getPreIndexedAddressParts - returns true by value, base pointer and
1695 /// offset pointer and addressing mode by reference if the node's address
1696 /// can be legally represented as pre-indexed load / store address.
1697 bool
1698 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDOperand &Base,
1699                                              SDOperand &Offset,
1700                                              ISD::MemIndexedMode &AM,
1701                                              SelectionDAG &DAG) {
1702   if (Subtarget->isThumb())
1703     return false;
1704
1705   MVT::ValueType VT;
1706   SDOperand Ptr;
1707   bool isSEXTLoad = false;
1708   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1709     Ptr = LD->getBasePtr();
1710     VT  = LD->getMemoryVT();
1711     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
1712   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1713     Ptr = ST->getBasePtr();
1714     VT  = ST->getMemoryVT();
1715   } else
1716     return false;
1717
1718   bool isInc;
1719   bool isLegal = getIndexedAddressParts(Ptr.Val, VT, isSEXTLoad, Base, Offset,
1720                                         isInc, DAG);
1721   if (isLegal) {
1722     AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
1723     return true;
1724   }
1725   return false;
1726 }
1727
1728 /// getPostIndexedAddressParts - returns true by value, base pointer and
1729 /// offset pointer and addressing mode by reference if this node can be
1730 /// combined with a load / store to form a post-indexed load / store.
1731 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
1732                                                    SDOperand &Base,
1733                                                    SDOperand &Offset,
1734                                                    ISD::MemIndexedMode &AM,
1735                                                    SelectionDAG &DAG) {
1736   if (Subtarget->isThumb())
1737     return false;
1738
1739   MVT::ValueType VT;
1740   SDOperand Ptr;
1741   bool isSEXTLoad = false;
1742   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1743     VT  = LD->getMemoryVT();
1744     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
1745   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1746     VT  = ST->getMemoryVT();
1747   } else
1748     return false;
1749
1750   bool isInc;
1751   bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
1752                                         isInc, DAG);
1753   if (isLegal) {
1754     AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
1755     return true;
1756   }
1757   return false;
1758 }
1759
1760 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
1761                                                        const APInt &Mask,
1762                                                        APInt &KnownZero, 
1763                                                        APInt &KnownOne,
1764                                                        const SelectionDAG &DAG,
1765                                                        unsigned Depth) const {
1766   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
1767   switch (Op.getOpcode()) {
1768   default: break;
1769   case ARMISD::CMOV: {
1770     // Bits are known zero/one if known on the LHS and RHS.
1771     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1772     if (KnownZero == 0 && KnownOne == 0) return;
1773
1774     APInt KnownZeroRHS, KnownOneRHS;
1775     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
1776                           KnownZeroRHS, KnownOneRHS, Depth+1);
1777     KnownZero &= KnownZeroRHS;
1778     KnownOne  &= KnownOneRHS;
1779     return;
1780   }
1781   }
1782 }
1783
1784 //===----------------------------------------------------------------------===//
1785 //                           ARM Inline Assembly Support
1786 //===----------------------------------------------------------------------===//
1787
1788 /// getConstraintType - Given a constraint letter, return the type of
1789 /// constraint it is for this target.
1790 ARMTargetLowering::ConstraintType
1791 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
1792   if (Constraint.size() == 1) {
1793     switch (Constraint[0]) {
1794     default:  break;
1795     case 'l': return C_RegisterClass;
1796     case 'w': return C_RegisterClass;
1797     }
1798   }
1799   return TargetLowering::getConstraintType(Constraint);
1800 }
1801
1802 std::pair<unsigned, const TargetRegisterClass*> 
1803 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1804                                                 MVT::ValueType VT) const {
1805   if (Constraint.size() == 1) {
1806     // GCC RS6000 Constraint Letters
1807     switch (Constraint[0]) {
1808     case 'l':
1809     // FIXME: in thumb mode, 'l' is only low-regs.
1810     // FALL THROUGH.
1811     case 'r':
1812       return std::make_pair(0U, ARM::GPRRegisterClass);
1813     case 'w':
1814       if (VT == MVT::f32)
1815         return std::make_pair(0U, ARM::SPRRegisterClass);
1816       if (VT == MVT::f64)
1817         return std::make_pair(0U, ARM::DPRRegisterClass);
1818       break;
1819     }
1820   }
1821   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1822 }
1823
1824 std::vector<unsigned> ARMTargetLowering::
1825 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1826                                   MVT::ValueType VT) const {
1827   if (Constraint.size() != 1)
1828     return std::vector<unsigned>();
1829
1830   switch (Constraint[0]) {      // GCC ARM Constraint Letters
1831   default: break;
1832   case 'l':
1833   case 'r':
1834     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
1835                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
1836                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
1837                                  ARM::R12, ARM::LR, 0);
1838   case 'w':
1839     if (VT == MVT::f32)
1840       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
1841                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
1842                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
1843                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
1844                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
1845                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
1846                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
1847                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
1848     if (VT == MVT::f64)
1849       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
1850                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
1851                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
1852                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
1853       break;
1854   }
1855
1856   return std::vector<unsigned>();
1857 }