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