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