Fix pr4202: Disable CodePlacementOpt for ARM. The ARMConstantIslandPass has
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMISelLowering.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMRegisterInfo.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instruction.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/GlobalValue.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/VectorExtras.h"
39 #include "llvm/Support/MathExtras.h"
40 using namespace llvm;
41
42 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
43                                    CCValAssign::LocInfo &LocInfo,
44                                    ISD::ArgFlagsTy &ArgFlags,
45                                    CCState &State);
46 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
47                                     CCValAssign::LocInfo &LocInfo,
48                                     ISD::ArgFlagsTy &ArgFlags,
49                                     CCState &State);
50 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
51                                       CCValAssign::LocInfo &LocInfo,
52                                       ISD::ArgFlagsTy &ArgFlags,
53                                       CCState &State);
54 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
55                                        CCValAssign::LocInfo &LocInfo,
56                                        ISD::ArgFlagsTy &ArgFlags,
57                                        CCState &State);
58
59 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
60     : TargetLowering(TM), ARMPCLabelIndex(0) {
61   Subtarget = &TM.getSubtarget<ARMSubtarget>();
62
63   if (Subtarget->isTargetDarwin()) {
64     // Uses VFP for Thumb libfuncs if available.
65     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
66       // Single-precision floating-point arithmetic.
67       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
68       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
69       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
70       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
71
72       // Double-precision floating-point arithmetic.
73       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
74       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
75       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
76       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
77
78       // Single-precision comparisons.
79       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
80       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
81       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
82       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
83       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
84       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
85       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
86       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
87
88       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
89       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
90       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
91       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
92       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
93       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
94       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
95       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
96
97       // Double-precision comparisons.
98       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
99       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
100       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
101       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
102       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
103       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
104       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
105       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
106
107       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
108       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
109       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
110       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
111       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
112       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
113       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
114       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
115
116       // Floating-point to integer conversions.
117       // i64 conversions are done via library routines even when generating VFP
118       // instructions, so use the same ones.
119       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
120       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
121       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
122       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
123
124       // Conversions between floating types.
125       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
126       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
127
128       // Integer to floating-point conversions.
129       // i64 conversions are done via library routines even when generating VFP
130       // instructions, so use the same ones.
131       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
132       // e.g., __floatunsidf vs. __floatunssidfvfp.
133       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
134       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
135       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
136       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
137     }
138   }
139
140   if (Subtarget->isThumb())
141     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
142   else
143     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
144   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
145     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
146     addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
147
148     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
149   }
150   computeRegisterProperties();
151
152   // ARM does not have f32 extending load.
153   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
154
155   // ARM does not have i1 sign extending load.
156   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
157
158   // ARM supports all 4 flavors of integer indexed load / store.
159   for (unsigned im = (unsigned)ISD::PRE_INC;
160        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
161     setIndexedLoadAction(im,  MVT::i1,  Legal);
162     setIndexedLoadAction(im,  MVT::i8,  Legal);
163     setIndexedLoadAction(im,  MVT::i16, Legal);
164     setIndexedLoadAction(im,  MVT::i32, Legal);
165     setIndexedStoreAction(im, MVT::i1,  Legal);
166     setIndexedStoreAction(im, MVT::i8,  Legal);
167     setIndexedStoreAction(im, MVT::i16, Legal);
168     setIndexedStoreAction(im, MVT::i32, Legal);
169   }
170
171   // i64 operation support.
172   if (Subtarget->isThumb()) {
173     setOperationAction(ISD::MUL,     MVT::i64, Expand);
174     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
175     setOperationAction(ISD::MULHS,   MVT::i32, Expand);
176     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
177     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
178   } else {
179     setOperationAction(ISD::MUL,     MVT::i64, Expand);
180     setOperationAction(ISD::MULHU,   MVT::i32, Expand);
181     if (!Subtarget->hasV6Ops())
182       setOperationAction(ISD::MULHS, MVT::i32, Expand);
183   }
184   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
185   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
186   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
187   setOperationAction(ISD::SRL,       MVT::i64, Custom);
188   setOperationAction(ISD::SRA,       MVT::i64, Custom);
189
190   // ARM does not have ROTL.
191   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
192   setOperationAction(ISD::CTTZ,  MVT::i32, Expand);
193   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
194   if (!Subtarget->hasV5TOps() || Subtarget->isThumb())
195     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
196
197   // Only ARMv6 has BSWAP.
198   if (!Subtarget->hasV6Ops())
199     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
200
201   // These are expanded into libcalls.
202   setOperationAction(ISD::SDIV,  MVT::i32, Expand);
203   setOperationAction(ISD::UDIV,  MVT::i32, Expand);
204   setOperationAction(ISD::SREM,  MVT::i32, Expand);
205   setOperationAction(ISD::UREM,  MVT::i32, Expand);
206   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
207   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
208
209   // Support label based line numbers.
210   setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
211   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
212
213   setOperationAction(ISD::RET,           MVT::Other, Custom);
214   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
215   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
216   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
217   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
218
219   // Use the default implementation.
220   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
221   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
222   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
223   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
224   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
225   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
226   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,   Expand);
227   setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
228
229   if (!Subtarget->hasV6Ops()) {
230     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
231     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
232   }
233   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
234
235   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb())
236     // Turn f64->i64 into FMRRD, i64 -> f64 to FMDRR iff target supports vfp2.
237     setOperationAction(ISD::BIT_CONVERT, MVT::i64, Custom);
238
239   // We want to custom lower some of our intrinsics.
240   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
241
242   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
243   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
244   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
245   setOperationAction(ISD::SELECT,    MVT::i32, Expand);
246   setOperationAction(ISD::SELECT,    MVT::f32, Expand);
247   setOperationAction(ISD::SELECT,    MVT::f64, Expand);
248   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
249   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
250   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
251
252   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
253   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
254   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
255   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
256   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
257
258   // We don't support sin/cos/fmod/copysign/pow
259   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
260   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
261   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
262   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
263   setOperationAction(ISD::FREM,      MVT::f64, Expand);
264   setOperationAction(ISD::FREM,      MVT::f32, Expand);
265   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
266     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
267     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
268   }
269   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
270   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
271
272   // int <-> fp are custom expanded into bit_convert + ARMISD ops.
273   if (!UseSoftFloat && Subtarget->hasVFP2() && !Subtarget->isThumb()) {
274     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
275     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
276     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
277     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
278   }
279
280   // We have target-specific dag combine patterns for the following nodes:
281   // ARMISD::FMRRD  - No need to call setTargetDAGCombine
282   setTargetDAGCombine(ISD::ADD);
283   setTargetDAGCombine(ISD::SUB);
284
285   setStackPointerRegisterToSaveRestore(ARM::SP);
286   setSchedulingPreference(SchedulingForRegPressure);
287   setIfCvtBlockSizeLimit(Subtarget->isThumb() ? 0 : 10);
288   setIfCvtDupBlockSizeLimit(Subtarget->isThumb() ? 0 : 2);
289
290   maxStoresPerMemcpy = 1;   //// temporary - rewrite interface to use type
291   // Do not enable CodePlacementOpt for now: it currently runs after the
292   // ARMConstantIslandPass and messes up branch relaxation and placement
293   // of constant islands.
294   // benefitFromCodePlacementOpt = true;
295 }
296
297 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
298   switch (Opcode) {
299   default: return 0;
300   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
301   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
302   case ARMISD::CALL:          return "ARMISD::CALL";
303   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
304   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
305   case ARMISD::tCALL:         return "ARMISD::tCALL";
306   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
307   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
308   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
309   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
310   case ARMISD::CMP:           return "ARMISD::CMP";
311   case ARMISD::CMPNZ:         return "ARMISD::CMPNZ";
312   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
313   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
314   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
315   case ARMISD::CMOV:          return "ARMISD::CMOV";
316   case ARMISD::CNEG:          return "ARMISD::CNEG";
317
318   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
319   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
320   case ARMISD::SITOF:         return "ARMISD::SITOF";
321   case ARMISD::UITOF:         return "ARMISD::UITOF";
322
323   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
324   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
325   case ARMISD::RRX:           return "ARMISD::RRX";
326
327   case ARMISD::FMRRD:         return "ARMISD::FMRRD";
328   case ARMISD::FMDRR:         return "ARMISD::FMDRR";
329
330   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
331   }
332 }
333
334 //===----------------------------------------------------------------------===//
335 // Lowering Code
336 //===----------------------------------------------------------------------===//
337
338 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
339 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
340   switch (CC) {
341   default: assert(0 && "Unknown condition code!");
342   case ISD::SETNE:  return ARMCC::NE;
343   case ISD::SETEQ:  return ARMCC::EQ;
344   case ISD::SETGT:  return ARMCC::GT;
345   case ISD::SETGE:  return ARMCC::GE;
346   case ISD::SETLT:  return ARMCC::LT;
347   case ISD::SETLE:  return ARMCC::LE;
348   case ISD::SETUGT: return ARMCC::HI;
349   case ISD::SETUGE: return ARMCC::HS;
350   case ISD::SETULT: return ARMCC::LO;
351   case ISD::SETULE: return ARMCC::LS;
352   }
353 }
354
355 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC. It
356 /// returns true if the operands should be inverted to form the proper
357 /// comparison.
358 static bool FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
359                         ARMCC::CondCodes &CondCode2) {
360   bool Invert = false;
361   CondCode2 = ARMCC::AL;
362   switch (CC) {
363   default: assert(0 && "Unknown FP condition!");
364   case ISD::SETEQ:
365   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
366   case ISD::SETGT:
367   case ISD::SETOGT: CondCode = ARMCC::GT; break;
368   case ISD::SETGE:
369   case ISD::SETOGE: CondCode = ARMCC::GE; break;
370   case ISD::SETOLT: CondCode = ARMCC::MI; break;
371   case ISD::SETOLE: CondCode = ARMCC::GT; Invert = true; break;
372   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
373   case ISD::SETO:   CondCode = ARMCC::VC; break;
374   case ISD::SETUO:  CondCode = ARMCC::VS; break;
375   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
376   case ISD::SETUGT: CondCode = ARMCC::HI; break;
377   case ISD::SETUGE: CondCode = ARMCC::PL; break;
378   case ISD::SETLT:
379   case ISD::SETULT: CondCode = ARMCC::LT; break;
380   case ISD::SETLE:
381   case ISD::SETULE: CondCode = ARMCC::LE; break;
382   case ISD::SETNE:
383   case ISD::SETUNE: CondCode = ARMCC::NE; break;
384   }
385   return Invert;
386 }
387
388 //===----------------------------------------------------------------------===//
389 //                      Calling Convention Implementation
390 //
391 //  The lower operations present on calling convention works on this order:
392 //      LowerCALL (virt regs --> phys regs, virt regs --> stack)
393 //      LowerFORMAL_ARGUMENTS (phys --> virt regs, stack --> virt regs)
394 //      LowerRET (virt regs --> phys regs)
395 //      LowerCALL (phys regs --> virt regs)
396 //
397 //===----------------------------------------------------------------------===//
398
399 #include "ARMGenCallingConv.inc"
400
401 // APCS f64 is in register pairs, possibly split to stack
402 static bool CC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
403                                    CCValAssign::LocInfo &LocInfo,
404                                    ISD::ArgFlagsTy &ArgFlags,
405                                    CCState &State) {
406   static const unsigned HiRegList[] = { ARM::R0, ARM::R1, ARM::R2, ARM::R3 };
407   static const unsigned LoRegList[] = { ARM::R1,
408                                         ARM::R2,
409                                         ARM::R3,
410                                         ARM::NoRegister };
411
412   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 4);
413   if (Reg == 0) 
414     return false; // we didn't handle it
415
416   unsigned i;
417   for (i = 0; i < 4; ++i)
418     if (HiRegList[i] == Reg)
419       break;
420
421   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
422   if (LoRegList[i] != ARM::NoRegister)
423     State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
424                                            MVT::i32, LocInfo));
425   else
426     State.addLoc(CCValAssign::getCustomMem(ValNo, ValVT,
427                                            State.AllocateStack(4, 4),
428                                            MVT::i32, LocInfo));
429   return true;  // we handled it
430 }
431
432 // AAPCS f64 is in aligned register pairs
433 static bool CC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
434                                     CCValAssign::LocInfo &LocInfo,
435                                     ISD::ArgFlagsTy &ArgFlags,
436                                     CCState &State) {
437   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
438   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
439
440   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
441   if (Reg == 0)
442     return false; // we didn't handle it
443
444   unsigned i;
445   for (i = 0; i < 2; ++i)
446     if (HiRegList[i] == Reg)
447       break;
448
449   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
450   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
451                                          MVT::i32, LocInfo));
452   return true;  // we handled it
453 }
454
455 static bool RetCC_ARM_APCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
456                                       CCValAssign::LocInfo &LocInfo,
457                                       ISD::ArgFlagsTy &ArgFlags,
458                                       CCState &State) {
459   static const unsigned HiRegList[] = { ARM::R0, ARM::R2 };
460   static const unsigned LoRegList[] = { ARM::R1, ARM::R3 };
461
462   unsigned Reg = State.AllocateReg(HiRegList, LoRegList, 2);
463   if (Reg == 0)
464     return false; // we didn't handle it
465
466   unsigned i;
467   for (i = 0; i < 2; ++i)
468     if (HiRegList[i] == Reg)
469       break;
470
471   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg, MVT::i32, LocInfo));
472   State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, LoRegList[i],
473                                          MVT::i32, LocInfo));
474   return true;  // we handled it
475 }
476
477 static bool RetCC_ARM_AAPCS_Custom_f64(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
478                                        CCValAssign::LocInfo &LocInfo,
479                                        ISD::ArgFlagsTy &ArgFlags,
480                                        CCState &State) {
481   return RetCC_ARM_APCS_Custom_f64(ValNo, ValVT, LocVT, LocInfo, ArgFlags,
482                                    State);
483 }
484
485 /// LowerCallResult - Lower the result values of an ISD::CALL into the
486 /// appropriate copies out of appropriate physical registers.  This assumes that
487 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
488 /// being lowered.  The returns a SDNode with the same number of values as the
489 /// ISD::CALL.
490 SDNode *ARMTargetLowering::
491 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
492                 unsigned CallingConv, SelectionDAG &DAG) {
493
494   DebugLoc dl = TheCall->getDebugLoc();
495   // Assign locations to each value returned by this call.
496   SmallVector<CCValAssign, 16> RVLocs;
497   bool isVarArg = TheCall->isVarArg();
498   CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
499   CCInfo.AnalyzeCallResult(TheCall, RetCC_ARM);
500
501   SmallVector<SDValue, 8> ResultVals;
502
503   // Copy all of the result registers out of their specified physreg.
504   for (unsigned i = 0; i != RVLocs.size(); ++i) {
505     CCValAssign VA = RVLocs[i];
506
507     SDValue Val;
508     if (VA.needsCustom()) {
509       // Handle f64 as custom.
510       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
511                                       InFlag);
512       Chain = Lo.getValue(1);
513       InFlag = Lo.getValue(2);
514       VA = RVLocs[++i]; // skip ahead to next loc
515       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
516                                       InFlag);
517       Chain = Hi.getValue(1);
518       InFlag = Hi.getValue(2);
519       Val = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
520     } else {
521       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
522                                InFlag);
523       Chain = Val.getValue(1);
524       InFlag = Val.getValue(2);
525     }
526
527     switch (VA.getLocInfo()) {
528     default: assert(0 && "Unknown loc info!");
529     case CCValAssign::Full: break;
530     case CCValAssign::BCvt:
531       Val = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), Val);
532       break;
533     }
534
535     ResultVals.push_back(Val);
536   }
537
538   // Merge everything together with a MERGE_VALUES node.
539   ResultVals.push_back(Chain);
540   return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
541                      &ResultVals[0], ResultVals.size()).getNode();
542 }
543
544 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
545 /// by "Src" to address "Dst" of size "Size".  Alignment information is
546 /// specified by the specific parameter attribute.  The copy will be passed as
547 /// a byval function parameter.
548 /// Sometimes what we are copying is the end of a larger object, the part that
549 /// does not fit in registers.
550 static SDValue
551 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
552                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
553                           DebugLoc dl) {
554   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
555   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
556                        /*AlwaysInline=*/false, NULL, 0, NULL, 0);
557 }
558
559 /// LowerMemOpCallTo - Store the argument to the stack.
560 SDValue
561 ARMTargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
562                                     const SDValue &StackPtr,
563                                     const CCValAssign &VA, SDValue Chain,
564                                     SDValue Arg, ISD::ArgFlagsTy Flags) {
565   DebugLoc dl = TheCall->getDebugLoc();
566   unsigned LocMemOffset = VA.getLocMemOffset();
567   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
568   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
569   if (Flags.isByVal()) {
570     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
571   }
572   return DAG.getStore(Chain, dl, Arg, PtrOff,
573                       PseudoSourceValue::getStack(), LocMemOffset);
574 }
575
576 /// LowerCALL - Lowering a ISD::CALL node into a callseq_start <-
577 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
578 /// nodes.
579 SDValue ARMTargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
580   CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
581   MVT RetVT           = TheCall->getRetValType(0);
582   SDValue Chain       = TheCall->getChain();
583   unsigned CC         = TheCall->getCallingConv();
584   assert((CC == CallingConv::C ||
585           CC == CallingConv::Fast) && "unknown calling convention");
586   bool isVarArg       = TheCall->isVarArg();
587   SDValue Callee      = TheCall->getCallee();
588   DebugLoc dl         = TheCall->getDebugLoc();
589
590   // Analyze operands of the call, assigning locations to each operand.
591   SmallVector<CCValAssign, 16> ArgLocs;
592   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
593   CCInfo.AnalyzeCallOperands(TheCall, CC_ARM);
594
595   // Get a count of how many bytes are to be pushed on the stack.
596   unsigned NumBytes = CCInfo.getNextStackOffset();
597
598   // Adjust the stack pointer for the new arguments...
599   // These operations are automatically eliminated by the prolog/epilog pass
600   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
601
602   SDValue StackPtr = DAG.getRegister(ARM::SP, MVT::i32);
603
604   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
605   SmallVector<SDValue, 8> MemOpChains;
606
607   // Walk the register/memloc assignments, inserting copies/loads.  In the case
608   // of tail call optimization, arguments are handled later.
609   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
610        i != e;
611        ++i, ++realArgIdx) {
612     CCValAssign &VA = ArgLocs[i];
613     SDValue Arg = TheCall->getArg(realArgIdx);
614     ISD::ArgFlagsTy Flags = TheCall->getArgFlags(realArgIdx);
615
616     // Promote the value if needed.
617     switch (VA.getLocInfo()) {
618     default: assert(0 && "Unknown loc info!");
619     case CCValAssign::Full: break;
620     case CCValAssign::SExt:
621       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
622       break;
623     case CCValAssign::ZExt:
624       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
625       break;
626     case CCValAssign::AExt:
627       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
628       break;
629     case CCValAssign::BCvt:
630       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
631       break;
632     }
633
634     // f64 is passed in i32 pairs and must be combined
635     if (VA.needsCustom()) {
636       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
637                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
638       RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
639       VA = ArgLocs[++i]; // skip ahead to next loc
640       if (VA.isRegLoc())
641         RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(1)));
642       else {
643         assert(VA.isMemLoc());
644         if (StackPtr.getNode() == 0)
645           StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
646
647         MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
648                                                Chain, fmrrd.getValue(1),
649                                                Flags));
650       }
651     } else if (VA.isRegLoc()) {
652       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
653     } else {
654       assert(VA.isMemLoc());
655       if (StackPtr.getNode() == 0)
656         StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
657
658       MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
659                                              Chain, Arg, Flags));
660     }
661   }
662
663   if (!MemOpChains.empty())
664     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
665                         &MemOpChains[0], MemOpChains.size());
666
667   // Build a sequence of copy-to-reg nodes chained together with token chain
668   // and flag operands which copy the outgoing args into the appropriate regs.
669   SDValue InFlag;
670   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
671     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
672                              RegsToPass[i].second, InFlag);
673     InFlag = Chain.getValue(1);
674   }
675
676   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
677   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
678   // node so that legalize doesn't hack it.
679   bool isDirect = false;
680   bool isARMFunc = false;
681   bool isLocalARMFunc = false;
682   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
683     GlobalValue *GV = G->getGlobal();
684     isDirect = true;
685     bool isExt = (GV->isDeclaration() || GV->hasWeakLinkage() ||
686                   GV->hasLinkOnceLinkage());
687     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
688                    getTargetMachine().getRelocationModel() != Reloc::Static;
689     isARMFunc = !Subtarget->isThumb() || isStub;
690     // ARM call to a local ARM function is predicable.
691     isLocalARMFunc = !Subtarget->isThumb() && !isExt;
692     // tBX takes a register source operand.
693     if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
694       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
695                                                            ARMCP::CPStub, 4);
696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
698       Callee = DAG.getLoad(getPointerTy(), dl,
699                            DAG.getEntryNode(), CPAddr, NULL, 0);
700       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
701       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
702                            getPointerTy(), Callee, PICLabel);
703    } else
704       Callee = DAG.getTargetGlobalAddress(GV, getPointerTy());
705   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
706     isDirect = true;
707     bool isStub = Subtarget->isTargetDarwin() &&
708                   getTargetMachine().getRelocationModel() != Reloc::Static;
709     isARMFunc = !Subtarget->isThumb() || isStub;
710     // tBX takes a register source operand.
711     const char *Sym = S->getSymbol();
712     if (isARMFunc && Subtarget->isThumb() && !Subtarget->hasV5TOps()) {
713       ARMConstantPoolValue *CPV = new ARMConstantPoolValue(Sym, ARMPCLabelIndex,
714                                                            ARMCP::CPStub, 4);
715       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
716       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
717       Callee = DAG.getLoad(getPointerTy(), dl,
718                            DAG.getEntryNode(), CPAddr, NULL, 0);
719       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
720       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
721                            getPointerTy(), Callee, PICLabel);
722     } else
723       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy());
724   }
725
726   // FIXME: handle tail calls differently.
727   unsigned CallOpc;
728   if (Subtarget->isThumb()) {
729     if (!Subtarget->hasV5TOps() && (!isDirect || isARMFunc))
730       CallOpc = ARMISD::CALL_NOLINK;
731     else
732       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
733   } else {
734     CallOpc = (isDirect || Subtarget->hasV5TOps())
735       ? (isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL)
736       : ARMISD::CALL_NOLINK;
737   }
738   if (CallOpc == ARMISD::CALL_NOLINK && !Subtarget->isThumb()) {
739     // implicit def LR - LR mustn't be allocated as GRP:$dst of CALL_NOLINK
740     Chain = DAG.getCopyToReg(Chain, dl, ARM::LR, DAG.getUNDEF(MVT::i32),InFlag);
741     InFlag = Chain.getValue(1);
742   }
743
744   std::vector<SDValue> Ops;
745   Ops.push_back(Chain);
746   Ops.push_back(Callee);
747
748   // Add argument registers to the end of the list so that they are known live
749   // into the call.
750   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
751     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
752                                   RegsToPass[i].second.getValueType()));
753
754   if (InFlag.getNode())
755     Ops.push_back(InFlag);
756   // Returns a chain and a flag for retval copy to use.
757   Chain = DAG.getNode(CallOpc, dl, DAG.getVTList(MVT::Other, MVT::Flag),
758                       &Ops[0], Ops.size());
759   InFlag = Chain.getValue(1);
760
761   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
762                              DAG.getIntPtrConstant(0, true), InFlag);
763   if (RetVT != MVT::Other)
764     InFlag = Chain.getValue(1);
765
766   // Handle result values, copying them out of physregs into vregs that we
767   // return.
768   return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
769                                  Op.getResNo());
770 }
771
772 SDValue ARMTargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
773   // The chain is always operand #0
774   SDValue Chain = Op.getOperand(0);
775   DebugLoc dl = Op.getDebugLoc();
776
777   // CCValAssign - represent the assignment of the return value to a location.
778   SmallVector<CCValAssign, 16> RVLocs;
779   unsigned CC   = DAG.getMachineFunction().getFunction()->getCallingConv();
780   bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
781
782   // CCState - Info about the registers and stack slots.
783   CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
784
785   // Analyze return values of ISD::RET.
786   CCInfo.AnalyzeReturn(Op.getNode(), RetCC_ARM);
787
788   // If this is the first return lowered for this function, add
789   // the regs to the liveout set for the function.
790   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
791     for (unsigned i = 0; i != RVLocs.size(); ++i)
792       if (RVLocs[i].isRegLoc())
793         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
794   }
795
796   SDValue Flag;
797
798   // Copy the result values into the output registers.
799   for (unsigned i = 0, realRVLocIdx = 0;
800        i != RVLocs.size();
801        ++i, ++realRVLocIdx) {
802     CCValAssign &VA = RVLocs[i];
803     assert(VA.isRegLoc() && "Can only return in registers!");
804
805     // ISD::RET => ret chain, (regnum1,val1), ...
806     // So i*2+1 index only the regnums
807     SDValue Arg = Op.getOperand(realRVLocIdx*2+1);
808
809     switch (VA.getLocInfo()) {
810     default: assert(0 && "Unknown loc info!");
811     case CCValAssign::Full: break;
812     case CCValAssign::BCvt:
813       Arg = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), Arg);
814       break;
815     }
816
817     // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
818     // available.
819     if (VA.needsCustom()) {
820       SDValue fmrrd = DAG.getNode(ARMISD::FMRRD, dl,
821                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
822       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
823       Flag = Chain.getValue(1);
824       VA = RVLocs[++i]; // skip ahead to next loc
825       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
826                                Flag);
827     } else
828       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
829
830     // Guarantee that all emitted copies are
831     // stuck together, avoiding something bad.
832     Flag = Chain.getValue(1);
833   }
834
835   SDValue result;
836   if (Flag.getNode())
837     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
838   else // Return Void
839     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
840
841   return result;
842 }
843
844 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
845 // their target countpart wrapped in the ARMISD::Wrapper node. Suppose N is
846 // one of the above mentioned nodes. It has to be wrapped because otherwise
847 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
848 // be used to form addressing mode. These wrapped nodes will be selected
849 // into MOVi.
850 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
851   MVT PtrVT = Op.getValueType();
852   // FIXME there is no actual debug info here
853   DebugLoc dl = Op.getDebugLoc();
854   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
855   SDValue Res;
856   if (CP->isMachineConstantPoolEntry())
857     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
858                                     CP->getAlignment());
859   else
860     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
861                                     CP->getAlignment());
862   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
863 }
864
865 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
866 SDValue
867 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
868                                                  SelectionDAG &DAG) {
869   DebugLoc dl = GA->getDebugLoc();
870   MVT PtrVT = getPointerTy();
871   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
872   ARMConstantPoolValue *CPV =
873     new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
874                              PCAdj, "tlsgd", true);
875   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
876   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
877   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument, NULL, 0);
878   SDValue Chain = Argument.getValue(1);
879
880   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
881   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
882
883   // call __tls_get_addr.
884   ArgListTy Args;
885   ArgListEntry Entry;
886   Entry.Node = Argument;
887   Entry.Ty = (const Type *) Type::Int32Ty;
888   Args.push_back(Entry);
889   // FIXME: is there useful debug info available here?
890   std::pair<SDValue, SDValue> CallResult =
891     LowerCallTo(Chain, (const Type *) Type::Int32Ty, false, false, false, false,
892                 CallingConv::C, false,
893                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
894   return CallResult.first;
895 }
896
897 // Lower ISD::GlobalTLSAddress using the "initial exec" or
898 // "local exec" model.
899 SDValue
900 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
901                                         SelectionDAG &DAG) {
902   GlobalValue *GV = GA->getGlobal();
903   DebugLoc dl = GA->getDebugLoc();
904   SDValue Offset;
905   SDValue Chain = DAG.getEntryNode();
906   MVT PtrVT = getPointerTy();
907   // Get the Thread Pointer
908   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
909
910   if (GV->isDeclaration()){
911     // initial exec model
912     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
913     ARMConstantPoolValue *CPV =
914       new ARMConstantPoolValue(GA->getGlobal(), ARMPCLabelIndex, ARMCP::CPValue,
915                                PCAdj, "gottpoff", true);
916     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
917     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
918     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
919     Chain = Offset.getValue(1);
920
921     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
922     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
923
924     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
925   } else {
926     // local exec model
927     ARMConstantPoolValue *CPV =
928       new ARMConstantPoolValue(GV, ARMCP::CPValue, "tpoff");
929     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
930     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
931     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset, NULL, 0);
932   }
933
934   // The address of the thread local variable is the add of the thread
935   // pointer with the offset of the variable.
936   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
937 }
938
939 SDValue
940 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
941   // TODO: implement the "local dynamic" model
942   assert(Subtarget->isTargetELF() &&
943          "TLS not implemented for non-ELF targets");
944   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
945   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
946   // otherwise use the "Local Exec" TLS Model
947   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
948     return LowerToTLSGeneralDynamicModel(GA, DAG);
949   else
950     return LowerToTLSExecModels(GA, DAG);
951 }
952
953 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
954                                                  SelectionDAG &DAG) {
955   MVT PtrVT = getPointerTy();
956   DebugLoc dl = Op.getDebugLoc();
957   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
958   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
959   if (RelocM == Reloc::PIC_) {
960     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
961     ARMConstantPoolValue *CPV =
962       new ARMConstantPoolValue(GV, ARMCP::CPValue, UseGOTOFF ? "GOTOFF":"GOT");
963     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
964     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
965     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
966                                  CPAddr, NULL, 0);
967     SDValue Chain = Result.getValue(1);
968     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
969     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
970     if (!UseGOTOFF)
971       Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
972     return Result;
973   } else {
974     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
975     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
976     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
977   }
978 }
979
980 /// GVIsIndirectSymbol - true if the GV will be accessed via an indirect symbol
981 /// even in non-static mode.
982 static bool GVIsIndirectSymbol(GlobalValue *GV, Reloc::Model RelocM) {
983   // If symbol visibility is hidden, the extra load is not needed if
984   // the symbol is definitely defined in the current translation unit.
985   bool isDecl = GV->isDeclaration() && !GV->hasNotBeenReadFromBitcode();
986   if (GV->hasHiddenVisibility() && (!isDecl && !GV->hasCommonLinkage()))
987     return false;
988   return RelocM != Reloc::Static && (isDecl || GV->isWeakForLinker());
989 }
990
991 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
992                                                     SelectionDAG &DAG) {
993   MVT PtrVT = getPointerTy();
994   DebugLoc dl = Op.getDebugLoc();
995   GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
996   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
997   bool IsIndirect = GVIsIndirectSymbol(GV, RelocM);
998   SDValue CPAddr;
999   if (RelocM == Reloc::Static)
1000     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
1001   else {
1002     unsigned PCAdj = (RelocM != Reloc::PIC_)
1003       ? 0 : (Subtarget->isThumb() ? 4 : 8);
1004     ARMCP::ARMCPKind Kind = IsIndirect ? ARMCP::CPNonLazyPtr
1005       : ARMCP::CPValue;
1006     ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, ARMPCLabelIndex,
1007                                                          Kind, PCAdj);
1008     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1009   }
1010   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1011
1012   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1013   SDValue Chain = Result.getValue(1);
1014
1015   if (RelocM == Reloc::PIC_) {
1016     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1017     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1018   }
1019   if (IsIndirect)
1020     Result = DAG.getLoad(PtrVT, dl, Chain, Result, NULL, 0);
1021
1022   return Result;
1023 }
1024
1025 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
1026                                                     SelectionDAG &DAG){
1027   assert(Subtarget->isTargetELF() &&
1028          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
1029   MVT PtrVT = getPointerTy();
1030   DebugLoc dl = Op.getDebugLoc();
1031   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
1032   ARMConstantPoolValue *CPV = new ARMConstantPoolValue("_GLOBAL_OFFSET_TABLE_",
1033                                                        ARMPCLabelIndex,
1034                                                        ARMCP::CPValue, PCAdj);
1035   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
1036   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1037   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr, NULL, 0);
1038   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex++, MVT::i32);
1039   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
1040 }
1041
1042 SDValue
1043 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
1044   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1045   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1046   DebugLoc dl = Op.getDebugLoc();
1047   switch (IntNo) {
1048   default: return SDValue();    // Don't custom lower most intrinsics.
1049   case Intrinsic::arm_thread_pointer:
1050       return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
1051   case Intrinsic::eh_sjlj_setjmp:
1052       SDValue Res = DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl, MVT::i32,
1053                          Op.getOperand(1));
1054       return Res;
1055   }
1056 }
1057
1058 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1059                             unsigned VarArgsFrameIndex) {
1060   // vastart just stores the address of the VarArgsFrameIndex slot into the
1061   // memory location argument.
1062   DebugLoc dl = Op.getDebugLoc();
1063   MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1064   SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, PtrVT);
1065   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1066   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
1067 }
1068
1069 SDValue
1070 ARMTargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1071   MachineFunction &MF = DAG.getMachineFunction();
1072   MachineFrameInfo *MFI = MF.getFrameInfo();
1073
1074   SDValue Root = Op.getOperand(0);
1075   DebugLoc dl = Op.getDebugLoc();
1076   bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1077   unsigned CC = MF.getFunction()->getCallingConv();
1078   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1079
1080   // Assign locations to all of the incoming arguments.
1081   SmallVector<CCValAssign, 16> ArgLocs;
1082   CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1083   CCInfo.AnalyzeFormalArguments(Op.getNode(), CC_ARM);
1084
1085   SmallVector<SDValue, 16> ArgValues;
1086
1087   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1088     CCValAssign &VA = ArgLocs[i];
1089
1090     // Arguments stored in registers.
1091     if (VA.isRegLoc()) {
1092       MVT RegVT = VA.getLocVT();
1093       TargetRegisterClass *RC;
1094       if (AFI->isThumbFunction())
1095         RC = ARM::tGPRRegisterClass;
1096       else
1097         RC = ARM::GPRRegisterClass;
1098
1099       if (RegVT == MVT::f64) {
1100         // f64 is passed in pairs of GPRs and must be combined.
1101         RegVT = MVT::i32;
1102       } else if (!((RegVT == MVT::i32) || (RegVT == MVT::f32)))
1103         assert(0 && "RegVT not supported by FORMAL_ARGUMENTS Lowering");
1104
1105       // Transform the arguments stored in physical registers into virtual ones.
1106       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1107       SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1108
1109       // f64 is passed in i32 pairs and must be combined.
1110       if (VA.needsCustom()) {
1111         SDValue ArgValue2;
1112
1113         VA = ArgLocs[++i]; // skip ahead to next loc
1114         if (VA.isMemLoc()) {
1115           // must be APCS to split like this
1116           unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1117           int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1118
1119           // Create load node to retrieve arguments from the stack.
1120           SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1121           ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN, NULL, 0);
1122         } else {
1123           Reg = MF.addLiveIn(VA.getLocReg(), RC);
1124           ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
1125         }
1126
1127         ArgValue = DAG.getNode(ARMISD::FMDRR, dl, MVT::f64,
1128                                ArgValue, ArgValue2);
1129       }
1130
1131       // If this is an 8 or 16-bit value, it is really passed promoted
1132       // to 32 bits.  Insert an assert[sz]ext to capture this, then
1133       // truncate to the right size.
1134       switch (VA.getLocInfo()) {
1135       default: assert(0 && "Unknown loc info!");
1136       case CCValAssign::Full: break;
1137       case CCValAssign::BCvt:
1138         ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1139         break;
1140       case CCValAssign::SExt:
1141         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1142                                DAG.getValueType(VA.getValVT()));
1143         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1144         break;
1145       case CCValAssign::ZExt:
1146         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1147                                DAG.getValueType(VA.getValVT()));
1148         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1149         break;
1150       }
1151
1152       ArgValues.push_back(ArgValue);
1153
1154     } else { // VA.isRegLoc()
1155
1156       // sanity check
1157       assert(VA.isMemLoc());
1158       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
1159
1160       unsigned ArgSize = VA.getLocVT().getSizeInBits()/8;
1161       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset());
1162
1163       // Create load nodes to retrieve arguments from the stack.
1164       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1165       ArgValues.push_back(DAG.getLoad(VA.getValVT(), dl, Root, FIN, NULL, 0));
1166     }
1167   }
1168
1169   // varargs
1170   if (isVarArg) {
1171     static const unsigned GPRArgRegs[] = {
1172       ARM::R0, ARM::R1, ARM::R2, ARM::R3
1173     };
1174
1175     unsigned NumGPRs = CCInfo.getFirstUnallocated
1176       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
1177
1178     unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1179     unsigned VARegSize = (4 - NumGPRs) * 4;
1180     unsigned VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
1181     unsigned ArgOffset = 0;
1182     if (VARegSaveSize) {
1183       // If this function is vararg, store any remaining integer argument regs
1184       // to their spots on the stack so that they may be loaded by deferencing
1185       // the result of va_next.
1186       AFI->setVarArgsRegSaveSize(VARegSaveSize);
1187       ArgOffset = CCInfo.getNextStackOffset();
1188       VarArgsFrameIndex = MFI->CreateFixedObject(VARegSaveSize, ArgOffset +
1189                                                  VARegSaveSize - VARegSize);
1190       SDValue FIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
1191
1192       SmallVector<SDValue, 4> MemOps;
1193       for (; NumGPRs < 4; ++NumGPRs) {
1194         TargetRegisterClass *RC;
1195         if (AFI->isThumbFunction())
1196           RC = ARM::tGPRRegisterClass;
1197         else
1198           RC = ARM::GPRRegisterClass;
1199
1200         unsigned VReg = MF.addLiveIn(GPRArgRegs[NumGPRs], RC);
1201         SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i32);
1202         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN, NULL, 0);
1203         MemOps.push_back(Store);
1204         FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1205                           DAG.getConstant(4, getPointerTy()));
1206       }
1207       if (!MemOps.empty())
1208         Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1209                            &MemOps[0], MemOps.size());
1210     } else
1211       // This will point to the next argument passed via stack.
1212       VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
1213   }
1214
1215   ArgValues.push_back(Root);
1216
1217   // Return the new list of results.
1218   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1219                      &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1220 }
1221
1222 /// isFloatingPointZero - Return true if this is +0.0.
1223 static bool isFloatingPointZero(SDValue Op) {
1224   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1225     return CFP->getValueAPF().isPosZero();
1226   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1227     // Maybe this has already been legalized into the constant pool?
1228     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
1229       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
1230       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
1231         if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1232           return CFP->getValueAPF().isPosZero();
1233     }
1234   }
1235   return false;
1236 }
1237
1238 static bool isLegalCmpImmediate(unsigned C, bool isThumb) {
1239   return ( isThumb && (C & ~255U) == 0) ||
1240          (!isThumb && ARM_AM::getSOImmVal(C) != -1);
1241 }
1242
1243 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
1244 /// the given operands.
1245 static SDValue getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1246                          SDValue &ARMCC, SelectionDAG &DAG, bool isThumb,
1247                          DebugLoc dl) {
1248   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1249     unsigned C = RHSC->getZExtValue();
1250     if (!isLegalCmpImmediate(C, isThumb)) {
1251       // Constant does not fit, try adjusting it by one?
1252       switch (CC) {
1253       default: break;
1254       case ISD::SETLT:
1255       case ISD::SETGE:
1256         if (isLegalCmpImmediate(C-1, isThumb)) {
1257           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1258           RHS = DAG.getConstant(C-1, MVT::i32);
1259         }
1260         break;
1261       case ISD::SETULT:
1262       case ISD::SETUGE:
1263         if (C > 0 && isLegalCmpImmediate(C-1, isThumb)) {
1264           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1265           RHS = DAG.getConstant(C-1, MVT::i32);
1266         }
1267         break;
1268       case ISD::SETLE:
1269       case ISD::SETGT:
1270         if (isLegalCmpImmediate(C+1, isThumb)) {
1271           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1272           RHS = DAG.getConstant(C+1, MVT::i32);
1273         }
1274         break;
1275       case ISD::SETULE:
1276       case ISD::SETUGT:
1277         if (C < 0xffffffff && isLegalCmpImmediate(C+1, isThumb)) {
1278           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1279           RHS = DAG.getConstant(C+1, MVT::i32);
1280         }
1281         break;
1282       }
1283     }
1284   }
1285
1286   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
1287   ARMISD::NodeType CompareType;
1288   switch (CondCode) {
1289   default:
1290     CompareType = ARMISD::CMP;
1291     break;
1292   case ARMCC::EQ:
1293   case ARMCC::NE:
1294   case ARMCC::MI:
1295   case ARMCC::PL:
1296     // Uses only N and Z Flags
1297     CompareType = ARMISD::CMPNZ;
1298     break;
1299   }
1300   ARMCC = DAG.getConstant(CondCode, MVT::i32);
1301   return DAG.getNode(CompareType, dl, MVT::Flag, LHS, RHS);
1302 }
1303
1304 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
1305 static SDValue getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
1306                          DebugLoc dl) {
1307   SDValue Cmp;
1308   if (!isFloatingPointZero(RHS))
1309     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Flag, LHS, RHS);
1310   else
1311     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Flag, LHS);
1312   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Flag, Cmp);
1313 }
1314
1315 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG,
1316                               const ARMSubtarget *ST) {
1317   MVT VT = Op.getValueType();
1318   SDValue LHS = Op.getOperand(0);
1319   SDValue RHS = Op.getOperand(1);
1320   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1321   SDValue TrueVal = Op.getOperand(2);
1322   SDValue FalseVal = Op.getOperand(3);
1323   DebugLoc dl = Op.getDebugLoc();
1324
1325   if (LHS.getValueType() == MVT::i32) {
1326     SDValue ARMCC;
1327     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1328     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb(), dl);
1329     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMCC, CCR,Cmp);
1330   }
1331
1332   ARMCC::CondCodes CondCode, CondCode2;
1333   if (FPCCToARMCC(CC, CondCode, CondCode2))
1334     std::swap(TrueVal, FalseVal);
1335
1336   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1337   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1338   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1339   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
1340                                  ARMCC, CCR, Cmp);
1341   if (CondCode2 != ARMCC::AL) {
1342     SDValue ARMCC2 = DAG.getConstant(CondCode2, MVT::i32);
1343     // FIXME: Needs another CMP because flag can have but one use.
1344     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
1345     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
1346                          Result, TrueVal, ARMCC2, CCR, Cmp2);
1347   }
1348   return Result;
1349 }
1350
1351 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG,
1352                           const ARMSubtarget *ST) {
1353   SDValue  Chain = Op.getOperand(0);
1354   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1355   SDValue    LHS = Op.getOperand(2);
1356   SDValue    RHS = Op.getOperand(3);
1357   SDValue   Dest = Op.getOperand(4);
1358   DebugLoc dl = Op.getDebugLoc();
1359
1360   if (LHS.getValueType() == MVT::i32) {
1361     SDValue ARMCC;
1362     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1363     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMCC, DAG, ST->isThumb(), dl);
1364     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
1365                        Chain, Dest, ARMCC, CCR,Cmp);
1366   }
1367
1368   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
1369   ARMCC::CondCodes CondCode, CondCode2;
1370   if (FPCCToARMCC(CC, CondCode, CondCode2))
1371     // Swap the LHS/RHS of the comparison if needed.
1372     std::swap(LHS, RHS);
1373
1374   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
1375   SDValue ARMCC = DAG.getConstant(CondCode, MVT::i32);
1376   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1377   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Flag);
1378   SDValue Ops[] = { Chain, Dest, ARMCC, CCR, Cmp };
1379   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1380   if (CondCode2 != ARMCC::AL) {
1381     ARMCC = DAG.getConstant(CondCode2, MVT::i32);
1382     SDValue Ops[] = { Res, Dest, ARMCC, CCR, Res.getValue(1) };
1383     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
1384   }
1385   return Res;
1386 }
1387
1388 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) {
1389   SDValue Chain = Op.getOperand(0);
1390   SDValue Table = Op.getOperand(1);
1391   SDValue Index = Op.getOperand(2);
1392   DebugLoc dl = Op.getDebugLoc();
1393
1394   MVT PTy = getPointerTy();
1395   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
1396   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
1397   SDValue UId =  DAG.getConstant(AFI->createJumpTableUId(), PTy);
1398   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
1399   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
1400   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
1401   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
1402   bool isPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1403   Addr = DAG.getLoad(isPIC ? (MVT)MVT::i32 : PTy, dl,
1404                      Chain, Addr, NULL, 0);
1405   Chain = Addr.getValue(1);
1406   if (isPIC)
1407     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
1408   return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
1409 }
1410
1411 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1412   DebugLoc dl = Op.getDebugLoc();
1413   unsigned Opc =
1414     Op.getOpcode() == ISD::FP_TO_SINT ? ARMISD::FTOSI : ARMISD::FTOUI;
1415   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
1416   return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
1417 }
1418
1419 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1420   MVT VT = Op.getValueType();
1421   DebugLoc dl = Op.getDebugLoc();
1422   unsigned Opc =
1423     Op.getOpcode() == ISD::SINT_TO_FP ? ARMISD::SITOF : ARMISD::UITOF;
1424
1425   Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Op.getOperand(0));
1426   return DAG.getNode(Opc, dl, VT, Op);
1427 }
1428
1429 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
1430   // Implement fcopysign with a fabs and a conditional fneg.
1431   SDValue Tmp0 = Op.getOperand(0);
1432   SDValue Tmp1 = Op.getOperand(1);
1433   DebugLoc dl = Op.getDebugLoc();
1434   MVT VT = Op.getValueType();
1435   MVT SrcVT = Tmp1.getValueType();
1436   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, VT, Tmp0);
1437   SDValue Cmp = getVFPCmp(Tmp1, DAG.getConstantFP(0.0, SrcVT), DAG, dl);
1438   SDValue ARMCC = DAG.getConstant(ARMCC::LT, MVT::i32);
1439   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
1440   return DAG.getNode(ARMISD::CNEG, dl, VT, AbsVal, AbsVal, ARMCC, CCR, Cmp);
1441 }
1442
1443 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1444   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1445   MFI->setFrameAddressIsTaken(true);
1446   MVT VT = Op.getValueType();
1447   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
1448   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1449   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->useThumbBacktraces())
1450     ? ARM::R7 : ARM::R11;
1451   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1452   while (Depth--)
1453     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
1454   return FrameAddr;
1455 }
1456
1457 SDValue
1458 ARMTargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
1459                                            SDValue Chain,
1460                                            SDValue Dst, SDValue Src,
1461                                            SDValue Size, unsigned Align,
1462                                            bool AlwaysInline,
1463                                          const Value *DstSV, uint64_t DstSVOff,
1464                                          const Value *SrcSV, uint64_t SrcSVOff){
1465   // Do repeated 4-byte loads and stores. To be improved.
1466   // This requires 4-byte alignment.
1467   if ((Align & 3) != 0)
1468     return SDValue();
1469   // This requires the copy size to be a constant, preferrably
1470   // within a subtarget-specific limit.
1471   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
1472   if (!ConstantSize)
1473     return SDValue();
1474   uint64_t SizeVal = ConstantSize->getZExtValue();
1475   if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
1476     return SDValue();
1477
1478   unsigned BytesLeft = SizeVal & 3;
1479   unsigned NumMemOps = SizeVal >> 2;
1480   unsigned EmittedNumMemOps = 0;
1481   MVT VT = MVT::i32;
1482   unsigned VTSize = 4;
1483   unsigned i = 0;
1484   const unsigned MAX_LOADS_IN_LDM = 6;
1485   SDValue TFOps[MAX_LOADS_IN_LDM];
1486   SDValue Loads[MAX_LOADS_IN_LDM];
1487   uint64_t SrcOff = 0, DstOff = 0;
1488
1489   // Emit up to MAX_LOADS_IN_LDM loads, then a TokenFactor barrier, then the
1490   // same number of stores.  The loads and stores will get combined into
1491   // ldm/stm later on.
1492   while (EmittedNumMemOps < NumMemOps) {
1493     for (i = 0;
1494          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1495       Loads[i] = DAG.getLoad(VT, dl, Chain,
1496                              DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1497                                          DAG.getConstant(SrcOff, MVT::i32)),
1498                              SrcSV, SrcSVOff + SrcOff);
1499       TFOps[i] = Loads[i].getValue(1);
1500       SrcOff += VTSize;
1501     }
1502     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1503
1504     for (i = 0;
1505          i < MAX_LOADS_IN_LDM && EmittedNumMemOps + i < NumMemOps; ++i) {
1506       TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1507                            DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1508                                        DAG.getConstant(DstOff, MVT::i32)),
1509                            DstSV, DstSVOff + DstOff);
1510       DstOff += VTSize;
1511     }
1512     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1513
1514     EmittedNumMemOps += i;
1515   }
1516
1517   if (BytesLeft == 0)
1518     return Chain;
1519
1520   // Issue loads / stores for the trailing (1 - 3) bytes.
1521   unsigned BytesLeftSave = BytesLeft;
1522   i = 0;
1523   while (BytesLeft) {
1524     if (BytesLeft >= 2) {
1525       VT = MVT::i16;
1526       VTSize = 2;
1527     } else {
1528       VT = MVT::i8;
1529       VTSize = 1;
1530     }
1531
1532     Loads[i] = DAG.getLoad(VT, dl, Chain,
1533                            DAG.getNode(ISD::ADD, dl, MVT::i32, Src,
1534                                        DAG.getConstant(SrcOff, MVT::i32)),
1535                            SrcSV, SrcSVOff + SrcOff);
1536     TFOps[i] = Loads[i].getValue(1);
1537     ++i;
1538     SrcOff += VTSize;
1539     BytesLeft -= VTSize;
1540   }
1541   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1542
1543   i = 0;
1544   BytesLeft = BytesLeftSave;
1545   while (BytesLeft) {
1546     if (BytesLeft >= 2) {
1547       VT = MVT::i16;
1548       VTSize = 2;
1549     } else {
1550       VT = MVT::i8;
1551       VTSize = 1;
1552     }
1553
1554     TFOps[i] = DAG.getStore(Chain, dl, Loads[i],
1555                             DAG.getNode(ISD::ADD, dl, MVT::i32, Dst,
1556                                         DAG.getConstant(DstOff, MVT::i32)),
1557                             DstSV, DstSVOff + DstOff);
1558     ++i;
1559     DstOff += VTSize;
1560     BytesLeft -= VTSize;
1561   }
1562   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &TFOps[0], i);
1563 }
1564
1565 static SDValue ExpandBIT_CONVERT(SDNode *N, SelectionDAG &DAG) {
1566   SDValue Op = N->getOperand(0);
1567   DebugLoc dl = N->getDebugLoc();
1568   if (N->getValueType(0) == MVT::f64) {
1569     // Turn i64->f64 into FMDRR.
1570     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1571                              DAG.getConstant(0, MVT::i32));
1572     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
1573                              DAG.getConstant(1, MVT::i32));
1574     return DAG.getNode(ARMISD::FMDRR, dl, MVT::f64, Lo, Hi);
1575   }
1576
1577   // Turn f64->i64 into FMRRD.
1578   SDValue Cvt = DAG.getNode(ARMISD::FMRRD, dl,
1579                             DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
1580
1581   // Merge the pieces into a single i64 value.
1582   return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
1583 }
1584
1585 static SDValue ExpandSRx(SDNode *N, SelectionDAG &DAG, const ARMSubtarget *ST) {
1586   assert(N->getValueType(0) == MVT::i64 &&
1587          (N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
1588          "Unknown shift to lower!");
1589
1590   // We only lower SRA, SRL of 1 here, all others use generic lowering.
1591   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
1592       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
1593     return SDValue();
1594
1595   // If we are in thumb mode, we don't have RRX.
1596   if (ST->isThumb()) return SDValue();
1597
1598   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
1599   DebugLoc dl = N->getDebugLoc();
1600   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
1601                              DAG.getConstant(0, MVT::i32));
1602   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
1603                              DAG.getConstant(1, MVT::i32));
1604
1605   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
1606   // captures the result into a carry flag.
1607   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
1608   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Flag), &Hi, 1);
1609
1610   // The low part is an ARMISD::RRX operand, which shifts the carry in.
1611   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
1612
1613   // Merge the pieces into a single i64 value.
1614  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
1615 }
1616
1617 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
1618   switch (Op.getOpcode()) {
1619   default: assert(0 && "Don't know how to custom lower this!"); abort();
1620   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
1621   case ISD::GlobalAddress:
1622     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
1623       LowerGlobalAddressELF(Op, DAG);
1624   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
1625   case ISD::CALL:          return LowerCALL(Op, DAG);
1626   case ISD::RET:           return LowerRET(Op, DAG);
1627   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG, Subtarget);
1628   case ISD::BR_CC:         return LowerBR_CC(Op, DAG, Subtarget);
1629   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
1630   case ISD::VASTART:       return LowerVASTART(Op, DAG, VarArgsFrameIndex);
1631   case ISD::SINT_TO_FP:
1632   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
1633   case ISD::FP_TO_SINT:
1634   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
1635   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
1636   case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
1637   case ISD::RETURNADDR:    break;
1638   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
1639   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
1640   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1641   case ISD::BIT_CONVERT:   return ExpandBIT_CONVERT(Op.getNode(), DAG);
1642   case ISD::SRL:
1643   case ISD::SRA:           return ExpandSRx(Op.getNode(), DAG,Subtarget);
1644   }
1645   return SDValue();
1646 }
1647
1648 /// ReplaceNodeResults - Replace the results of node with an illegal result
1649 /// type with new values built out of custom code.
1650 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
1651                                            SmallVectorImpl<SDValue>&Results,
1652                                            SelectionDAG &DAG) {
1653   switch (N->getOpcode()) {
1654   default:
1655     assert(0 && "Don't know how to custom expand this!");
1656     return;
1657   case ISD::BIT_CONVERT:
1658     Results.push_back(ExpandBIT_CONVERT(N, DAG));
1659     return;
1660   case ISD::SRL:
1661   case ISD::SRA: {
1662     SDValue Res = ExpandSRx(N, DAG, Subtarget);
1663     if (Res.getNode())
1664       Results.push_back(Res);
1665     return;
1666   }
1667   }
1668 }
1669
1670 //===----------------------------------------------------------------------===//
1671 //                           ARM Scheduler Hooks
1672 //===----------------------------------------------------------------------===//
1673
1674 MachineBasicBlock *
1675 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1676                                                MachineBasicBlock *BB) const {
1677   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1678   DebugLoc dl = MI->getDebugLoc();
1679   switch (MI->getOpcode()) {
1680   default: assert(false && "Unexpected instr type to insert");
1681   case ARM::tMOVCCr: {
1682     // To "insert" a SELECT_CC instruction, we actually have to insert the
1683     // diamond control-flow pattern.  The incoming instruction knows the
1684     // destination vreg to set, the condition code register to branch on, the
1685     // true/false values to select between, and a branch opcode to use.
1686     const BasicBlock *LLVM_BB = BB->getBasicBlock();
1687     MachineFunction::iterator It = BB;
1688     ++It;
1689
1690     //  thisMBB:
1691     //  ...
1692     //   TrueVal = ...
1693     //   cmpTY ccX, r1, r2
1694     //   bCC copy1MBB
1695     //   fallthrough --> copy0MBB
1696     MachineBasicBlock *thisMBB  = BB;
1697     MachineFunction *F = BB->getParent();
1698     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1699     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1700     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
1701       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
1702     F->insert(It, copy0MBB);
1703     F->insert(It, sinkMBB);
1704     // Update machine-CFG edges by first adding all successors of the current
1705     // block to the new block which will contain the Phi node for the select.
1706     for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
1707         e = BB->succ_end(); i != e; ++i)
1708       sinkMBB->addSuccessor(*i);
1709     // Next, remove all successors of the current block, and add the true
1710     // and fallthrough blocks as its successors.
1711     while(!BB->succ_empty())
1712       BB->removeSuccessor(BB->succ_begin());
1713     BB->addSuccessor(copy0MBB);
1714     BB->addSuccessor(sinkMBB);
1715
1716     //  copy0MBB:
1717     //   %FalseValue = ...
1718     //   # fallthrough to sinkMBB
1719     BB = copy0MBB;
1720
1721     // Update machine-CFG edges
1722     BB->addSuccessor(sinkMBB);
1723
1724     //  sinkMBB:
1725     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1726     //  ...
1727     BB = sinkMBB;
1728     BuildMI(BB, dl, TII->get(ARM::PHI), MI->getOperand(0).getReg())
1729       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
1730       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
1731
1732     F->DeleteMachineInstr(MI);   // The pseudo instruction is gone now.
1733     return BB;
1734   }
1735   }
1736 }
1737
1738 //===----------------------------------------------------------------------===//
1739 //                           ARM Optimization Hooks
1740 //===----------------------------------------------------------------------===//
1741
1742 static
1743 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
1744                             TargetLowering::DAGCombinerInfo &DCI) {
1745   SelectionDAG &DAG = DCI.DAG;
1746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1747   MVT VT = N->getValueType(0);
1748   unsigned Opc = N->getOpcode();
1749   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
1750   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
1751   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
1752   ISD::CondCode CC = ISD::SETCC_INVALID;
1753
1754   if (isSlctCC) {
1755     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
1756   } else {
1757     SDValue CCOp = Slct.getOperand(0);
1758     if (CCOp.getOpcode() == ISD::SETCC)
1759       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
1760   }
1761
1762   bool DoXform = false;
1763   bool InvCC = false;
1764   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
1765           "Bad input!");
1766
1767   if (LHS.getOpcode() == ISD::Constant &&
1768       cast<ConstantSDNode>(LHS)->isNullValue()) {
1769     DoXform = true;
1770   } else if (CC != ISD::SETCC_INVALID &&
1771              RHS.getOpcode() == ISD::Constant &&
1772              cast<ConstantSDNode>(RHS)->isNullValue()) {
1773     std::swap(LHS, RHS);
1774     SDValue Op0 = Slct.getOperand(0);
1775     MVT OpVT = isSlctCC ? Op0.getValueType() :
1776                           Op0.getOperand(0).getValueType();
1777     bool isInt = OpVT.isInteger();
1778     CC = ISD::getSetCCInverse(CC, isInt);
1779
1780     if (!TLI.isCondCodeLegal(CC, OpVT))
1781       return SDValue();         // Inverse operator isn't legal.
1782
1783     DoXform = true;
1784     InvCC = true;
1785   }
1786
1787   if (DoXform) {
1788     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
1789     if (isSlctCC)
1790       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
1791                              Slct.getOperand(0), Slct.getOperand(1), CC);
1792     SDValue CCOp = Slct.getOperand(0);
1793     if (InvCC)
1794       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
1795                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
1796     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
1797                        CCOp, OtherOp, Result);
1798   }
1799   return SDValue();
1800 }
1801
1802 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
1803 static SDValue PerformADDCombine(SDNode *N,
1804                                  TargetLowering::DAGCombinerInfo &DCI) {
1805   // added by evan in r37685 with no testcase.
1806   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1807
1808   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1809   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
1810     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
1811     if (Result.getNode()) return Result;
1812   }
1813   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1814     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
1815     if (Result.getNode()) return Result;
1816   }
1817
1818   return SDValue();
1819 }
1820
1821 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
1822 static SDValue PerformSUBCombine(SDNode *N,
1823                                  TargetLowering::DAGCombinerInfo &DCI) {
1824   // added by evan in r37685 with no testcase.
1825   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1826
1827   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1828   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1829     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
1830     if (Result.getNode()) return Result;
1831   }
1832
1833   return SDValue();
1834 }
1835
1836
1837 /// PerformFMRRDCombine - Target-specific dag combine xforms for ARMISD::FMRRD.
1838 static SDValue PerformFMRRDCombine(SDNode *N,
1839                                    TargetLowering::DAGCombinerInfo &DCI) {
1840   // fmrrd(fmdrr x, y) -> x,y
1841   SDValue InDouble = N->getOperand(0);
1842   if (InDouble.getOpcode() == ARMISD::FMDRR)
1843     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
1844   return SDValue();
1845 }
1846
1847 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
1848                                              DAGCombinerInfo &DCI) const {
1849   switch (N->getOpcode()) {
1850   default: break;
1851   case ISD::ADD:      return PerformADDCombine(N, DCI);
1852   case ISD::SUB:      return PerformSUBCombine(N, DCI);
1853   case ARMISD::FMRRD: return PerformFMRRDCombine(N, DCI);
1854   }
1855
1856   return SDValue();
1857 }
1858
1859 /// isLegalAddressImmediate - Return true if the integer value can be used
1860 /// as the offset of the target addressing mode for load / store of the
1861 /// given type.
1862 static bool isLegalAddressImmediate(int64_t V, MVT VT,
1863                                     const ARMSubtarget *Subtarget) {
1864   if (V == 0)
1865     return true;
1866
1867   if (!VT.isSimple())
1868     return false;
1869
1870   if (Subtarget->isThumb()) {
1871     if (V < 0)
1872       return false;
1873
1874     unsigned Scale = 1;
1875     switch (VT.getSimpleVT()) {
1876     default: return false;
1877     case MVT::i1:
1878     case MVT::i8:
1879       // Scale == 1;
1880       break;
1881     case MVT::i16:
1882       // Scale == 2;
1883       Scale = 2;
1884       break;
1885     case MVT::i32:
1886       // Scale == 4;
1887       Scale = 4;
1888       break;
1889     }
1890
1891     if ((V & (Scale - 1)) != 0)
1892       return false;
1893     V /= Scale;
1894     return V == (V & ((1LL << 5) - 1));
1895   }
1896
1897   if (V < 0)
1898     V = - V;
1899   switch (VT.getSimpleVT()) {
1900   default: return false;
1901   case MVT::i1:
1902   case MVT::i8:
1903   case MVT::i32:
1904     // +- imm12
1905     return V == (V & ((1LL << 12) - 1));
1906   case MVT::i16:
1907     // +- imm8
1908     return V == (V & ((1LL << 8) - 1));
1909   case MVT::f32:
1910   case MVT::f64:
1911     if (!Subtarget->hasVFP2())
1912       return false;
1913     if ((V & 3) != 0)
1914       return false;
1915     V >>= 2;
1916     return V == (V & ((1LL << 8) - 1));
1917   }
1918 }
1919
1920 /// isLegalAddressingMode - Return true if the addressing mode represented
1921 /// by AM is legal for this target, for a load/store of the specified type.
1922 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
1923                                               const Type *Ty) const {
1924   MVT VT = getValueType(Ty, true);
1925   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
1926     return false;
1927
1928   // Can never fold addr of global into load/store.
1929   if (AM.BaseGV)
1930     return false;
1931
1932   switch (AM.Scale) {
1933   case 0:  // no scale reg, must be "r+i" or "r", or "i".
1934     break;
1935   case 1:
1936     if (Subtarget->isThumb())
1937       return false;
1938     // FALL THROUGH.
1939   default:
1940     // ARM doesn't support any R+R*scale+imm addr modes.
1941     if (AM.BaseOffs)
1942       return false;
1943
1944     if (!VT.isSimple())
1945       return false;
1946
1947     int Scale = AM.Scale;
1948     switch (VT.getSimpleVT()) {
1949     default: return false;
1950     case MVT::i1:
1951     case MVT::i8:
1952     case MVT::i32:
1953     case MVT::i64:
1954       // This assumes i64 is legalized to a pair of i32. If not (i.e.
1955       // ldrd / strd are used, then its address mode is same as i16.
1956       // r + r
1957       if (Scale < 0) Scale = -Scale;
1958       if (Scale == 1)
1959         return true;
1960       // r + r << imm
1961       return isPowerOf2_32(Scale & ~1);
1962     case MVT::i16:
1963       // r + r
1964       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
1965         return true;
1966       return false;
1967
1968     case MVT::isVoid:
1969       // Note, we allow "void" uses (basically, uses that aren't loads or
1970       // stores), because arm allows folding a scale into many arithmetic
1971       // operations.  This should be made more precise and revisited later.
1972
1973       // Allow r << imm, but the imm has to be a multiple of two.
1974       if (AM.Scale & 1) return false;
1975       return isPowerOf2_32(AM.Scale);
1976     }
1977     break;
1978   }
1979   return true;
1980 }
1981
1982 static bool getIndexedAddressParts(SDNode *Ptr, MVT VT,
1983                                    bool isSEXTLoad, SDValue &Base,
1984                                    SDValue &Offset, bool &isInc,
1985                                    SelectionDAG &DAG) {
1986   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
1987     return false;
1988
1989   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
1990     // AddressingMode 3
1991     Base = Ptr->getOperand(0);
1992     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
1993       int RHSC = (int)RHS->getZExtValue();
1994       if (RHSC < 0 && RHSC > -256) {
1995         isInc = false;
1996         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
1997         return true;
1998       }
1999     }
2000     isInc = (Ptr->getOpcode() == ISD::ADD);
2001     Offset = Ptr->getOperand(1);
2002     return true;
2003   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
2004     // AddressingMode 2
2005     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
2006       int RHSC = (int)RHS->getZExtValue();
2007       if (RHSC < 0 && RHSC > -0x1000) {
2008         isInc = false;
2009         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
2010         Base = Ptr->getOperand(0);
2011         return true;
2012       }
2013     }
2014
2015     if (Ptr->getOpcode() == ISD::ADD) {
2016       isInc = true;
2017       ARM_AM::ShiftOpc ShOpcVal= ARM_AM::getShiftOpcForNode(Ptr->getOperand(0));
2018       if (ShOpcVal != ARM_AM::no_shift) {
2019         Base = Ptr->getOperand(1);
2020         Offset = Ptr->getOperand(0);
2021       } else {
2022         Base = Ptr->getOperand(0);
2023         Offset = Ptr->getOperand(1);
2024       }
2025       return true;
2026     }
2027
2028     isInc = (Ptr->getOpcode() == ISD::ADD);
2029     Base = Ptr->getOperand(0);
2030     Offset = Ptr->getOperand(1);
2031     return true;
2032   }
2033
2034   // FIXME: Use FLDM / FSTM to emulate indexed FP load / store.
2035   return false;
2036 }
2037
2038 /// getPreIndexedAddressParts - returns true by value, base pointer and
2039 /// offset pointer and addressing mode by reference if the node's address
2040 /// can be legally represented as pre-indexed load / store address.
2041 bool
2042 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2043                                              SDValue &Offset,
2044                                              ISD::MemIndexedMode &AM,
2045                                              SelectionDAG &DAG) const {
2046   if (Subtarget->isThumb())
2047     return false;
2048
2049   MVT VT;
2050   SDValue Ptr;
2051   bool isSEXTLoad = false;
2052   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2053     Ptr = LD->getBasePtr();
2054     VT  = LD->getMemoryVT();
2055     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
2056   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2057     Ptr = ST->getBasePtr();
2058     VT  = ST->getMemoryVT();
2059   } else
2060     return false;
2061
2062   bool isInc;
2063   bool isLegal = getIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base, Offset,
2064                                         isInc, DAG);
2065   if (isLegal) {
2066     AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
2067     return true;
2068   }
2069   return false;
2070 }
2071
2072 /// getPostIndexedAddressParts - returns true by value, base pointer and
2073 /// offset pointer and addressing mode by reference if this node can be
2074 /// combined with a load / store to form a post-indexed load / store.
2075 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
2076                                                    SDValue &Base,
2077                                                    SDValue &Offset,
2078                                                    ISD::MemIndexedMode &AM,
2079                                                    SelectionDAG &DAG) const {
2080   if (Subtarget->isThumb())
2081     return false;
2082
2083   MVT VT;
2084   SDValue Ptr;
2085   bool isSEXTLoad = false;
2086   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2087     VT  = LD->getMemoryVT();
2088     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
2089   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2090     VT  = ST->getMemoryVT();
2091   } else
2092     return false;
2093
2094   bool isInc;
2095   bool isLegal = getIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
2096                                         isInc, DAG);
2097   if (isLegal) {
2098     AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
2099     return true;
2100   }
2101   return false;
2102 }
2103
2104 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
2105                                                        const APInt &Mask,
2106                                                        APInt &KnownZero,
2107                                                        APInt &KnownOne,
2108                                                        const SelectionDAG &DAG,
2109                                                        unsigned Depth) const {
2110   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
2111   switch (Op.getOpcode()) {
2112   default: break;
2113   case ARMISD::CMOV: {
2114     // Bits are known zero/one if known on the LHS and RHS.
2115     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2116     if (KnownZero == 0 && KnownOne == 0) return;
2117
2118     APInt KnownZeroRHS, KnownOneRHS;
2119     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
2120                           KnownZeroRHS, KnownOneRHS, Depth+1);
2121     KnownZero &= KnownZeroRHS;
2122     KnownOne  &= KnownOneRHS;
2123     return;
2124   }
2125   }
2126 }
2127
2128 //===----------------------------------------------------------------------===//
2129 //                           ARM Inline Assembly Support
2130 //===----------------------------------------------------------------------===//
2131
2132 /// getConstraintType - Given a constraint letter, return the type of
2133 /// constraint it is for this target.
2134 ARMTargetLowering::ConstraintType
2135 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
2136   if (Constraint.size() == 1) {
2137     switch (Constraint[0]) {
2138     default:  break;
2139     case 'l': return C_RegisterClass;
2140     case 'w': return C_RegisterClass;
2141     }
2142   }
2143   return TargetLowering::getConstraintType(Constraint);
2144 }
2145
2146 std::pair<unsigned, const TargetRegisterClass*>
2147 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
2148                                                 MVT VT) const {
2149   if (Constraint.size() == 1) {
2150     // GCC RS6000 Constraint Letters
2151     switch (Constraint[0]) {
2152     case 'l':
2153       if (Subtarget->isThumb())
2154         return std::make_pair(0U, ARM::tGPRRegisterClass);
2155       else
2156         return std::make_pair(0U, ARM::GPRRegisterClass);
2157     case 'r':
2158       return std::make_pair(0U, ARM::GPRRegisterClass);
2159     case 'w':
2160       if (VT == MVT::f32)
2161         return std::make_pair(0U, ARM::SPRRegisterClass);
2162       if (VT == MVT::f64)
2163         return std::make_pair(0U, ARM::DPRRegisterClass);
2164       break;
2165     }
2166   }
2167   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2168 }
2169
2170 std::vector<unsigned> ARMTargetLowering::
2171 getRegClassForInlineAsmConstraint(const std::string &Constraint,
2172                                   MVT VT) const {
2173   if (Constraint.size() != 1)
2174     return std::vector<unsigned>();
2175
2176   switch (Constraint[0]) {      // GCC ARM Constraint Letters
2177   default: break;
2178   case 'l':
2179     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
2180                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
2181                                  0);
2182   case 'r':
2183     return make_vector<unsigned>(ARM::R0, ARM::R1, ARM::R2, ARM::R3,
2184                                  ARM::R4, ARM::R5, ARM::R6, ARM::R7,
2185                                  ARM::R8, ARM::R9, ARM::R10, ARM::R11,
2186                                  ARM::R12, ARM::LR, 0);
2187   case 'w':
2188     if (VT == MVT::f32)
2189       return make_vector<unsigned>(ARM::S0, ARM::S1, ARM::S2, ARM::S3,
2190                                    ARM::S4, ARM::S5, ARM::S6, ARM::S7,
2191                                    ARM::S8, ARM::S9, ARM::S10, ARM::S11,
2192                                    ARM::S12,ARM::S13,ARM::S14,ARM::S15,
2193                                    ARM::S16,ARM::S17,ARM::S18,ARM::S19,
2194                                    ARM::S20,ARM::S21,ARM::S22,ARM::S23,
2195                                    ARM::S24,ARM::S25,ARM::S26,ARM::S27,
2196                                    ARM::S28,ARM::S29,ARM::S30,ARM::S31, 0);
2197     if (VT == MVT::f64)
2198       return make_vector<unsigned>(ARM::D0, ARM::D1, ARM::D2, ARM::D3,
2199                                    ARM::D4, ARM::D5, ARM::D6, ARM::D7,
2200                                    ARM::D8, ARM::D9, ARM::D10,ARM::D11,
2201                                    ARM::D12,ARM::D13,ARM::D14,ARM::D15, 0);
2202       break;
2203   }
2204
2205   return std::vector<unsigned>();
2206 }
2207
2208 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2209 /// vector.  If it is invalid, don't add anything to Ops.
2210 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2211                                                      char Constraint,
2212                                                      bool hasMemory,
2213                                                      std::vector<SDValue>&Ops,
2214                                                      SelectionDAG &DAG) const {
2215   SDValue Result(0, 0);
2216
2217   switch (Constraint) {
2218   default: break;
2219   case 'I': case 'J': case 'K': case 'L':
2220   case 'M': case 'N': case 'O':
2221     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2222     if (!C)
2223       return;
2224
2225     int64_t CVal64 = C->getSExtValue();
2226     int CVal = (int) CVal64;
2227     // None of these constraints allow values larger than 32 bits.  Check
2228     // that the value fits in an int.
2229     if (CVal != CVal64)
2230       return;
2231
2232     switch (Constraint) {
2233       case 'I':
2234         if (Subtarget->isThumb()) {
2235           // This must be a constant between 0 and 255, for ADD immediates.
2236           if (CVal >= 0 && CVal <= 255)
2237             break;
2238         } else {
2239           // A constant that can be used as an immediate value in a
2240           // data-processing instruction.
2241           if (ARM_AM::getSOImmVal(CVal) != -1)
2242             break;
2243         }
2244         return;
2245
2246       case 'J':
2247         if (Subtarget->isThumb()) {
2248           // This must be a constant between -255 and -1, for negated ADD
2249           // immediates. This can be used in GCC with an "n" modifier that
2250           // prints the negated value, for use with SUB instructions. It is
2251           // not useful otherwise but is implemented for compatibility.
2252           if (CVal >= -255 && CVal <= -1)
2253             break;
2254         } else {
2255           // This must be a constant between -4095 and 4095. It is not clear
2256           // what this constraint is intended for. Implemented for
2257           // compatibility with GCC.
2258           if (CVal >= -4095 && CVal <= 4095)
2259             break;
2260         }
2261         return;
2262
2263       case 'K':
2264         if (Subtarget->isThumb()) {
2265           // A 32-bit value where only one byte has a nonzero value. Exclude
2266           // zero to match GCC. This constraint is used by GCC internally for
2267           // constants that can be loaded with a move/shift combination.
2268           // It is not useful otherwise but is implemented for compatibility.
2269           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
2270             break;
2271         } else {
2272           // A constant whose bitwise inverse can be used as an immediate
2273           // value in a data-processing instruction. This can be used in GCC
2274           // with a "B" modifier that prints the inverted value, for use with
2275           // BIC and MVN instructions. It is not useful otherwise but is
2276           // implemented for compatibility.
2277           if (ARM_AM::getSOImmVal(~CVal) != -1)
2278             break;
2279         }
2280         return;
2281
2282       case 'L':
2283         if (Subtarget->isThumb()) {
2284           // This must be a constant between -7 and 7,
2285           // for 3-operand ADD/SUB immediate instructions.
2286           if (CVal >= -7 && CVal < 7)
2287             break;
2288         } else {
2289           // A constant whose negation can be used as an immediate value in a
2290           // data-processing instruction. This can be used in GCC with an "n"
2291           // modifier that prints the negated value, for use with SUB
2292           // instructions. It is not useful otherwise but is implemented for
2293           // compatibility.
2294           if (ARM_AM::getSOImmVal(-CVal) != -1)
2295             break;
2296         }
2297         return;
2298
2299       case 'M':
2300         if (Subtarget->isThumb()) {
2301           // This must be a multiple of 4 between 0 and 1020, for
2302           // ADD sp + immediate.
2303           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
2304             break;
2305         } else {
2306           // A power of two or a constant between 0 and 32.  This is used in
2307           // GCC for the shift amount on shifted register operands, but it is
2308           // useful in general for any shift amounts.
2309           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
2310             break;
2311         }
2312         return;
2313
2314       case 'N':
2315         if (Subtarget->isThumb()) {
2316           // This must be a constant between 0 and 31, for shift amounts.
2317           if (CVal >= 0 && CVal <= 31)
2318             break;
2319         }
2320         return;
2321
2322       case 'O':
2323         if (Subtarget->isThumb()) {
2324           // This must be a multiple of 4 between -508 and 508, for
2325           // ADD/SUB sp = sp + immediate.
2326           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
2327             break;
2328         }
2329         return;
2330     }
2331     Result = DAG.getTargetConstant(CVal, Op.getValueType());
2332     break;
2333   }
2334
2335   if (Result.getNode()) {
2336     Ops.push_back(Result);
2337     return;
2338   }
2339   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
2340                                                       Ops, DAG);
2341 }