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