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