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