Change ARMInstPrinter::printPredicateOperand() so it will not abort if it
[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 #define DEBUG_TYPE "arm-isel"
16 #include "ARM.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMISelLowering.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSubtarget.h"
24 #include "ARMTargetMachine.h"
25 #include "ARMTargetObjectFile.h"
26 #include "MCTargetDesc/ARMAddressingModes.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/Constants.h"
29 #include "llvm/Function.h"
30 #include "llvm/GlobalValue.h"
31 #include "llvm/Instruction.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Type.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/IntrinsicLowering.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFrameInfo.h"
39 #include "llvm/CodeGen/MachineFunction.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineModuleInfo.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/ADT/StringExtras.h"
47 #include "llvm/ADT/Statistic.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include <sstream>
53 using namespace llvm;
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57
58 // This option should go away when tail calls fully work.
59 static cl::opt<bool>
60 EnableARMTailCalls("arm-tail-calls", cl::Hidden,
61   cl::desc("Generate tail calls (TEMPORARY OPTION)."),
62   cl::init(false));
63
64 cl::opt<bool>
65 EnableARMLongCalls("arm-long-calls", cl::Hidden,
66   cl::desc("Generate calls via indirect call instructions"),
67   cl::init(false));
68
69 static cl::opt<bool>
70 ARMInterworking("arm-interworking", cl::Hidden,
71   cl::desc("Enable / disable ARM interworking (for debugging only)"),
72   cl::init(true));
73
74 namespace {
75   class ARMCCState : public CCState {
76   public:
77     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
78                const TargetMachine &TM, SmallVector<CCValAssign, 16> &locs,
79                LLVMContext &C, ParmContext PC)
80         : CCState(CC, isVarArg, MF, TM, locs, C) {
81       assert(((PC == Call) || (PC == Prologue)) &&
82              "ARMCCState users must specify whether their context is call"
83              "or prologue generation.");
84       CallOrPrologue = PC;
85     }
86   };
87 }
88
89 // The APCS parameter registers.
90 static const unsigned GPRArgRegs[] = {
91   ARM::R0, ARM::R1, ARM::R2, ARM::R3
92 };
93
94 void ARMTargetLowering::addTypeForNEON(EVT VT, EVT PromotedLdStVT,
95                                        EVT PromotedBitwiseVT) {
96   if (VT != PromotedLdStVT) {
97     setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
98     AddPromotedToType (ISD::LOAD, VT.getSimpleVT(),
99                        PromotedLdStVT.getSimpleVT());
100
101     setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
102     AddPromotedToType (ISD::STORE, VT.getSimpleVT(),
103                        PromotedLdStVT.getSimpleVT());
104   }
105
106   EVT ElemTy = VT.getVectorElementType();
107   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
108     setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
109   setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
110   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
111   if (ElemTy == MVT::i32) {
112     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Custom);
113     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Custom);
114     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
115     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
116   } else {
117     setOperationAction(ISD::SINT_TO_FP, VT.getSimpleVT(), Expand);
118     setOperationAction(ISD::UINT_TO_FP, VT.getSimpleVT(), Expand);
119     setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Expand);
120     setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Expand);
121   }
122   setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
123   setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
124   setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
125   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Legal);
126   setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
127   setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
128   setOperationAction(ISD::SIGN_EXTEND_INREG, VT.getSimpleVT(), Expand);
129   if (VT.isInteger()) {
130     setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
131     setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
132     setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
133   }
134
135   // Promote all bit-wise operations.
136   if (VT.isInteger() && VT != PromotedBitwiseVT) {
137     setOperationAction(ISD::AND, VT.getSimpleVT(), Promote);
138     AddPromotedToType (ISD::AND, VT.getSimpleVT(),
139                        PromotedBitwiseVT.getSimpleVT());
140     setOperationAction(ISD::OR,  VT.getSimpleVT(), Promote);
141     AddPromotedToType (ISD::OR,  VT.getSimpleVT(),
142                        PromotedBitwiseVT.getSimpleVT());
143     setOperationAction(ISD::XOR, VT.getSimpleVT(), Promote);
144     AddPromotedToType (ISD::XOR, VT.getSimpleVT(),
145                        PromotedBitwiseVT.getSimpleVT());
146   }
147
148   // Neon does not support vector divide/remainder operations.
149   setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
150   setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
151   setOperationAction(ISD::FDIV, VT.getSimpleVT(), Expand);
152   setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
153   setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
154   setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
155 }
156
157 void ARMTargetLowering::addDRTypeForNEON(EVT VT) {
158   addRegisterClass(VT, ARM::DPRRegisterClass);
159   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
160 }
161
162 void ARMTargetLowering::addQRTypeForNEON(EVT VT) {
163   addRegisterClass(VT, ARM::QPRRegisterClass);
164   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
165 }
166
167 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
168   if (TM.getSubtarget<ARMSubtarget>().isTargetDarwin())
169     return new TargetLoweringObjectFileMachO();
170
171   return new ARMElfTargetObjectFile();
172 }
173
174 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
175     : TargetLowering(TM, createTLOF(TM)) {
176   Subtarget = &TM.getSubtarget<ARMSubtarget>();
177   RegInfo = TM.getRegisterInfo();
178   Itins = TM.getInstrItineraryData();
179
180   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
181
182   if (Subtarget->isTargetDarwin()) {
183     // Uses VFP for Thumb libfuncs if available.
184     if (Subtarget->isThumb() && Subtarget->hasVFP2()) {
185       // Single-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
187       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
188       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
189       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
190
191       // Double-precision floating-point arithmetic.
192       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
193       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
194       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
195       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
196
197       // Single-precision comparisons.
198       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
199       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
200       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
201       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
202       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
203       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
204       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
205       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
206
207       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
208       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
209       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
210       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
211       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
212       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
213       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
214       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
215
216       // Double-precision comparisons.
217       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
218       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
219       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
220       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
221       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
222       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
223       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
224       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
225
226       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
227       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
228       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
229       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
230       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
231       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
232       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
233       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
234
235       // Floating-point to integer conversions.
236       // i64 conversions are done via library routines even when generating VFP
237       // instructions, so use the same ones.
238       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
239       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
240       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
241       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
242
243       // Conversions between floating types.
244       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
245       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
246
247       // Integer to floating-point conversions.
248       // i64 conversions are done via library routines even when generating VFP
249       // instructions, so use the same ones.
250       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
251       // e.g., __floatunsidf vs. __floatunssidfvfp.
252       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
253       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
254       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
255       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
256     }
257   }
258
259   // These libcalls are not available in 32-bit.
260   setLibcallName(RTLIB::SHL_I128, 0);
261   setLibcallName(RTLIB::SRL_I128, 0);
262   setLibcallName(RTLIB::SRA_I128, 0);
263
264   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetDarwin()) {
265     // Double-precision floating-point arithmetic helper functions
266     // RTABI chapter 4.1.2, Table 2
267     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
268     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
269     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
270     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
271     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
272     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
273     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
274     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
275
276     // Double-precision floating-point comparison helper functions
277     // RTABI chapter 4.1.2, Table 3
278     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
279     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
280     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
281     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
282     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
283     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
284     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
285     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
286     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
287     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
288     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
289     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
290     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
291     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
292     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
293     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
294     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
295     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
296     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
297     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
298     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
299     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
301     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
302
303     // Single-precision floating-point arithmetic helper functions
304     // RTABI chapter 4.1.2, Table 4
305     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
306     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
307     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
308     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
309     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
310     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
311     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
312     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
313
314     // Single-precision floating-point comparison helper functions
315     // RTABI chapter 4.1.2, Table 5
316     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
317     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
318     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
319     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
320     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
321     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
322     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
323     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
324     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
325     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
326     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
327     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
328     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
329     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
330     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
331     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
332     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
333     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
334     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
335     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
336     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
337     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
338     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
339     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
340
341     // Floating-point to integer conversions.
342     // RTABI chapter 4.1.2, Table 6
343     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
344     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
345     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
346     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
347     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
348     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
349     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
350     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
351     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
352     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
353     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
354     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
356     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
358     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
359
360     // Conversions between floating types.
361     // RTABI chapter 4.1.2, Table 7
362     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
363     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
364     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
365     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
366
367     // Integer to floating-point conversions.
368     // RTABI chapter 4.1.2, Table 8
369     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
370     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
371     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
372     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
373     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
374     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
375     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
376     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
377     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
378     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
379     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
380     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
381     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
382     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
384     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
385
386     // Long long helper functions
387     // RTABI chapter 4.2, Table 9
388     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
389     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
390     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
391     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
392     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
393     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
394     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
395     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
396     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
398
399     // Integer division functions
400     // RTABI chapter 4.3.1
401     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
402     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
403     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
404     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
405     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
406     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
407     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
408     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
409     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
410     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
411     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
412     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
413     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
415     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
416     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
417
418     // Memory operations
419     // RTABI chapter 4.3.4
420     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
421     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
422     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
423     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
424     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
425     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
426   }
427
428   // Use divmod compiler-rt calls for iOS 5.0 and later.
429   if (Subtarget->getTargetTriple().getOS() == Triple::IOS &&
430       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
431     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
432     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
433   }
434
435   if (Subtarget->isThumb1Only())
436     addRegisterClass(MVT::i32, ARM::tGPRRegisterClass);
437   else
438     addRegisterClass(MVT::i32, ARM::GPRRegisterClass);
439   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
440       !Subtarget->isThumb1Only()) {
441     addRegisterClass(MVT::f32, ARM::SPRRegisterClass);
442     if (!Subtarget->isFPOnlySP())
443       addRegisterClass(MVT::f64, ARM::DPRRegisterClass);
444
445     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
446   }
447
448   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
449        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
450     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
452       setTruncStoreAction((MVT::SimpleValueType)VT,
453                           (MVT::SimpleValueType)InnerVT, Expand);
454     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
455     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
456     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
457   }
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     
511     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
512     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
513     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
514     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
516     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
519     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setTargetDAGCombine(ISD::INTRINSIC_VOID);
545     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
546     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
547     setTargetDAGCombine(ISD::SHL);
548     setTargetDAGCombine(ISD::SRL);
549     setTargetDAGCombine(ISD::SRA);
550     setTargetDAGCombine(ISD::SIGN_EXTEND);
551     setTargetDAGCombine(ISD::ZERO_EXTEND);
552     setTargetDAGCombine(ISD::ANY_EXTEND);
553     setTargetDAGCombine(ISD::SELECT_CC);
554     setTargetDAGCombine(ISD::BUILD_VECTOR);
555     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
556     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
557     setTargetDAGCombine(ISD::STORE);
558     setTargetDAGCombine(ISD::FP_TO_SINT);
559     setTargetDAGCombine(ISD::FP_TO_UINT);
560     setTargetDAGCombine(ISD::FDIV);
561
562     // It is legal to extload from v4i8 to v4i16 or v4i32.
563     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
564                   MVT::v4i16, MVT::v2i16,
565                   MVT::v2i32};
566     for (unsigned i = 0; i < 6; ++i) {
567       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
568       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
569       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
570     }
571   }
572
573   computeRegisterProperties();
574
575   // ARM does not have f32 extending load.
576   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
577
578   // ARM does not have i1 sign extending load.
579   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
580
581   // ARM supports all 4 flavors of integer indexed load / store.
582   if (!Subtarget->isThumb1Only()) {
583     for (unsigned im = (unsigned)ISD::PRE_INC;
584          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
585       setIndexedLoadAction(im,  MVT::i1,  Legal);
586       setIndexedLoadAction(im,  MVT::i8,  Legal);
587       setIndexedLoadAction(im,  MVT::i16, Legal);
588       setIndexedLoadAction(im,  MVT::i32, Legal);
589       setIndexedStoreAction(im, MVT::i1,  Legal);
590       setIndexedStoreAction(im, MVT::i8,  Legal);
591       setIndexedStoreAction(im, MVT::i16, Legal);
592       setIndexedStoreAction(im, MVT::i32, Legal);
593     }
594   }
595
596   // i64 operation support.
597   setOperationAction(ISD::MUL,     MVT::i64, Expand);
598   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
599   if (Subtarget->isThumb1Only()) {
600     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
601     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
602   }
603   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
604       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
605     setOperationAction(ISD::MULHS, MVT::i32, Expand);
606
607   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
608   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
609   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
610   setOperationAction(ISD::SRL,       MVT::i64, Custom);
611   setOperationAction(ISD::SRA,       MVT::i64, Custom);
612
613   if (!Subtarget->isThumb1Only()) {
614     // FIXME: We should do this for Thumb1 as well.
615     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
616     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
617     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
618     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
619   }
620
621   // ARM does not have ROTL.
622   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
623   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
624   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
625   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
626     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
627
628   // These just redirect to CTTZ and CTLZ on ARM.
629   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
630   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
631
632   // Only ARMv6 has BSWAP.
633   if (!Subtarget->hasV6Ops())
634     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
635
636   // These are expanded into libcalls.
637   if (!Subtarget->hasDivide() || !Subtarget->isThumb2()) {
638     // v7M has a hardware divider
639     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
640     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
641   }
642   setOperationAction(ISD::SREM,  MVT::i32, Expand);
643   setOperationAction(ISD::UREM,  MVT::i32, Expand);
644   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
645   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
646
647   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
648   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
649   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
650   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
651   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
652
653   setOperationAction(ISD::TRAP, MVT::Other, Legal);
654
655   // Use the default implementation.
656   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
657   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
658   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
659   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
660   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
661   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
662
663   if (!Subtarget->isTargetDarwin()) {
664     // Non-Darwin platforms may return values in these registers via the
665     // personality function.
666     setOperationAction(ISD::EHSELECTION,      MVT::i32,   Expand);
667     setOperationAction(ISD::EXCEPTIONADDR,    MVT::i32,   Expand);
668     setExceptionPointerRegister(ARM::R0);
669     setExceptionSelectorRegister(ARM::R1);
670   }
671
672   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
673   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
674   // the default expansion.
675   // FIXME: This should be checking for v6k, not just v6.
676   if (Subtarget->hasDataBarrier() ||
677       (Subtarget->hasV6Ops() && !Subtarget->isThumb())) {
678     // membarrier needs custom lowering; the rest are legal and handled
679     // normally.
680     setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
681     setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
682     // Custom lowering for 64-bit ops
683     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
684     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
685     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
686     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
687     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
688     setOperationAction(ISD::ATOMIC_SWAP,  MVT::i64, Custom);
689     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
690     // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
691     setInsertFencesForAtomic(true);
692   } else {
693     // Set them all for expansion, which will force libcalls.
694     setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
695     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
696     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
697     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
698     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
699     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
700     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
701     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
702     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
703     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
704     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
705     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
706     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
707     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
708     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
709     // Unordered/Monotonic case.
710     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
711     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
712     // Since the libcalls include locking, fold in the fences
713     setShouldFoldAtomicFences(true);
714   }
715
716   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
717
718   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
719   if (!Subtarget->hasV6Ops()) {
720     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
721     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
722   }
723   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
724
725   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
726       !Subtarget->isThumb1Only()) {
727     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
728     // iff target supports vfp2.
729     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
730     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
731   }
732
733   // We want to custom lower some of our intrinsics.
734   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
735   if (Subtarget->isTargetDarwin()) {
736     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
737     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
738     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
739   }
740
741   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
742   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
743   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
744   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
745   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
746   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
747   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
748   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
749   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
750
751   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
752   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
753   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
754   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
755   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
756
757   // We don't support sin/cos/fmod/copysign/pow
758   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
759   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
760   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
761   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
762   setOperationAction(ISD::FREM,      MVT::f64, Expand);
763   setOperationAction(ISD::FREM,      MVT::f32, Expand);
764   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
765       !Subtarget->isThumb1Only()) {
766     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
767     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
768   }
769   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
770   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
771
772   setOperationAction(ISD::FMA, MVT::f64, Expand);
773   setOperationAction(ISD::FMA, MVT::f32, Expand);
774
775   // Various VFP goodness
776   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
777     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
778     if (Subtarget->hasVFP2()) {
779       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
780       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
781       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
782       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
783     }
784     // Special handling for half-precision FP.
785     if (!Subtarget->hasFP16()) {
786       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
787       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
788     }
789   }
790
791   // We have target-specific dag combine patterns for the following nodes:
792   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
793   setTargetDAGCombine(ISD::ADD);
794   setTargetDAGCombine(ISD::SUB);
795   setTargetDAGCombine(ISD::MUL);
796
797   if (Subtarget->hasV6T2Ops() || Subtarget->hasNEON()) {
798     setTargetDAGCombine(ISD::AND);
799     setTargetDAGCombine(ISD::OR);
800     setTargetDAGCombine(ISD::XOR);
801   }
802
803   if (Subtarget->hasV6Ops())
804     setTargetDAGCombine(ISD::SRL);
805
806   setStackPointerRegisterToSaveRestore(ARM::SP);
807
808   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
809       !Subtarget->hasVFP2())
810     setSchedulingPreference(Sched::RegPressure);
811   else
812     setSchedulingPreference(Sched::Hybrid);
813
814   //// temporary - rewrite interface to use type
815   maxStoresPerMemcpy = maxStoresPerMemcpyOptSize = 1;
816   maxStoresPerMemset = 16;
817   maxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
818
819   // On ARM arguments smaller than 4 bytes are extended, so all arguments
820   // are at least 4 bytes aligned.
821   setMinStackArgumentAlignment(4);
822
823   benefitFromCodePlacementOpt = true;
824
825   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
826 }
827
828 // FIXME: It might make sense to define the representative register class as the
829 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
830 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
831 // SPR's representative would be DPR_VFP2. This should work well if register
832 // pressure tracking were modified such that a register use would increment the
833 // pressure of the register class's representative and all of it's super
834 // classes' representatives transitively. We have not implemented this because
835 // of the difficulty prior to coalescing of modeling operand register classes
836 // due to the common occurrence of cross class copies and subregister insertions
837 // and extractions.
838 std::pair<const TargetRegisterClass*, uint8_t>
839 ARMTargetLowering::findRepresentativeClass(EVT VT) const{
840   const TargetRegisterClass *RRC = 0;
841   uint8_t Cost = 1;
842   switch (VT.getSimpleVT().SimpleTy) {
843   default:
844     return TargetLowering::findRepresentativeClass(VT);
845   // Use DPR as representative register class for all floating point
846   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
847   // the cost is 1 for both f32 and f64.
848   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
849   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
850     RRC = ARM::DPRRegisterClass;
851     // When NEON is used for SP, only half of the register file is available
852     // because operations that define both SP and DP results will be constrained
853     // to the VFP2 class (D0-D15). We currently model this constraint prior to
854     // coalescing by double-counting the SP regs. See the FIXME above.
855     if (Subtarget->useNEONForSinglePrecisionFP())
856       Cost = 2;
857     break;
858   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
859   case MVT::v4f32: case MVT::v2f64:
860     RRC = ARM::DPRRegisterClass;
861     Cost = 2;
862     break;
863   case MVT::v4i64:
864     RRC = ARM::DPRRegisterClass;
865     Cost = 4;
866     break;
867   case MVT::v8i64:
868     RRC = ARM::DPRRegisterClass;
869     Cost = 8;
870     break;
871   }
872   return std::make_pair(RRC, Cost);
873 }
874
875 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
876   switch (Opcode) {
877   default: return 0;
878   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
879   case ARMISD::WrapperDYN:    return "ARMISD::WrapperDYN";
880   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
881   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
882   case ARMISD::CALL:          return "ARMISD::CALL";
883   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
884   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
885   case ARMISD::tCALL:         return "ARMISD::tCALL";
886   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
887   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
888   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
889   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
890   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
891   case ARMISD::CMP:           return "ARMISD::CMP";
892   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
893   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
894   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
895   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
896   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
897
898   case ARMISD::CMOV:          return "ARMISD::CMOV";
899   case ARMISD::CAND:          return "ARMISD::CAND";
900   case ARMISD::COR:           return "ARMISD::COR";
901   case ARMISD::CXOR:          return "ARMISD::CXOR";
902
903   case ARMISD::RBIT:          return "ARMISD::RBIT";
904
905   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
906   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
907   case ARMISD::SITOF:         return "ARMISD::SITOF";
908   case ARMISD::UITOF:         return "ARMISD::UITOF";
909
910   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
911   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
912   case ARMISD::RRX:           return "ARMISD::RRX";
913
914   case ARMISD::ADDC:          return "ARMISD::ADDC";
915   case ARMISD::ADDE:          return "ARMISD::ADDE";
916   case ARMISD::SUBC:          return "ARMISD::SUBC";
917   case ARMISD::SUBE:          return "ARMISD::SUBE";
918
919   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
920   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
921
922   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
923   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
924
925   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
926
927   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
928
929   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
930
931   case ARMISD::MEMBARRIER:    return "ARMISD::MEMBARRIER";
932   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
933
934   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
935
936   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
937   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
938   case ARMISD::VCGE:          return "ARMISD::VCGE";
939   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
940   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
941   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
942   case ARMISD::VCGT:          return "ARMISD::VCGT";
943   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
944   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
945   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
946   case ARMISD::VTST:          return "ARMISD::VTST";
947
948   case ARMISD::VSHL:          return "ARMISD::VSHL";
949   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
950   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
951   case ARMISD::VSHLLs:        return "ARMISD::VSHLLs";
952   case ARMISD::VSHLLu:        return "ARMISD::VSHLLu";
953   case ARMISD::VSHLLi:        return "ARMISD::VSHLLi";
954   case ARMISD::VSHRN:         return "ARMISD::VSHRN";
955   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
956   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
957   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
958   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
959   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
960   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
961   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
962   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
963   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
964   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
965   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
966   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
967   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
968   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
969   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
970   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
971   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
972   case ARMISD::VDUP:          return "ARMISD::VDUP";
973   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
974   case ARMISD::VEXT:          return "ARMISD::VEXT";
975   case ARMISD::VREV64:        return "ARMISD::VREV64";
976   case ARMISD::VREV32:        return "ARMISD::VREV32";
977   case ARMISD::VREV16:        return "ARMISD::VREV16";
978   case ARMISD::VZIP:          return "ARMISD::VZIP";
979   case ARMISD::VUZP:          return "ARMISD::VUZP";
980   case ARMISD::VTRN:          return "ARMISD::VTRN";
981   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
982   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
983   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
984   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
985   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
986   case ARMISD::FMAX:          return "ARMISD::FMAX";
987   case ARMISD::FMIN:          return "ARMISD::FMIN";
988   case ARMISD::BFI:           return "ARMISD::BFI";
989   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
990   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
991   case ARMISD::VBSL:          return "ARMISD::VBSL";
992   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
993   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
994   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
995   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
996   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
997   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
998   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
999   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1000   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1001   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1002   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1003   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1004   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1005   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1006   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1007   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1008   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1009   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1010   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1011   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1012   }
1013 }
1014
1015 EVT ARMTargetLowering::getSetCCResultType(EVT VT) const {
1016   if (!VT.isVector()) return getPointerTy();
1017   return VT.changeVectorElementTypeToInteger();
1018 }
1019
1020 /// getRegClassFor - Return the register class that should be used for the
1021 /// specified value type.
1022 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(EVT VT) const {
1023   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1024   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1025   // load / store 4 to 8 consecutive D registers.
1026   if (Subtarget->hasNEON()) {
1027     if (VT == MVT::v4i64)
1028       return ARM::QQPRRegisterClass;
1029     else if (VT == MVT::v8i64)
1030       return ARM::QQQQPRRegisterClass;
1031   }
1032   return TargetLowering::getRegClassFor(VT);
1033 }
1034
1035 // Create a fast isel object.
1036 FastISel *
1037 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
1038   return ARM::createFastISel(funcInfo);
1039 }
1040
1041 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1042 /// be used for loads / stores from the global.
1043 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1044   return (Subtarget->isThumb1Only() ? 127 : 4095);
1045 }
1046
1047 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1048   unsigned NumVals = N->getNumValues();
1049   if (!NumVals)
1050     return Sched::RegPressure;
1051
1052   for (unsigned i = 0; i != NumVals; ++i) {
1053     EVT VT = N->getValueType(i);
1054     if (VT == MVT::Glue || VT == MVT::Other)
1055       continue;
1056     if (VT.isFloatingPoint() || VT.isVector())
1057       return Sched::ILP;
1058   }
1059
1060   if (!N->isMachineOpcode())
1061     return Sched::RegPressure;
1062
1063   // Load are scheduled for latency even if there instruction itinerary
1064   // is not available.
1065   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1066   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1067
1068   if (MCID.getNumDefs() == 0)
1069     return Sched::RegPressure;
1070   if (!Itins->isEmpty() &&
1071       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1072     return Sched::ILP;
1073
1074   return Sched::RegPressure;
1075 }
1076
1077 //===----------------------------------------------------------------------===//
1078 // Lowering Code
1079 //===----------------------------------------------------------------------===//
1080
1081 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1082 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1083   switch (CC) {
1084   default: llvm_unreachable("Unknown condition code!");
1085   case ISD::SETNE:  return ARMCC::NE;
1086   case ISD::SETEQ:  return ARMCC::EQ;
1087   case ISD::SETGT:  return ARMCC::GT;
1088   case ISD::SETGE:  return ARMCC::GE;
1089   case ISD::SETLT:  return ARMCC::LT;
1090   case ISD::SETLE:  return ARMCC::LE;
1091   case ISD::SETUGT: return ARMCC::HI;
1092   case ISD::SETUGE: return ARMCC::HS;
1093   case ISD::SETULT: return ARMCC::LO;
1094   case ISD::SETULE: return ARMCC::LS;
1095   }
1096 }
1097
1098 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1099 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1100                         ARMCC::CondCodes &CondCode2) {
1101   CondCode2 = ARMCC::AL;
1102   switch (CC) {
1103   default: llvm_unreachable("Unknown FP condition!");
1104   case ISD::SETEQ:
1105   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1106   case ISD::SETGT:
1107   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1108   case ISD::SETGE:
1109   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1110   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1111   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1112   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1113   case ISD::SETO:   CondCode = ARMCC::VC; break;
1114   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1115   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1116   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1117   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1118   case ISD::SETLT:
1119   case ISD::SETULT: CondCode = ARMCC::LT; break;
1120   case ISD::SETLE:
1121   case ISD::SETULE: CondCode = ARMCC::LE; break;
1122   case ISD::SETNE:
1123   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1124   }
1125 }
1126
1127 //===----------------------------------------------------------------------===//
1128 //                      Calling Convention Implementation
1129 //===----------------------------------------------------------------------===//
1130
1131 #include "ARMGenCallingConv.inc"
1132
1133 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1134 /// given CallingConvention value.
1135 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1136                                                  bool Return,
1137                                                  bool isVarArg) const {
1138   switch (CC) {
1139   default:
1140     llvm_unreachable("Unsupported calling convention");
1141   case CallingConv::Fast:
1142     if (Subtarget->hasVFP2() && !isVarArg) {
1143       if (!Subtarget->isAAPCS_ABI())
1144         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1145       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1146       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1147     }
1148     // Fallthrough
1149   case CallingConv::C: {
1150     // Use target triple & subtarget features to do actual dispatch.
1151     if (!Subtarget->isAAPCS_ABI())
1152       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1153     else if (Subtarget->hasVFP2() &&
1154              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1155              !isVarArg)
1156       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1157     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1158   }
1159   case CallingConv::ARM_AAPCS_VFP:
1160     if (!isVarArg)
1161       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1162     // Fallthrough
1163   case CallingConv::ARM_AAPCS:
1164     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1165   case CallingConv::ARM_APCS:
1166     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1167   }
1168 }
1169
1170 /// LowerCallResult - Lower the result values of a call into the
1171 /// appropriate copies out of appropriate physical registers.
1172 SDValue
1173 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1174                                    CallingConv::ID CallConv, bool isVarArg,
1175                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1176                                    DebugLoc dl, SelectionDAG &DAG,
1177                                    SmallVectorImpl<SDValue> &InVals) const {
1178
1179   // Assign locations to each value returned by this call.
1180   SmallVector<CCValAssign, 16> RVLocs;
1181   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1182                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1183   CCInfo.AnalyzeCallResult(Ins,
1184                            CCAssignFnForNode(CallConv, /* Return*/ true,
1185                                              isVarArg));
1186
1187   // Copy all of the result registers out of their specified physreg.
1188   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1189     CCValAssign VA = RVLocs[i];
1190
1191     SDValue Val;
1192     if (VA.needsCustom()) {
1193       // Handle f64 or half of a v2f64.
1194       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1195                                       InFlag);
1196       Chain = Lo.getValue(1);
1197       InFlag = Lo.getValue(2);
1198       VA = RVLocs[++i]; // skip ahead to next loc
1199       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1200                                       InFlag);
1201       Chain = Hi.getValue(1);
1202       InFlag = Hi.getValue(2);
1203       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1204
1205       if (VA.getLocVT() == MVT::v2f64) {
1206         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1207         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1208                           DAG.getConstant(0, MVT::i32));
1209
1210         VA = RVLocs[++i]; // skip ahead to next loc
1211         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1212         Chain = Lo.getValue(1);
1213         InFlag = Lo.getValue(2);
1214         VA = RVLocs[++i]; // skip ahead to next loc
1215         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1216         Chain = Hi.getValue(1);
1217         InFlag = Hi.getValue(2);
1218         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1219         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1220                           DAG.getConstant(1, MVT::i32));
1221       }
1222     } else {
1223       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1224                                InFlag);
1225       Chain = Val.getValue(1);
1226       InFlag = Val.getValue(2);
1227     }
1228
1229     switch (VA.getLocInfo()) {
1230     default: llvm_unreachable("Unknown loc info!");
1231     case CCValAssign::Full: break;
1232     case CCValAssign::BCvt:
1233       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1234       break;
1235     }
1236
1237     InVals.push_back(Val);
1238   }
1239
1240   return Chain;
1241 }
1242
1243 /// LowerMemOpCallTo - Store the argument to the stack.
1244 SDValue
1245 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1246                                     SDValue StackPtr, SDValue Arg,
1247                                     DebugLoc dl, SelectionDAG &DAG,
1248                                     const CCValAssign &VA,
1249                                     ISD::ArgFlagsTy Flags) const {
1250   unsigned LocMemOffset = VA.getLocMemOffset();
1251   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1252   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1253   return DAG.getStore(Chain, dl, Arg, PtrOff,
1254                       MachinePointerInfo::getStack(LocMemOffset),
1255                       false, false, 0);
1256 }
1257
1258 void ARMTargetLowering::PassF64ArgInRegs(DebugLoc dl, SelectionDAG &DAG,
1259                                          SDValue Chain, SDValue &Arg,
1260                                          RegsToPassVector &RegsToPass,
1261                                          CCValAssign &VA, CCValAssign &NextVA,
1262                                          SDValue &StackPtr,
1263                                          SmallVector<SDValue, 8> &MemOpChains,
1264                                          ISD::ArgFlagsTy Flags) const {
1265
1266   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1267                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1268   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1269
1270   if (NextVA.isRegLoc())
1271     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1272   else {
1273     assert(NextVA.isMemLoc());
1274     if (StackPtr.getNode() == 0)
1275       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1276
1277     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1278                                            dl, DAG, NextVA,
1279                                            Flags));
1280   }
1281 }
1282
1283 /// LowerCall - Lowering a call into a callseq_start <-
1284 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1285 /// nodes.
1286 SDValue
1287 ARMTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1288                              CallingConv::ID CallConv, bool isVarArg,
1289                              bool doesNotRet, bool &isTailCall,
1290                              const SmallVectorImpl<ISD::OutputArg> &Outs,
1291                              const SmallVectorImpl<SDValue> &OutVals,
1292                              const SmallVectorImpl<ISD::InputArg> &Ins,
1293                              DebugLoc dl, SelectionDAG &DAG,
1294                              SmallVectorImpl<SDValue> &InVals) const {
1295   MachineFunction &MF = DAG.getMachineFunction();
1296   bool IsStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1297   bool IsSibCall = false;
1298   // Disable tail calls if they're not supported.
1299   if (!EnableARMTailCalls && !Subtarget->supportsTailCall())
1300     isTailCall = false;
1301   if (isTailCall) {
1302     // Check if it's really possible to do a tail call.
1303     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1304                     isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1305                                                    Outs, OutVals, Ins, DAG);
1306     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1307     // detected sibcalls.
1308     if (isTailCall) {
1309       ++NumTailCalls;
1310       IsSibCall = true;
1311     }
1312   }
1313
1314   // Analyze operands of the call, assigning locations to each operand.
1315   SmallVector<CCValAssign, 16> ArgLocs;
1316   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1317                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1318   CCInfo.AnalyzeCallOperands(Outs,
1319                              CCAssignFnForNode(CallConv, /* Return*/ false,
1320                                                isVarArg));
1321
1322   // Get a count of how many bytes are to be pushed on the stack.
1323   unsigned NumBytes = CCInfo.getNextStackOffset();
1324
1325   // For tail calls, memory operands are available in our caller's stack.
1326   if (IsSibCall)
1327     NumBytes = 0;
1328
1329   // Adjust the stack pointer for the new arguments...
1330   // These operations are automatically eliminated by the prolog/epilog pass
1331   if (!IsSibCall)
1332     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1333
1334   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1335
1336   RegsToPassVector RegsToPass;
1337   SmallVector<SDValue, 8> MemOpChains;
1338
1339   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1340   // of tail call optimization, arguments are handled later.
1341   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1342        i != e;
1343        ++i, ++realArgIdx) {
1344     CCValAssign &VA = ArgLocs[i];
1345     SDValue Arg = OutVals[realArgIdx];
1346     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1347     bool isByVal = Flags.isByVal();
1348
1349     // Promote the value if needed.
1350     switch (VA.getLocInfo()) {
1351     default: llvm_unreachable("Unknown loc info!");
1352     case CCValAssign::Full: break;
1353     case CCValAssign::SExt:
1354       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1355       break;
1356     case CCValAssign::ZExt:
1357       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1358       break;
1359     case CCValAssign::AExt:
1360       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1361       break;
1362     case CCValAssign::BCvt:
1363       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1364       break;
1365     }
1366
1367     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1368     if (VA.needsCustom()) {
1369       if (VA.getLocVT() == MVT::v2f64) {
1370         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1371                                   DAG.getConstant(0, MVT::i32));
1372         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1373                                   DAG.getConstant(1, MVT::i32));
1374
1375         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1376                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1377
1378         VA = ArgLocs[++i]; // skip ahead to next loc
1379         if (VA.isRegLoc()) {
1380           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1381                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1382         } else {
1383           assert(VA.isMemLoc());
1384
1385           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1386                                                  dl, DAG, VA, Flags));
1387         }
1388       } else {
1389         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1390                          StackPtr, MemOpChains, Flags);
1391       }
1392     } else if (VA.isRegLoc()) {
1393       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1394     } else if (isByVal) {
1395       assert(VA.isMemLoc());
1396       unsigned offset = 0;
1397
1398       // True if this byval aggregate will be split between registers
1399       // and memory.
1400       if (CCInfo.isFirstByValRegValid()) {
1401         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1402         unsigned int i, j;
1403         for (i = 0, j = CCInfo.getFirstByValReg(); j < ARM::R4; i++, j++) {
1404           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1405           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1406           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1407                                      MachinePointerInfo(),
1408                                      false, false, false, 0);
1409           MemOpChains.push_back(Load.getValue(1));
1410           RegsToPass.push_back(std::make_pair(j, Load));
1411         }
1412         offset = ARM::R4 - CCInfo.getFirstByValReg();
1413         CCInfo.clearFirstByValReg();
1414       }
1415
1416       unsigned LocMemOffset = VA.getLocMemOffset();
1417       SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418       SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1419                                 StkPtrOff);
1420       SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1421       SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1422       SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1423                                          MVT::i32);
1424       MemOpChains.push_back(DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
1425                                           Flags.getByValAlign(),
1426                                           /*isVolatile=*/false,
1427                                           /*AlwaysInline=*/false,
1428                                           MachinePointerInfo(0),
1429                                           MachinePointerInfo(0)));
1430
1431     } else if (!IsSibCall) {
1432       assert(VA.isMemLoc());
1433
1434       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1435                                              dl, DAG, VA, Flags));
1436     }
1437   }
1438
1439   if (!MemOpChains.empty())
1440     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1441                         &MemOpChains[0], MemOpChains.size());
1442
1443   // Build a sequence of copy-to-reg nodes chained together with token chain
1444   // and flag operands which copy the outgoing args into the appropriate regs.
1445   SDValue InFlag;
1446   // Tail call byval lowering might overwrite argument registers so in case of
1447   // tail call optimization the copies to registers are lowered later.
1448   if (!isTailCall)
1449     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1450       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1451                                RegsToPass[i].second, InFlag);
1452       InFlag = Chain.getValue(1);
1453     }
1454
1455   // For tail calls lower the arguments to the 'real' stack slot.
1456   if (isTailCall) {
1457     // Force all the incoming stack arguments to be loaded from the stack
1458     // before any new outgoing arguments are stored to the stack, because the
1459     // outgoing stack slots may alias the incoming argument stack slots, and
1460     // the alias isn't otherwise explicit. This is slightly more conservative
1461     // than necessary, because it means that each store effectively depends
1462     // on every argument instead of just those arguments it would clobber.
1463
1464     // Do not flag preceding copytoreg stuff together with the following stuff.
1465     InFlag = SDValue();
1466     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1467       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1468                                RegsToPass[i].second, InFlag);
1469       InFlag = Chain.getValue(1);
1470     }
1471     InFlag =SDValue();
1472   }
1473
1474   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1475   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1476   // node so that legalize doesn't hack it.
1477   bool isDirect = false;
1478   bool isARMFunc = false;
1479   bool isLocalARMFunc = false;
1480   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1481
1482   if (EnableARMLongCalls) {
1483     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1484             && "long-calls with non-static relocation model!");
1485     // Handle a global address or an external symbol. If it's not one of
1486     // those, the target's already in a register, so we don't need to do
1487     // anything extra.
1488     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1489       const GlobalValue *GV = G->getGlobal();
1490       // Create a constant pool entry for the callee address
1491       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1492       ARMConstantPoolValue *CPV =
1493         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1494
1495       // Get the address of the callee into a register
1496       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1497       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1498       Callee = DAG.getLoad(getPointerTy(), dl,
1499                            DAG.getEntryNode(), CPAddr,
1500                            MachinePointerInfo::getConstantPool(),
1501                            false, false, false, 0);
1502     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1503       const char *Sym = S->getSymbol();
1504
1505       // Create a constant pool entry for the callee address
1506       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1507       ARMConstantPoolValue *CPV =
1508         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1509                                       ARMPCLabelIndex, 0);
1510       // Get the address of the callee into a register
1511       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1512       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1513       Callee = DAG.getLoad(getPointerTy(), dl,
1514                            DAG.getEntryNode(), CPAddr,
1515                            MachinePointerInfo::getConstantPool(),
1516                            false, false, false, 0);
1517     }
1518   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1519     const GlobalValue *GV = G->getGlobal();
1520     isDirect = true;
1521     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1522     bool isStub = (isExt && Subtarget->isTargetDarwin()) &&
1523                    getTargetMachine().getRelocationModel() != Reloc::Static;
1524     isARMFunc = !Subtarget->isThumb() || isStub;
1525     // ARM call to a local ARM function is predicable.
1526     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1527     // tBX takes a register source operand.
1528     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1529       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1530       ARMConstantPoolValue *CPV =
1531         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 4);
1532       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1533       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1534       Callee = DAG.getLoad(getPointerTy(), dl,
1535                            DAG.getEntryNode(), CPAddr,
1536                            MachinePointerInfo::getConstantPool(),
1537                            false, false, false, 0);
1538       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1539       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1540                            getPointerTy(), Callee, PICLabel);
1541     } else {
1542       // On ELF targets for PIC code, direct calls should go through the PLT
1543       unsigned OpFlags = 0;
1544       if (Subtarget->isTargetELF() &&
1545                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1546         OpFlags = ARMII::MO_PLT;
1547       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1548     }
1549   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1550     isDirect = true;
1551     bool isStub = Subtarget->isTargetDarwin() &&
1552                   getTargetMachine().getRelocationModel() != Reloc::Static;
1553     isARMFunc = !Subtarget->isThumb() || isStub;
1554     // tBX takes a register source operand.
1555     const char *Sym = S->getSymbol();
1556     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1557       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1558       ARMConstantPoolValue *CPV =
1559         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1560                                       ARMPCLabelIndex, 4);
1561       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1562       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1563       Callee = DAG.getLoad(getPointerTy(), dl,
1564                            DAG.getEntryNode(), CPAddr,
1565                            MachinePointerInfo::getConstantPool(),
1566                            false, false, false, 0);
1567       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1568       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1569                            getPointerTy(), Callee, PICLabel);
1570     } else {
1571       unsigned OpFlags = 0;
1572       // On ELF targets for PIC code, direct calls should go through the PLT
1573       if (Subtarget->isTargetELF() &&
1574                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1575         OpFlags = ARMII::MO_PLT;
1576       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1577     }
1578   }
1579
1580   // FIXME: handle tail calls differently.
1581   unsigned CallOpc;
1582   if (Subtarget->isThumb()) {
1583     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1584       CallOpc = ARMISD::CALL_NOLINK;
1585     else if (doesNotRet && isDirect && !isARMFunc &&
1586              Subtarget->hasRAS() && !Subtarget->isThumb1Only())
1587       // "mov lr, pc; b _foo" to avoid confusing the RSP
1588       CallOpc = ARMISD::CALL_NOLINK;
1589     else
1590       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1591   } else {
1592     if (!isDirect && !Subtarget->hasV5TOps()) {
1593       CallOpc = ARMISD::CALL_NOLINK;
1594     } else if (doesNotRet && isDirect && Subtarget->hasRAS())
1595       // "mov lr, pc; b _foo" to avoid confusing the RSP
1596       CallOpc = ARMISD::CALL_NOLINK;
1597     else
1598       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1599   }
1600
1601   std::vector<SDValue> Ops;
1602   Ops.push_back(Chain);
1603   Ops.push_back(Callee);
1604
1605   // Add argument registers to the end of the list so that they are known live
1606   // into the call.
1607   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1608     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1609                                   RegsToPass[i].second.getValueType()));
1610
1611   // Add a register mask operand representing the call-preserved registers.
1612   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1613   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
1614   assert(Mask && "Missing call preserved mask for calling convention");
1615   Ops.push_back(DAG.getRegisterMask(Mask));
1616
1617   if (InFlag.getNode())
1618     Ops.push_back(InFlag);
1619
1620   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1621   if (isTailCall)
1622     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1623
1624   // Returns a chain and a flag for retval copy to use.
1625   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1626   InFlag = Chain.getValue(1);
1627
1628   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1629                              DAG.getIntPtrConstant(0, true), InFlag);
1630   if (!Ins.empty())
1631     InFlag = Chain.getValue(1);
1632
1633   // Handle result values, copying them out of physregs into vregs that we
1634   // return.
1635   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins,
1636                          dl, DAG, InVals);
1637 }
1638
1639 /// HandleByVal - Every parameter *after* a byval parameter is passed
1640 /// on the stack.  Remember the next parameter register to allocate,
1641 /// and then confiscate the rest of the parameter registers to insure
1642 /// this.
1643 void
1644 llvm::ARMTargetLowering::HandleByVal(CCState *State, unsigned &size) const {
1645   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1646   assert((State->getCallOrPrologue() == Prologue ||
1647           State->getCallOrPrologue() == Call) &&
1648          "unhandled ParmContext");
1649   if ((!State->isFirstByValRegValid()) &&
1650       (ARM::R0 <= reg) && (reg <= ARM::R3)) {
1651     State->setFirstByValReg(reg);
1652     // At a call site, a byval parameter that is split between
1653     // registers and memory needs its size truncated here.  In a
1654     // function prologue, such byval parameters are reassembled in
1655     // memory, and are not truncated.
1656     if (State->getCallOrPrologue() == Call) {
1657       unsigned excess = 4 * (ARM::R4 - reg);
1658       assert(size >= excess && "expected larger existing stack allocation");
1659       size -= excess;
1660     }
1661   }
1662   // Confiscate any remaining parameter registers to preclude their
1663   // assignment to subsequent parameters.
1664   while (State->AllocateReg(GPRArgRegs, 4))
1665     ;
1666 }
1667
1668 /// MatchingStackOffset - Return true if the given stack call argument is
1669 /// already available in the same position (relatively) of the caller's
1670 /// incoming argument stack.
1671 static
1672 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1673                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1674                          const ARMInstrInfo *TII) {
1675   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1676   int FI = INT_MAX;
1677   if (Arg.getOpcode() == ISD::CopyFromReg) {
1678     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1679     if (!TargetRegisterInfo::isVirtualRegister(VR))
1680       return false;
1681     MachineInstr *Def = MRI->getVRegDef(VR);
1682     if (!Def)
1683       return false;
1684     if (!Flags.isByVal()) {
1685       if (!TII->isLoadFromStackSlot(Def, FI))
1686         return false;
1687     } else {
1688       return false;
1689     }
1690   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1691     if (Flags.isByVal())
1692       // ByVal argument is passed in as a pointer but it's now being
1693       // dereferenced. e.g.
1694       // define @foo(%struct.X* %A) {
1695       //   tail call @bar(%struct.X* byval %A)
1696       // }
1697       return false;
1698     SDValue Ptr = Ld->getBasePtr();
1699     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1700     if (!FINode)
1701       return false;
1702     FI = FINode->getIndex();
1703   } else
1704     return false;
1705
1706   assert(FI != INT_MAX);
1707   if (!MFI->isFixedObjectIndex(FI))
1708     return false;
1709   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1710 }
1711
1712 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1713 /// for tail call optimization. Targets which want to do tail call
1714 /// optimization should implement this function.
1715 bool
1716 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1717                                                      CallingConv::ID CalleeCC,
1718                                                      bool isVarArg,
1719                                                      bool isCalleeStructRet,
1720                                                      bool isCallerStructRet,
1721                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1722                                     const SmallVectorImpl<SDValue> &OutVals,
1723                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1724                                                      SelectionDAG& DAG) const {
1725   const Function *CallerF = DAG.getMachineFunction().getFunction();
1726   CallingConv::ID CallerCC = CallerF->getCallingConv();
1727   bool CCMatch = CallerCC == CalleeCC;
1728
1729   // Look for obvious safe cases to perform tail call optimization that do not
1730   // require ABI changes. This is what gcc calls sibcall.
1731
1732   // Do not sibcall optimize vararg calls unless the call site is not passing
1733   // any arguments.
1734   if (isVarArg && !Outs.empty())
1735     return false;
1736
1737   // Also avoid sibcall optimization if either caller or callee uses struct
1738   // return semantics.
1739   if (isCalleeStructRet || isCallerStructRet)
1740     return false;
1741
1742   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1743   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1744   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1745   // support in the assembler and linker to be used. This would need to be
1746   // fixed to fully support tail calls in Thumb1.
1747   //
1748   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1749   // LR.  This means if we need to reload LR, it takes an extra instructions,
1750   // which outweighs the value of the tail call; but here we don't know yet
1751   // whether LR is going to be used.  Probably the right approach is to
1752   // generate the tail call here and turn it back into CALL/RET in
1753   // emitEpilogue if LR is used.
1754
1755   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1756   // but we need to make sure there are enough registers; the only valid
1757   // registers are the 4 used for parameters.  We don't currently do this
1758   // case.
1759   if (Subtarget->isThumb1Only())
1760     return false;
1761
1762   // If the calling conventions do not match, then we'd better make sure the
1763   // results are returned in the same way as what the caller expects.
1764   if (!CCMatch) {
1765     SmallVector<CCValAssign, 16> RVLocs1;
1766     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1767                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1768     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1769
1770     SmallVector<CCValAssign, 16> RVLocs2;
1771     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1772                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1773     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1774
1775     if (RVLocs1.size() != RVLocs2.size())
1776       return false;
1777     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1778       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1779         return false;
1780       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1781         return false;
1782       if (RVLocs1[i].isRegLoc()) {
1783         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1784           return false;
1785       } else {
1786         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1787           return false;
1788       }
1789     }
1790   }
1791
1792   // If the callee takes no arguments then go on to check the results of the
1793   // call.
1794   if (!Outs.empty()) {
1795     // Check if stack adjustment is needed. For now, do not do this if any
1796     // argument is passed on the stack.
1797     SmallVector<CCValAssign, 16> ArgLocs;
1798     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1799                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1800     CCInfo.AnalyzeCallOperands(Outs,
1801                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1802     if (CCInfo.getNextStackOffset()) {
1803       MachineFunction &MF = DAG.getMachineFunction();
1804
1805       // Check if the arguments are already laid out in the right way as
1806       // the caller's fixed stack objects.
1807       MachineFrameInfo *MFI = MF.getFrameInfo();
1808       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1809       const ARMInstrInfo *TII =
1810         ((ARMTargetMachine&)getTargetMachine()).getInstrInfo();
1811       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1812            i != e;
1813            ++i, ++realArgIdx) {
1814         CCValAssign &VA = ArgLocs[i];
1815         EVT RegVT = VA.getLocVT();
1816         SDValue Arg = OutVals[realArgIdx];
1817         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1818         if (VA.getLocInfo() == CCValAssign::Indirect)
1819           return false;
1820         if (VA.needsCustom()) {
1821           // f64 and vector types are split into multiple registers or
1822           // register/stack-slot combinations.  The types will not match
1823           // the registers; give up on memory f64 refs until we figure
1824           // out what to do about this.
1825           if (!VA.isRegLoc())
1826             return false;
1827           if (!ArgLocs[++i].isRegLoc())
1828             return false;
1829           if (RegVT == MVT::v2f64) {
1830             if (!ArgLocs[++i].isRegLoc())
1831               return false;
1832             if (!ArgLocs[++i].isRegLoc())
1833               return false;
1834           }
1835         } else if (!VA.isRegLoc()) {
1836           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
1837                                    MFI, MRI, TII))
1838             return false;
1839         }
1840       }
1841     }
1842   }
1843
1844   return true;
1845 }
1846
1847 SDValue
1848 ARMTargetLowering::LowerReturn(SDValue Chain,
1849                                CallingConv::ID CallConv, bool isVarArg,
1850                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1851                                const SmallVectorImpl<SDValue> &OutVals,
1852                                DebugLoc dl, SelectionDAG &DAG) const {
1853
1854   // CCValAssign - represent the assignment of the return value to a location.
1855   SmallVector<CCValAssign, 16> RVLocs;
1856
1857   // CCState - Info about the registers and stack slots.
1858   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1859                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1860
1861   // Analyze outgoing return values.
1862   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
1863                                                isVarArg));
1864
1865   // If this is the first return lowered for this function, add
1866   // the regs to the liveout set for the function.
1867   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1868     for (unsigned i = 0; i != RVLocs.size(); ++i)
1869       if (RVLocs[i].isRegLoc())
1870         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1871   }
1872
1873   SDValue Flag;
1874
1875   // Copy the result values into the output registers.
1876   for (unsigned i = 0, realRVLocIdx = 0;
1877        i != RVLocs.size();
1878        ++i, ++realRVLocIdx) {
1879     CCValAssign &VA = RVLocs[i];
1880     assert(VA.isRegLoc() && "Can only return in registers!");
1881
1882     SDValue Arg = OutVals[realRVLocIdx];
1883
1884     switch (VA.getLocInfo()) {
1885     default: llvm_unreachable("Unknown loc info!");
1886     case CCValAssign::Full: break;
1887     case CCValAssign::BCvt:
1888       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1889       break;
1890     }
1891
1892     if (VA.needsCustom()) {
1893       if (VA.getLocVT() == MVT::v2f64) {
1894         // Extract the first half and return it in two registers.
1895         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1896                                    DAG.getConstant(0, MVT::i32));
1897         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
1898                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
1899
1900         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
1901         Flag = Chain.getValue(1);
1902         VA = RVLocs[++i]; // skip ahead to next loc
1903         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
1904                                  HalfGPRs.getValue(1), Flag);
1905         Flag = Chain.getValue(1);
1906         VA = RVLocs[++i]; // skip ahead to next loc
1907
1908         // Extract the 2nd half and fall through to handle it as an f64 value.
1909         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1910                           DAG.getConstant(1, MVT::i32));
1911       }
1912       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
1913       // available.
1914       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1915                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
1916       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
1917       Flag = Chain.getValue(1);
1918       VA = RVLocs[++i]; // skip ahead to next loc
1919       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
1920                                Flag);
1921     } else
1922       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
1923
1924     // Guarantee that all emitted copies are
1925     // stuck together, avoiding something bad.
1926     Flag = Chain.getValue(1);
1927   }
1928
1929   SDValue result;
1930   if (Flag.getNode())
1931     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
1932   else // Return Void
1933     result = DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, Chain);
1934
1935   return result;
1936 }
1937
1938 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N) const {
1939   if (N->getNumValues() != 1)
1940     return false;
1941   if (!N->hasNUsesOfValue(1, 0))
1942     return false;
1943
1944   unsigned NumCopies = 0;
1945   SDNode* Copies[2] = { 0, 0 };
1946   SDNode *Use = *N->use_begin();
1947   if (Use->getOpcode() == ISD::CopyToReg) {
1948     Copies[NumCopies++] = Use;
1949   } else if (Use->getOpcode() == ARMISD::VMOVRRD) {
1950     // f64 returned in a pair of GPRs.
1951     for (SDNode::use_iterator UI = Use->use_begin(), UE = Use->use_end();
1952          UI != UE; ++UI) {
1953       if (UI->getOpcode() != ISD::CopyToReg)
1954         return false;
1955       Copies[UI.getUse().getResNo()] = *UI;
1956       ++NumCopies;
1957     }
1958   } else if (Use->getOpcode() == ISD::BITCAST) {
1959     // f32 returned in a single GPR.
1960     if (!Use->hasNUsesOfValue(1, 0))
1961       return false;
1962     Use = *Use->use_begin();
1963     if (Use->getOpcode() != ISD::CopyToReg || !Use->hasNUsesOfValue(1, 0))
1964       return false;
1965     Copies[NumCopies++] = Use;
1966   } else {
1967     return false;
1968   }
1969
1970   if (NumCopies != 1 && NumCopies != 2)
1971     return false;
1972
1973   bool HasRet = false;
1974   for (unsigned i = 0; i < NumCopies; ++i) {
1975     SDNode *Copy = Copies[i];
1976     for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1977          UI != UE; ++UI) {
1978       if (UI->getOpcode() == ISD::CopyToReg) {
1979         SDNode *Use = *UI;
1980         if (Use == Copies[0] || ((NumCopies == 2) && (Use == Copies[1])))
1981           continue;
1982         return false;
1983       }
1984       if (UI->getOpcode() != ARMISD::RET_FLAG)
1985         return false;
1986       HasRet = true;
1987     }
1988   }
1989
1990   return HasRet;
1991 }
1992
1993 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
1994   if (!EnableARMTailCalls)
1995     return false;
1996
1997   if (!CI->isTailCall())
1998     return false;
1999
2000   return !Subtarget->isThumb1Only();
2001 }
2002
2003 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2004 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2005 // one of the above mentioned nodes. It has to be wrapped because otherwise
2006 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2007 // be used to form addressing mode. These wrapped nodes will be selected
2008 // into MOVi.
2009 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2010   EVT PtrVT = Op.getValueType();
2011   // FIXME there is no actual debug info here
2012   DebugLoc dl = Op.getDebugLoc();
2013   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2014   SDValue Res;
2015   if (CP->isMachineConstantPoolEntry())
2016     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2017                                     CP->getAlignment());
2018   else
2019     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2020                                     CP->getAlignment());
2021   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2022 }
2023
2024 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2025   return MachineJumpTableInfo::EK_Inline;
2026 }
2027
2028 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2029                                              SelectionDAG &DAG) const {
2030   MachineFunction &MF = DAG.getMachineFunction();
2031   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2032   unsigned ARMPCLabelIndex = 0;
2033   DebugLoc DL = Op.getDebugLoc();
2034   EVT PtrVT = getPointerTy();
2035   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2036   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2037   SDValue CPAddr;
2038   if (RelocM == Reloc::Static) {
2039     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2040   } else {
2041     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2042     ARMPCLabelIndex = AFI->createPICLabelUId();
2043     ARMConstantPoolValue *CPV =
2044       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2045                                       ARMCP::CPBlockAddress, PCAdj);
2046     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2047   }
2048   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2049   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2050                                MachinePointerInfo::getConstantPool(),
2051                                false, false, false, 0);
2052   if (RelocM == Reloc::Static)
2053     return Result;
2054   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2055   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2056 }
2057
2058 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2059 SDValue
2060 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2061                                                  SelectionDAG &DAG) const {
2062   DebugLoc dl = GA->getDebugLoc();
2063   EVT PtrVT = getPointerTy();
2064   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2065   MachineFunction &MF = DAG.getMachineFunction();
2066   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2067   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2068   ARMConstantPoolValue *CPV =
2069     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2070                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2071   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2072   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2073   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2074                          MachinePointerInfo::getConstantPool(),
2075                          false, false, false, 0);
2076   SDValue Chain = Argument.getValue(1);
2077
2078   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2079   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2080
2081   // call __tls_get_addr.
2082   ArgListTy Args;
2083   ArgListEntry Entry;
2084   Entry.Node = Argument;
2085   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2086   Args.push_back(Entry);
2087   // FIXME: is there useful debug info available here?
2088   std::pair<SDValue, SDValue> CallResult =
2089     LowerCallTo(Chain, (Type *) Type::getInt32Ty(*DAG.getContext()),
2090                 false, false, false, false,
2091                 0, CallingConv::C, /*isTailCall=*/false,
2092                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2093                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2094   return CallResult.first;
2095 }
2096
2097 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2098 // "local exec" model.
2099 SDValue
2100 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2101                                         SelectionDAG &DAG) const {
2102   const GlobalValue *GV = GA->getGlobal();
2103   DebugLoc dl = GA->getDebugLoc();
2104   SDValue Offset;
2105   SDValue Chain = DAG.getEntryNode();
2106   EVT PtrVT = getPointerTy();
2107   // Get the Thread Pointer
2108   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2109
2110   if (GV->isDeclaration()) {
2111     MachineFunction &MF = DAG.getMachineFunction();
2112     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2113     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2114     // Initial exec model.
2115     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2116     ARMConstantPoolValue *CPV =
2117       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2118                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2119                                       true);
2120     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2121     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2122     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2123                          MachinePointerInfo::getConstantPool(),
2124                          false, false, false, 0);
2125     Chain = Offset.getValue(1);
2126
2127     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2128     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2129
2130     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2131                          MachinePointerInfo::getConstantPool(),
2132                          false, false, false, 0);
2133   } else {
2134     // local exec model
2135     ARMConstantPoolValue *CPV =
2136       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2137     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2138     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2139     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2140                          MachinePointerInfo::getConstantPool(),
2141                          false, false, false, 0);
2142   }
2143
2144   // The address of the thread local variable is the add of the thread
2145   // pointer with the offset of the variable.
2146   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2147 }
2148
2149 SDValue
2150 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2151   // TODO: implement the "local dynamic" model
2152   assert(Subtarget->isTargetELF() &&
2153          "TLS not implemented for non-ELF targets");
2154   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2155   // If the relocation model is PIC, use the "General Dynamic" TLS Model,
2156   // otherwise use the "Local Exec" TLS Model
2157   if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
2158     return LowerToTLSGeneralDynamicModel(GA, DAG);
2159   else
2160     return LowerToTLSExecModels(GA, DAG);
2161 }
2162
2163 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2164                                                  SelectionDAG &DAG) const {
2165   EVT PtrVT = getPointerTy();
2166   DebugLoc dl = Op.getDebugLoc();
2167   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2168   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2169   if (RelocM == Reloc::PIC_) {
2170     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2171     ARMConstantPoolValue *CPV =
2172       ARMConstantPoolConstant::Create(GV,
2173                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2174     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2175     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2176     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2177                                  CPAddr,
2178                                  MachinePointerInfo::getConstantPool(),
2179                                  false, false, false, 0);
2180     SDValue Chain = Result.getValue(1);
2181     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2182     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2183     if (!UseGOTOFF)
2184       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2185                            MachinePointerInfo::getGOT(),
2186                            false, false, false, 0);
2187     return Result;
2188   }
2189
2190   // If we have T2 ops, we can materialize the address directly via movt/movw
2191   // pair. This is always cheaper.
2192   if (Subtarget->useMovt()) {
2193     ++NumMovwMovt;
2194     // FIXME: Once remat is capable of dealing with instructions with register
2195     // operands, expand this into two nodes.
2196     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2197                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2198   } else {
2199     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2200     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2201     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2202                        MachinePointerInfo::getConstantPool(),
2203                        false, false, false, 0);
2204   }
2205 }
2206
2207 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2208                                                     SelectionDAG &DAG) const {
2209   EVT PtrVT = getPointerTy();
2210   DebugLoc dl = Op.getDebugLoc();
2211   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2212   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2213   MachineFunction &MF = DAG.getMachineFunction();
2214   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2215
2216   // FIXME: Enable this for static codegen when tool issues are fixed.  Also
2217   // update ARMFastISel::ARMMaterializeGV.
2218   if (Subtarget->useMovt() && RelocM != Reloc::Static) {
2219     ++NumMovwMovt;
2220     // FIXME: Once remat is capable of dealing with instructions with register
2221     // operands, expand this into two nodes.
2222     if (RelocM == Reloc::Static)
2223       return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2224                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2225
2226     unsigned Wrapper = (RelocM == Reloc::PIC_)
2227       ? ARMISD::WrapperPIC : ARMISD::WrapperDYN;
2228     SDValue Result = DAG.getNode(Wrapper, dl, PtrVT,
2229                                  DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2230     if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2231       Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2232                            MachinePointerInfo::getGOT(),
2233                            false, false, false, 0);
2234     return Result;
2235   }
2236
2237   unsigned ARMPCLabelIndex = 0;
2238   SDValue CPAddr;
2239   if (RelocM == Reloc::Static) {
2240     CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2241   } else {
2242     ARMPCLabelIndex = AFI->createPICLabelUId();
2243     unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb()?4:8);
2244     ARMConstantPoolValue *CPV =
2245       ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue,
2246                                       PCAdj);
2247     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2248   }
2249   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2250
2251   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2252                                MachinePointerInfo::getConstantPool(),
2253                                false, false, false, 0);
2254   SDValue Chain = Result.getValue(1);
2255
2256   if (RelocM == Reloc::PIC_) {
2257     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2258     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2259   }
2260
2261   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2262     Result = DAG.getLoad(PtrVT, dl, Chain, Result, MachinePointerInfo::getGOT(),
2263                          false, false, false, 0);
2264
2265   return Result;
2266 }
2267
2268 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2269                                                     SelectionDAG &DAG) const {
2270   assert(Subtarget->isTargetELF() &&
2271          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2272   MachineFunction &MF = DAG.getMachineFunction();
2273   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2274   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2275   EVT PtrVT = getPointerTy();
2276   DebugLoc dl = Op.getDebugLoc();
2277   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2278   ARMConstantPoolValue *CPV =
2279     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2280                                   ARMPCLabelIndex, PCAdj);
2281   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2282   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2283   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2284                                MachinePointerInfo::getConstantPool(),
2285                                false, false, false, 0);
2286   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2287   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2288 }
2289
2290 SDValue
2291 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2292   DebugLoc dl = Op.getDebugLoc();
2293   SDValue Val = DAG.getConstant(0, MVT::i32);
2294   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2295                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2296                      Op.getOperand(1), Val);
2297 }
2298
2299 SDValue
2300 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2301   DebugLoc dl = Op.getDebugLoc();
2302   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2303                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2304 }
2305
2306 SDValue
2307 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2308                                           const ARMSubtarget *Subtarget) const {
2309   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2310   DebugLoc dl = Op.getDebugLoc();
2311   switch (IntNo) {
2312   default: return SDValue();    // Don't custom lower most intrinsics.
2313   case Intrinsic::arm_thread_pointer: {
2314     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2315     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2316   }
2317   case Intrinsic::eh_sjlj_lsda: {
2318     MachineFunction &MF = DAG.getMachineFunction();
2319     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2320     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2321     EVT PtrVT = getPointerTy();
2322     DebugLoc dl = Op.getDebugLoc();
2323     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2324     SDValue CPAddr;
2325     unsigned PCAdj = (RelocM != Reloc::PIC_)
2326       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2327     ARMConstantPoolValue *CPV =
2328       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2329                                       ARMCP::CPLSDA, PCAdj);
2330     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2331     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2332     SDValue Result =
2333       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2334                   MachinePointerInfo::getConstantPool(),
2335                   false, false, false, 0);
2336
2337     if (RelocM == Reloc::PIC_) {
2338       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2339       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2340     }
2341     return Result;
2342   }
2343   case Intrinsic::arm_neon_vmulls:
2344   case Intrinsic::arm_neon_vmullu: {
2345     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2346       ? ARMISD::VMULLs : ARMISD::VMULLu;
2347     return DAG.getNode(NewOpc, Op.getDebugLoc(), Op.getValueType(),
2348                        Op.getOperand(1), Op.getOperand(2));
2349   }
2350   }
2351 }
2352
2353 static SDValue LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG,
2354                                const ARMSubtarget *Subtarget) {
2355   DebugLoc dl = Op.getDebugLoc();
2356   if (!Subtarget->hasDataBarrier()) {
2357     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2358     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2359     // here.
2360     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2361            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2362     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2363                        DAG.getConstant(0, MVT::i32));
2364   }
2365
2366   SDValue Op5 = Op.getOperand(5);
2367   bool isDeviceBarrier = cast<ConstantSDNode>(Op5)->getZExtValue() != 0;
2368   unsigned isLL = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
2369   unsigned isLS = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2370   bool isOnlyStoreBarrier = (isLL == 0 && isLS == 0);
2371
2372   ARM_MB::MemBOpt DMBOpt;
2373   if (isDeviceBarrier)
2374     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ST : ARM_MB::SY;
2375   else
2376     DMBOpt = isOnlyStoreBarrier ? ARM_MB::ISHST : ARM_MB::ISH;
2377   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2378                      DAG.getConstant(DMBOpt, MVT::i32));
2379 }
2380
2381
2382 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2383                                  const ARMSubtarget *Subtarget) {
2384   // FIXME: handle "fence singlethread" more efficiently.
2385   DebugLoc dl = Op.getDebugLoc();
2386   if (!Subtarget->hasDataBarrier()) {
2387     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2388     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2389     // here.
2390     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2391            "Unexpected ISD::MEMBARRIER encountered. Should be libcall!");
2392     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2393                        DAG.getConstant(0, MVT::i32));
2394   }
2395
2396   return DAG.getNode(ARMISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
2397                      DAG.getConstant(ARM_MB::ISH, MVT::i32));
2398 }
2399
2400 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2401                              const ARMSubtarget *Subtarget) {
2402   // ARM pre v5TE and Thumb1 does not have preload instructions.
2403   if (!(Subtarget->isThumb2() ||
2404         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2405     // Just preserve the chain.
2406     return Op.getOperand(0);
2407
2408   DebugLoc dl = Op.getDebugLoc();
2409   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2410   if (!isRead &&
2411       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2412     // ARMv7 with MP extension has PLDW.
2413     return Op.getOperand(0);
2414
2415   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2416   if (Subtarget->isThumb()) {
2417     // Invert the bits.
2418     isRead = ~isRead & 1;
2419     isData = ~isData & 1;
2420   }
2421
2422   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2423                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2424                      DAG.getConstant(isData, MVT::i32));
2425 }
2426
2427 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2428   MachineFunction &MF = DAG.getMachineFunction();
2429   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2430
2431   // vastart just stores the address of the VarArgsFrameIndex slot into the
2432   // memory location argument.
2433   DebugLoc dl = Op.getDebugLoc();
2434   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2435   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2436   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2437   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2438                       MachinePointerInfo(SV), false, false, 0);
2439 }
2440
2441 SDValue
2442 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2443                                         SDValue &Root, SelectionDAG &DAG,
2444                                         DebugLoc dl) const {
2445   MachineFunction &MF = DAG.getMachineFunction();
2446   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2447
2448   const TargetRegisterClass *RC;
2449   if (AFI->isThumb1OnlyFunction())
2450     RC = ARM::tGPRRegisterClass;
2451   else
2452     RC = ARM::GPRRegisterClass;
2453
2454   // Transform the arguments stored in physical registers into virtual ones.
2455   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2456   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2457
2458   SDValue ArgValue2;
2459   if (NextVA.isMemLoc()) {
2460     MachineFrameInfo *MFI = MF.getFrameInfo();
2461     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2462
2463     // Create load node to retrieve arguments from the stack.
2464     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2465     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2466                             MachinePointerInfo::getFixedStack(FI),
2467                             false, false, false, 0);
2468   } else {
2469     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2470     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2471   }
2472
2473   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2474 }
2475
2476 void
2477 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2478                                   unsigned &VARegSize, unsigned &VARegSaveSize)
2479   const {
2480   unsigned NumGPRs;
2481   if (CCInfo.isFirstByValRegValid())
2482     NumGPRs = ARM::R4 - CCInfo.getFirstByValReg();
2483   else {
2484     unsigned int firstUnalloced;
2485     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2486                                                 sizeof(GPRArgRegs) /
2487                                                 sizeof(GPRArgRegs[0]));
2488     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2489   }
2490
2491   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2492   VARegSize = NumGPRs * 4;
2493   VARegSaveSize = (VARegSize + Align - 1) & ~(Align - 1);
2494 }
2495
2496 // The remaining GPRs hold either the beginning of variable-argument
2497 // data, or the beginning of an aggregate passed by value (usuall
2498 // byval).  Either way, we allocate stack slots adjacent to the data
2499 // provided by our caller, and store the unallocated registers there.
2500 // If this is a variadic function, the va_list pointer will begin with
2501 // these values; otherwise, this reassembles a (byval) structure that
2502 // was split between registers and memory.
2503 void
2504 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2505                                         DebugLoc dl, SDValue &Chain,
2506                                         unsigned ArgOffset) const {
2507   MachineFunction &MF = DAG.getMachineFunction();
2508   MachineFrameInfo *MFI = MF.getFrameInfo();
2509   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2510   unsigned firstRegToSaveIndex;
2511   if (CCInfo.isFirstByValRegValid())
2512     firstRegToSaveIndex = CCInfo.getFirstByValReg() - ARM::R0;
2513   else {
2514     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2515       (GPRArgRegs, sizeof(GPRArgRegs) / sizeof(GPRArgRegs[0]));
2516   }
2517
2518   unsigned VARegSize, VARegSaveSize;
2519   computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2520   if (VARegSaveSize) {
2521     // If this function is vararg, store any remaining integer argument regs
2522     // to their spots on the stack so that they may be loaded by deferencing
2523     // the result of va_next.
2524     AFI->setVarArgsRegSaveSize(VARegSaveSize);
2525     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(VARegSaveSize,
2526                                                      ArgOffset + VARegSaveSize
2527                                                      - VARegSize,
2528                                                      false));
2529     SDValue FIN = DAG.getFrameIndex(AFI->getVarArgsFrameIndex(),
2530                                     getPointerTy());
2531
2532     SmallVector<SDValue, 4> MemOps;
2533     for (; firstRegToSaveIndex < 4; ++firstRegToSaveIndex) {
2534       const TargetRegisterClass *RC;
2535       if (AFI->isThumb1OnlyFunction())
2536         RC = ARM::tGPRRegisterClass;
2537       else
2538         RC = ARM::GPRRegisterClass;
2539
2540       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2541       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2542       SDValue Store =
2543         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2544                  MachinePointerInfo::getFixedStack(AFI->getVarArgsFrameIndex()),
2545                      false, false, 0);
2546       MemOps.push_back(Store);
2547       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2548                         DAG.getConstant(4, getPointerTy()));
2549     }
2550     if (!MemOps.empty())
2551       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2552                           &MemOps[0], MemOps.size());
2553   } else
2554     // This will point to the next argument passed via stack.
2555     AFI->setVarArgsFrameIndex(MFI->CreateFixedObject(4, ArgOffset, true));
2556 }
2557
2558 SDValue
2559 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2560                                         CallingConv::ID CallConv, bool isVarArg,
2561                                         const SmallVectorImpl<ISD::InputArg>
2562                                           &Ins,
2563                                         DebugLoc dl, SelectionDAG &DAG,
2564                                         SmallVectorImpl<SDValue> &InVals)
2565                                           const {
2566   MachineFunction &MF = DAG.getMachineFunction();
2567   MachineFrameInfo *MFI = MF.getFrameInfo();
2568
2569   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2570
2571   // Assign locations to all of the incoming arguments.
2572   SmallVector<CCValAssign, 16> ArgLocs;
2573   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2574                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2575   CCInfo.AnalyzeFormalArguments(Ins,
2576                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2577                                                   isVarArg));
2578
2579   SmallVector<SDValue, 16> ArgValues;
2580   int lastInsIndex = -1;
2581
2582   SDValue ArgValue;
2583   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2584     CCValAssign &VA = ArgLocs[i];
2585
2586     // Arguments stored in registers.
2587     if (VA.isRegLoc()) {
2588       EVT RegVT = VA.getLocVT();
2589
2590       if (VA.needsCustom()) {
2591         // f64 and vector types are split up into multiple registers or
2592         // combinations of registers and stack slots.
2593         if (VA.getLocVT() == MVT::v2f64) {
2594           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2595                                                    Chain, DAG, dl);
2596           VA = ArgLocs[++i]; // skip ahead to next loc
2597           SDValue ArgValue2;
2598           if (VA.isMemLoc()) {
2599             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2600             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2601             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2602                                     MachinePointerInfo::getFixedStack(FI),
2603                                     false, false, false, 0);
2604           } else {
2605             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2606                                              Chain, DAG, dl);
2607           }
2608           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2609           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2610                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2611           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2612                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2613         } else
2614           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2615
2616       } else {
2617         const TargetRegisterClass *RC;
2618
2619         if (RegVT == MVT::f32)
2620           RC = ARM::SPRRegisterClass;
2621         else if (RegVT == MVT::f64)
2622           RC = ARM::DPRRegisterClass;
2623         else if (RegVT == MVT::v2f64)
2624           RC = ARM::QPRRegisterClass;
2625         else if (RegVT == MVT::i32)
2626           RC = (AFI->isThumb1OnlyFunction() ?
2627                 ARM::tGPRRegisterClass : ARM::GPRRegisterClass);
2628         else
2629           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2630
2631         // Transform the arguments in physical registers into virtual ones.
2632         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2633         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2634       }
2635
2636       // If this is an 8 or 16-bit value, it is really passed promoted
2637       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2638       // truncate to the right size.
2639       switch (VA.getLocInfo()) {
2640       default: llvm_unreachable("Unknown loc info!");
2641       case CCValAssign::Full: break;
2642       case CCValAssign::BCvt:
2643         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2644         break;
2645       case CCValAssign::SExt:
2646         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2647                                DAG.getValueType(VA.getValVT()));
2648         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2649         break;
2650       case CCValAssign::ZExt:
2651         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2652                                DAG.getValueType(VA.getValVT()));
2653         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2654         break;
2655       }
2656
2657       InVals.push_back(ArgValue);
2658
2659     } else { // VA.isRegLoc()
2660
2661       // sanity check
2662       assert(VA.isMemLoc());
2663       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
2664
2665       int index = ArgLocs[i].getValNo();
2666
2667       // Some Ins[] entries become multiple ArgLoc[] entries.
2668       // Process them only once.
2669       if (index != lastInsIndex)
2670         {
2671           ISD::ArgFlagsTy Flags = Ins[index].Flags;
2672           // FIXME: For now, all byval parameter objects are marked mutable.
2673           // This can be changed with more analysis.
2674           // In case of tail call optimization mark all arguments mutable.
2675           // Since they could be overwritten by lowering of arguments in case of
2676           // a tail call.
2677           if (Flags.isByVal()) {
2678             unsigned VARegSize, VARegSaveSize;
2679             computeRegArea(CCInfo, MF, VARegSize, VARegSaveSize);
2680             VarArgStyleRegisters(CCInfo, DAG, dl, Chain, 0);
2681             unsigned Bytes = Flags.getByValSize() - VARegSize;
2682             if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2683             int FI = MFI->CreateFixedObject(Bytes,
2684                                             VA.getLocMemOffset(), false);
2685             InVals.push_back(DAG.getFrameIndex(FI, getPointerTy()));
2686           } else {
2687             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
2688                                             VA.getLocMemOffset(), true);
2689
2690             // Create load nodes to retrieve arguments from the stack.
2691             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2692             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2693                                          MachinePointerInfo::getFixedStack(FI),
2694                                          false, false, false, 0));
2695           }
2696           lastInsIndex = index;
2697         }
2698     }
2699   }
2700
2701   // varargs
2702   if (isVarArg)
2703     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset());
2704
2705   return Chain;
2706 }
2707
2708 /// isFloatingPointZero - Return true if this is +0.0.
2709 static bool isFloatingPointZero(SDValue Op) {
2710   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
2711     return CFP->getValueAPF().isPosZero();
2712   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
2713     // Maybe this has already been legalized into the constant pool?
2714     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
2715       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
2716       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
2717         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
2718           return CFP->getValueAPF().isPosZero();
2719     }
2720   }
2721   return false;
2722 }
2723
2724 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
2725 /// the given operands.
2726 SDValue
2727 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2728                              SDValue &ARMcc, SelectionDAG &DAG,
2729                              DebugLoc dl) const {
2730   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
2731     unsigned C = RHSC->getZExtValue();
2732     if (!isLegalICmpImmediate(C)) {
2733       // Constant does not fit, try adjusting it by one?
2734       switch (CC) {
2735       default: break;
2736       case ISD::SETLT:
2737       case ISD::SETGE:
2738         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
2739           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
2740           RHS = DAG.getConstant(C-1, MVT::i32);
2741         }
2742         break;
2743       case ISD::SETULT:
2744       case ISD::SETUGE:
2745         if (C != 0 && isLegalICmpImmediate(C-1)) {
2746           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
2747           RHS = DAG.getConstant(C-1, MVT::i32);
2748         }
2749         break;
2750       case ISD::SETLE:
2751       case ISD::SETGT:
2752         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
2753           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
2754           RHS = DAG.getConstant(C+1, MVT::i32);
2755         }
2756         break;
2757       case ISD::SETULE:
2758       case ISD::SETUGT:
2759         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
2760           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2761           RHS = DAG.getConstant(C+1, MVT::i32);
2762         }
2763         break;
2764       }
2765     }
2766   }
2767
2768   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
2769   ARMISD::NodeType CompareType;
2770   switch (CondCode) {
2771   default:
2772     CompareType = ARMISD::CMP;
2773     break;
2774   case ARMCC::EQ:
2775   case ARMCC::NE:
2776     // Uses only Z Flag
2777     CompareType = ARMISD::CMPZ;
2778     break;
2779   }
2780   ARMcc = DAG.getConstant(CondCode, MVT::i32);
2781   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
2782 }
2783
2784 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
2785 SDValue
2786 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
2787                              DebugLoc dl) const {
2788   SDValue Cmp;
2789   if (!isFloatingPointZero(RHS))
2790     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
2791   else
2792     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
2793   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
2794 }
2795
2796 /// duplicateCmp - Glue values can have only one use, so this function
2797 /// duplicates a comparison node.
2798 SDValue
2799 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
2800   unsigned Opc = Cmp.getOpcode();
2801   DebugLoc DL = Cmp.getDebugLoc();
2802   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
2803     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2804
2805   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
2806   Cmp = Cmp.getOperand(0);
2807   Opc = Cmp.getOpcode();
2808   if (Opc == ARMISD::CMPFP)
2809     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
2810   else {
2811     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
2812     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
2813   }
2814   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
2815 }
2816
2817 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2818   SDValue Cond = Op.getOperand(0);
2819   SDValue SelectTrue = Op.getOperand(1);
2820   SDValue SelectFalse = Op.getOperand(2);
2821   DebugLoc dl = Op.getDebugLoc();
2822
2823   // Convert:
2824   //
2825   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
2826   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
2827   //
2828   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
2829     const ConstantSDNode *CMOVTrue =
2830       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
2831     const ConstantSDNode *CMOVFalse =
2832       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
2833
2834     if (CMOVTrue && CMOVFalse) {
2835       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
2836       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
2837
2838       SDValue True;
2839       SDValue False;
2840       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
2841         True = SelectTrue;
2842         False = SelectFalse;
2843       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
2844         True = SelectFalse;
2845         False = SelectTrue;
2846       }
2847
2848       if (True.getNode() && False.getNode()) {
2849         EVT VT = Op.getValueType();
2850         SDValue ARMcc = Cond.getOperand(2);
2851         SDValue CCR = Cond.getOperand(3);
2852         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
2853         assert(True.getValueType() == VT);
2854         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
2855       }
2856     }
2857   }
2858
2859   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
2860   // undefined bits before doing a full-word comparison with zero.
2861   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
2862                      DAG.getConstant(1, Cond.getValueType()));
2863
2864   return DAG.getSelectCC(dl, Cond,
2865                          DAG.getConstant(0, Cond.getValueType()),
2866                          SelectTrue, SelectFalse, ISD::SETNE);
2867 }
2868
2869 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
2870   EVT VT = Op.getValueType();
2871   SDValue LHS = Op.getOperand(0);
2872   SDValue RHS = Op.getOperand(1);
2873   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2874   SDValue TrueVal = Op.getOperand(2);
2875   SDValue FalseVal = Op.getOperand(3);
2876   DebugLoc dl = Op.getDebugLoc();
2877
2878   if (LHS.getValueType() == MVT::i32) {
2879     SDValue ARMcc;
2880     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2881     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
2882     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,Cmp);
2883   }
2884
2885   ARMCC::CondCodes CondCode, CondCode2;
2886   FPCCToARMCC(CC, CondCode, CondCode2);
2887
2888   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
2889   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
2890   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
2891   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
2892                                ARMcc, CCR, Cmp);
2893   if (CondCode2 != ARMCC::AL) {
2894     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
2895     // FIXME: Needs another CMP because flag can have but one use.
2896     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
2897     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
2898                          Result, TrueVal, ARMcc2, CCR, Cmp2);
2899   }
2900   return Result;
2901 }
2902
2903 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
2904 /// to morph to an integer compare sequence.
2905 static bool canChangeToInt(SDValue Op, bool &SeenZero,
2906                            const ARMSubtarget *Subtarget) {
2907   SDNode *N = Op.getNode();
2908   if (!N->hasOneUse())
2909     // Otherwise it requires moving the value from fp to integer registers.
2910     return false;
2911   if (!N->getNumValues())
2912     return false;
2913   EVT VT = Op.getValueType();
2914   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
2915     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
2916     // vmrs are very slow, e.g. cortex-a8.
2917     return false;
2918
2919   if (isFloatingPointZero(Op)) {
2920     SeenZero = true;
2921     return true;
2922   }
2923   return ISD::isNormalLoad(N);
2924 }
2925
2926 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
2927   if (isFloatingPointZero(Op))
2928     return DAG.getConstant(0, MVT::i32);
2929
2930   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
2931     return DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2932                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
2933                        Ld->isVolatile(), Ld->isNonTemporal(),
2934                        Ld->isInvariant(), Ld->getAlignment());
2935
2936   llvm_unreachable("Unknown VFP cmp argument!");
2937 }
2938
2939 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
2940                            SDValue &RetVal1, SDValue &RetVal2) {
2941   if (isFloatingPointZero(Op)) {
2942     RetVal1 = DAG.getConstant(0, MVT::i32);
2943     RetVal2 = DAG.getConstant(0, MVT::i32);
2944     return;
2945   }
2946
2947   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
2948     SDValue Ptr = Ld->getBasePtr();
2949     RetVal1 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2950                           Ld->getChain(), Ptr,
2951                           Ld->getPointerInfo(),
2952                           Ld->isVolatile(), Ld->isNonTemporal(),
2953                           Ld->isInvariant(), Ld->getAlignment());
2954
2955     EVT PtrType = Ptr.getValueType();
2956     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
2957     SDValue NewPtr = DAG.getNode(ISD::ADD, Op.getDebugLoc(),
2958                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
2959     RetVal2 = DAG.getLoad(MVT::i32, Op.getDebugLoc(),
2960                           Ld->getChain(), NewPtr,
2961                           Ld->getPointerInfo().getWithOffset(4),
2962                           Ld->isVolatile(), Ld->isNonTemporal(),
2963                           Ld->isInvariant(), NewAlign);
2964     return;
2965   }
2966
2967   llvm_unreachable("Unknown VFP cmp argument!");
2968 }
2969
2970 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
2971 /// f32 and even f64 comparisons to integer ones.
2972 SDValue
2973 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
2974   SDValue Chain = Op.getOperand(0);
2975   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2976   SDValue LHS = Op.getOperand(2);
2977   SDValue RHS = Op.getOperand(3);
2978   SDValue Dest = Op.getOperand(4);
2979   DebugLoc dl = Op.getDebugLoc();
2980
2981   bool SeenZero = false;
2982   if (canChangeToInt(LHS, SeenZero, Subtarget) &&
2983       canChangeToInt(RHS, SeenZero, Subtarget) &&
2984       // If one of the operand is zero, it's safe to ignore the NaN case since
2985       // we only care about equality comparisons.
2986       (SeenZero || (DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS)))) {
2987     // If unsafe fp math optimization is enabled and there are no other uses of
2988     // the CMP operands, and the condition code is EQ or NE, we can optimize it
2989     // to an integer comparison.
2990     if (CC == ISD::SETOEQ)
2991       CC = ISD::SETEQ;
2992     else if (CC == ISD::SETUNE)
2993       CC = ISD::SETNE;
2994
2995     SDValue ARMcc;
2996     if (LHS.getValueType() == MVT::f32) {
2997       LHS = bitcastf32Toi32(LHS, DAG);
2998       RHS = bitcastf32Toi32(RHS, DAG);
2999       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3000       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3001       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3002                          Chain, Dest, ARMcc, CCR, Cmp);
3003     }
3004
3005     SDValue LHS1, LHS2;
3006     SDValue RHS1, RHS2;
3007     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3008     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3009     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3010     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3011     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3012     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3013     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3014   }
3015
3016   return SDValue();
3017 }
3018
3019 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3020   SDValue Chain = Op.getOperand(0);
3021   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3022   SDValue LHS = Op.getOperand(2);
3023   SDValue RHS = Op.getOperand(3);
3024   SDValue Dest = Op.getOperand(4);
3025   DebugLoc dl = Op.getDebugLoc();
3026
3027   if (LHS.getValueType() == MVT::i32) {
3028     SDValue ARMcc;
3029     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3030     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3031     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3032                        Chain, Dest, ARMcc, CCR, Cmp);
3033   }
3034
3035   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3036
3037   if (getTargetMachine().Options.UnsafeFPMath &&
3038       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3039        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3040     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3041     if (Result.getNode())
3042       return Result;
3043   }
3044
3045   ARMCC::CondCodes CondCode, CondCode2;
3046   FPCCToARMCC(CC, CondCode, CondCode2);
3047
3048   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3049   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3050   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3051   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3052   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3053   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3054   if (CondCode2 != ARMCC::AL) {
3055     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3056     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3057     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3058   }
3059   return Res;
3060 }
3061
3062 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3063   SDValue Chain = Op.getOperand(0);
3064   SDValue Table = Op.getOperand(1);
3065   SDValue Index = Op.getOperand(2);
3066   DebugLoc dl = Op.getDebugLoc();
3067
3068   EVT PTy = getPointerTy();
3069   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3070   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3071   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3072   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3073   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3074   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3075   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3076   if (Subtarget->isThumb2()) {
3077     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3078     // which does another jump to the destination. This also makes it easier
3079     // to translate it to TBB / TBH later.
3080     // FIXME: This might not work if the function is extremely large.
3081     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3082                        Addr, Op.getOperand(2), JTI, UId);
3083   }
3084   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3085     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3086                        MachinePointerInfo::getJumpTable(),
3087                        false, false, false, 0);
3088     Chain = Addr.getValue(1);
3089     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3090     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3091   } else {
3092     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3093                        MachinePointerInfo::getJumpTable(),
3094                        false, false, false, 0);
3095     Chain = Addr.getValue(1);
3096     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3097   }
3098 }
3099
3100 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3101   EVT VT = Op.getValueType();
3102   DebugLoc dl = Op.getDebugLoc();
3103
3104   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3105     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3106       return Op;
3107     return DAG.UnrollVectorOp(Op.getNode());
3108   }
3109
3110   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3111          "Invalid type for custom lowering!");
3112   if (VT != MVT::v4i16)
3113     return DAG.UnrollVectorOp(Op.getNode());
3114
3115   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3116   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3117 }
3118
3119 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3120   EVT VT = Op.getValueType();
3121   if (VT.isVector())
3122     return LowerVectorFP_TO_INT(Op, DAG);
3123
3124   DebugLoc dl = Op.getDebugLoc();
3125   unsigned Opc;
3126
3127   switch (Op.getOpcode()) {
3128   default: llvm_unreachable("Invalid opcode!");
3129   case ISD::FP_TO_SINT:
3130     Opc = ARMISD::FTOSI;
3131     break;
3132   case ISD::FP_TO_UINT:
3133     Opc = ARMISD::FTOUI;
3134     break;
3135   }
3136   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3137   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3138 }
3139
3140 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3141   EVT VT = Op.getValueType();
3142   DebugLoc dl = Op.getDebugLoc();
3143
3144   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3145     if (VT.getVectorElementType() == MVT::f32)
3146       return Op;
3147     return DAG.UnrollVectorOp(Op.getNode());
3148   }
3149
3150   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3151          "Invalid type for custom lowering!");
3152   if (VT != MVT::v4f32)
3153     return DAG.UnrollVectorOp(Op.getNode());
3154
3155   unsigned CastOpc;
3156   unsigned Opc;
3157   switch (Op.getOpcode()) {
3158   default: llvm_unreachable("Invalid opcode!");
3159   case ISD::SINT_TO_FP:
3160     CastOpc = ISD::SIGN_EXTEND;
3161     Opc = ISD::SINT_TO_FP;
3162     break;
3163   case ISD::UINT_TO_FP:
3164     CastOpc = ISD::ZERO_EXTEND;
3165     Opc = ISD::UINT_TO_FP;
3166     break;
3167   }
3168
3169   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3170   return DAG.getNode(Opc, dl, VT, Op);
3171 }
3172
3173 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3174   EVT VT = Op.getValueType();
3175   if (VT.isVector())
3176     return LowerVectorINT_TO_FP(Op, DAG);
3177
3178   DebugLoc dl = Op.getDebugLoc();
3179   unsigned Opc;
3180
3181   switch (Op.getOpcode()) {
3182   default: llvm_unreachable("Invalid opcode!");
3183   case ISD::SINT_TO_FP:
3184     Opc = ARMISD::SITOF;
3185     break;
3186   case ISD::UINT_TO_FP:
3187     Opc = ARMISD::UITOF;
3188     break;
3189   }
3190
3191   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3192   return DAG.getNode(Opc, dl, VT, Op);
3193 }
3194
3195 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3196   // Implement fcopysign with a fabs and a conditional fneg.
3197   SDValue Tmp0 = Op.getOperand(0);
3198   SDValue Tmp1 = Op.getOperand(1);
3199   DebugLoc dl = Op.getDebugLoc();
3200   EVT VT = Op.getValueType();
3201   EVT SrcVT = Tmp1.getValueType();
3202   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3203     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3204   bool UseNEON = !InGPR && Subtarget->hasNEON();
3205
3206   if (UseNEON) {
3207     // Use VBSL to copy the sign bit.
3208     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3209     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3210                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3211     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3212     if (VT == MVT::f64)
3213       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3214                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3215                          DAG.getConstant(32, MVT::i32));
3216     else /*if (VT == MVT::f32)*/
3217       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3218     if (SrcVT == MVT::f32) {
3219       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3220       if (VT == MVT::f64)
3221         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3222                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3223                            DAG.getConstant(32, MVT::i32));
3224     } else if (VT == MVT::f32)
3225       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3226                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3227                          DAG.getConstant(32, MVT::i32));
3228     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3229     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3230
3231     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3232                                             MVT::i32);
3233     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3234     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3235                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3236
3237     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3238                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3239                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3240     if (VT == MVT::f32) {
3241       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3242       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3243                         DAG.getConstant(0, MVT::i32));
3244     } else {
3245       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3246     }
3247
3248     return Res;
3249   }
3250
3251   // Bitcast operand 1 to i32.
3252   if (SrcVT == MVT::f64)
3253     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3254                        &Tmp1, 1).getValue(1);
3255   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3256
3257   // Or in the signbit with integer operations.
3258   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3259   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3260   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3261   if (VT == MVT::f32) {
3262     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3263                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3264     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3265                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3266   }
3267
3268   // f64: Or the high part with signbit and then combine two parts.
3269   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3270                      &Tmp0, 1);
3271   SDValue Lo = Tmp0.getValue(0);
3272   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3273   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3274   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3275 }
3276
3277 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3278   MachineFunction &MF = DAG.getMachineFunction();
3279   MachineFrameInfo *MFI = MF.getFrameInfo();
3280   MFI->setReturnAddressIsTaken(true);
3281
3282   EVT VT = Op.getValueType();
3283   DebugLoc dl = Op.getDebugLoc();
3284   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3285   if (Depth) {
3286     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3287     SDValue Offset = DAG.getConstant(4, MVT::i32);
3288     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3289                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3290                        MachinePointerInfo(), false, false, false, 0);
3291   }
3292
3293   // Return LR, which contains the return address. Mark it an implicit live-in.
3294   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3295   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3296 }
3297
3298 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3299   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3300   MFI->setFrameAddressIsTaken(true);
3301
3302   EVT VT = Op.getValueType();
3303   DebugLoc dl = Op.getDebugLoc();  // FIXME probably not meaningful
3304   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3305   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetDarwin())
3306     ? ARM::R7 : ARM::R11;
3307   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3308   while (Depth--)
3309     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3310                             MachinePointerInfo(),
3311                             false, false, false, 0);
3312   return FrameAddr;
3313 }
3314
3315 /// ExpandBITCAST - If the target supports VFP, this function is called to
3316 /// expand a bit convert where either the source or destination type is i64 to
3317 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3318 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3319 /// vectors), since the legalizer won't know what to do with that.
3320 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3322   DebugLoc dl = N->getDebugLoc();
3323   SDValue Op = N->getOperand(0);
3324
3325   // This function is only supposed to be called for i64 types, either as the
3326   // source or destination of the bit convert.
3327   EVT SrcVT = Op.getValueType();
3328   EVT DstVT = N->getValueType(0);
3329   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3330          "ExpandBITCAST called for non-i64 type");
3331
3332   // Turn i64->f64 into VMOVDRR.
3333   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3334     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3335                              DAG.getConstant(0, MVT::i32));
3336     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3337                              DAG.getConstant(1, MVT::i32));
3338     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3339                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3340   }
3341
3342   // Turn f64->i64 into VMOVRRD.
3343   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3344     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3345                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3346     // Merge the pieces into a single i64 value.
3347     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3348   }
3349
3350   return SDValue();
3351 }
3352
3353 /// getZeroVector - Returns a vector of specified type with all zero elements.
3354 /// Zero vectors are used to represent vector negation and in those cases
3355 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3356 /// not support i64 elements, so sometimes the zero vectors will need to be
3357 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3358 /// zero vector.
3359 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3360   assert(VT.isVector() && "Expected a vector type");
3361   // The canonical modified immediate encoding of a zero vector is....0!
3362   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3363   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3364   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3365   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3366 }
3367
3368 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3369 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3370 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3371                                                 SelectionDAG &DAG) const {
3372   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3373   EVT VT = Op.getValueType();
3374   unsigned VTBits = VT.getSizeInBits();
3375   DebugLoc dl = Op.getDebugLoc();
3376   SDValue ShOpLo = Op.getOperand(0);
3377   SDValue ShOpHi = Op.getOperand(1);
3378   SDValue ShAmt  = Op.getOperand(2);
3379   SDValue ARMcc;
3380   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3381
3382   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3383
3384   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3385                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3386   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3387   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3388                                    DAG.getConstant(VTBits, MVT::i32));
3389   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3390   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3391   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3392
3393   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3394   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3395                           ARMcc, DAG, dl);
3396   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3397   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3398                            CCR, Cmp);
3399
3400   SDValue Ops[2] = { Lo, Hi };
3401   return DAG.getMergeValues(Ops, 2, dl);
3402 }
3403
3404 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3405 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3406 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3407                                                SelectionDAG &DAG) const {
3408   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3409   EVT VT = Op.getValueType();
3410   unsigned VTBits = VT.getSizeInBits();
3411   DebugLoc dl = Op.getDebugLoc();
3412   SDValue ShOpLo = Op.getOperand(0);
3413   SDValue ShOpHi = Op.getOperand(1);
3414   SDValue ShAmt  = Op.getOperand(2);
3415   SDValue ARMcc;
3416
3417   assert(Op.getOpcode() == ISD::SHL_PARTS);
3418   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3419                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3420   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3421   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3422                                    DAG.getConstant(VTBits, MVT::i32));
3423   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3424   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3425
3426   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3427   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3428   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3429                           ARMcc, DAG, dl);
3430   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3431   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3432                            CCR, Cmp);
3433
3434   SDValue Ops[2] = { Lo, Hi };
3435   return DAG.getMergeValues(Ops, 2, dl);
3436 }
3437
3438 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3439                                             SelectionDAG &DAG) const {
3440   // The rounding mode is in bits 23:22 of the FPSCR.
3441   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3442   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3443   // so that the shift + and get folded into a bitfield extract.
3444   DebugLoc dl = Op.getDebugLoc();
3445   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3446                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3447                                               MVT::i32));
3448   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3449                                   DAG.getConstant(1U << 22, MVT::i32));
3450   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3451                               DAG.getConstant(22, MVT::i32));
3452   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3453                      DAG.getConstant(3, MVT::i32));
3454 }
3455
3456 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3457                          const ARMSubtarget *ST) {
3458   EVT VT = N->getValueType(0);
3459   DebugLoc dl = N->getDebugLoc();
3460
3461   if (!ST->hasV6T2Ops())
3462     return SDValue();
3463
3464   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3465   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3466 }
3467
3468 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
3469                           const ARMSubtarget *ST) {
3470   EVT VT = N->getValueType(0);
3471   DebugLoc dl = N->getDebugLoc();
3472
3473   if (!VT.isVector())
3474     return SDValue();
3475
3476   // Lower vector shifts on NEON to use VSHL.
3477   assert(ST->hasNEON() && "unexpected vector shift");
3478
3479   // Left shifts translate directly to the vshiftu intrinsic.
3480   if (N->getOpcode() == ISD::SHL)
3481     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3482                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
3483                        N->getOperand(0), N->getOperand(1));
3484
3485   assert((N->getOpcode() == ISD::SRA ||
3486           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
3487
3488   // NEON uses the same intrinsics for both left and right shifts.  For
3489   // right shifts, the shift amounts are negative, so negate the vector of
3490   // shift amounts.
3491   EVT ShiftVT = N->getOperand(1).getValueType();
3492   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
3493                                      getZeroVector(ShiftVT, DAG, dl),
3494                                      N->getOperand(1));
3495   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
3496                              Intrinsic::arm_neon_vshifts :
3497                              Intrinsic::arm_neon_vshiftu);
3498   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
3499                      DAG.getConstant(vshiftInt, MVT::i32),
3500                      N->getOperand(0), NegatedCount);
3501 }
3502
3503 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
3504                                 const ARMSubtarget *ST) {
3505   EVT VT = N->getValueType(0);
3506   DebugLoc dl = N->getDebugLoc();
3507
3508   // We can get here for a node like i32 = ISD::SHL i32, i64
3509   if (VT != MVT::i64)
3510     return SDValue();
3511
3512   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
3513          "Unknown shift to lower!");
3514
3515   // We only lower SRA, SRL of 1 here, all others use generic lowering.
3516   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
3517       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
3518     return SDValue();
3519
3520   // If we are in thumb mode, we don't have RRX.
3521   if (ST->isThumb1Only()) return SDValue();
3522
3523   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
3524   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3525                            DAG.getConstant(0, MVT::i32));
3526   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
3527                            DAG.getConstant(1, MVT::i32));
3528
3529   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
3530   // captures the result into a carry flag.
3531   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
3532   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
3533
3534   // The low part is an ARMISD::RRX operand, which shifts the carry in.
3535   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
3536
3537   // Merge the pieces into a single i64 value.
3538  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
3539 }
3540
3541 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
3542   SDValue TmpOp0, TmpOp1;
3543   bool Invert = false;
3544   bool Swap = false;
3545   unsigned Opc = 0;
3546
3547   SDValue Op0 = Op.getOperand(0);
3548   SDValue Op1 = Op.getOperand(1);
3549   SDValue CC = Op.getOperand(2);
3550   EVT VT = Op.getValueType();
3551   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
3552   DebugLoc dl = Op.getDebugLoc();
3553
3554   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
3555     switch (SetCCOpcode) {
3556     default: llvm_unreachable("Illegal FP comparison");
3557     case ISD::SETUNE:
3558     case ISD::SETNE:  Invert = true; // Fallthrough
3559     case ISD::SETOEQ:
3560     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3561     case ISD::SETOLT:
3562     case ISD::SETLT: Swap = true; // Fallthrough
3563     case ISD::SETOGT:
3564     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3565     case ISD::SETOLE:
3566     case ISD::SETLE:  Swap = true; // Fallthrough
3567     case ISD::SETOGE:
3568     case ISD::SETGE: Opc = ARMISD::VCGE; break;
3569     case ISD::SETUGE: Swap = true; // Fallthrough
3570     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
3571     case ISD::SETUGT: Swap = true; // Fallthrough
3572     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
3573     case ISD::SETUEQ: Invert = true; // Fallthrough
3574     case ISD::SETONE:
3575       // Expand this to (OLT | OGT).
3576       TmpOp0 = Op0;
3577       TmpOp1 = Op1;
3578       Opc = ISD::OR;
3579       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3580       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
3581       break;
3582     case ISD::SETUO: Invert = true; // Fallthrough
3583     case ISD::SETO:
3584       // Expand this to (OLT | OGE).
3585       TmpOp0 = Op0;
3586       TmpOp1 = Op1;
3587       Opc = ISD::OR;
3588       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
3589       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
3590       break;
3591     }
3592   } else {
3593     // Integer comparisons.
3594     switch (SetCCOpcode) {
3595     default: llvm_unreachable("Illegal integer comparison");
3596     case ISD::SETNE:  Invert = true;
3597     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
3598     case ISD::SETLT:  Swap = true;
3599     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
3600     case ISD::SETLE:  Swap = true;
3601     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
3602     case ISD::SETULT: Swap = true;
3603     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
3604     case ISD::SETULE: Swap = true;
3605     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
3606     }
3607
3608     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
3609     if (Opc == ARMISD::VCEQ) {
3610
3611       SDValue AndOp;
3612       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3613         AndOp = Op0;
3614       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
3615         AndOp = Op1;
3616
3617       // Ignore bitconvert.
3618       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
3619         AndOp = AndOp.getOperand(0);
3620
3621       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
3622         Opc = ARMISD::VTST;
3623         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
3624         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
3625         Invert = !Invert;
3626       }
3627     }
3628   }
3629
3630   if (Swap)
3631     std::swap(Op0, Op1);
3632
3633   // If one of the operands is a constant vector zero, attempt to fold the
3634   // comparison to a specialized compare-against-zero form.
3635   SDValue SingleOp;
3636   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
3637     SingleOp = Op0;
3638   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
3639     if (Opc == ARMISD::VCGE)
3640       Opc = ARMISD::VCLEZ;
3641     else if (Opc == ARMISD::VCGT)
3642       Opc = ARMISD::VCLTZ;
3643     SingleOp = Op1;
3644   }
3645
3646   SDValue Result;
3647   if (SingleOp.getNode()) {
3648     switch (Opc) {
3649     case ARMISD::VCEQ:
3650       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
3651     case ARMISD::VCGE:
3652       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
3653     case ARMISD::VCLEZ:
3654       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
3655     case ARMISD::VCGT:
3656       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
3657     case ARMISD::VCLTZ:
3658       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
3659     default:
3660       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3661     }
3662   } else {
3663      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
3664   }
3665
3666   if (Invert)
3667     Result = DAG.getNOT(dl, Result, VT);
3668
3669   return Result;
3670 }
3671
3672 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
3673 /// valid vector constant for a NEON instruction with a "modified immediate"
3674 /// operand (e.g., VMOV).  If so, return the encoded value.
3675 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
3676                                  unsigned SplatBitSize, SelectionDAG &DAG,
3677                                  EVT &VT, bool is128Bits, NEONModImmType type) {
3678   unsigned OpCmode, Imm;
3679
3680   // SplatBitSize is set to the smallest size that splats the vector, so a
3681   // zero vector will always have SplatBitSize == 8.  However, NEON modified
3682   // immediate instructions others than VMOV do not support the 8-bit encoding
3683   // of a zero vector, and the default encoding of zero is supposed to be the
3684   // 32-bit version.
3685   if (SplatBits == 0)
3686     SplatBitSize = 32;
3687
3688   switch (SplatBitSize) {
3689   case 8:
3690     if (type != VMOVModImm)
3691       return SDValue();
3692     // Any 1-byte value is OK.  Op=0, Cmode=1110.
3693     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
3694     OpCmode = 0xe;
3695     Imm = SplatBits;
3696     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
3697     break;
3698
3699   case 16:
3700     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
3701     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
3702     if ((SplatBits & ~0xff) == 0) {
3703       // Value = 0x00nn: Op=x, Cmode=100x.
3704       OpCmode = 0x8;
3705       Imm = SplatBits;
3706       break;
3707     }
3708     if ((SplatBits & ~0xff00) == 0) {
3709       // Value = 0xnn00: Op=x, Cmode=101x.
3710       OpCmode = 0xa;
3711       Imm = SplatBits >> 8;
3712       break;
3713     }
3714     return SDValue();
3715
3716   case 32:
3717     // NEON's 32-bit VMOV supports splat values where:
3718     // * only one byte is nonzero, or
3719     // * the least significant byte is 0xff and the second byte is nonzero, or
3720     // * the least significant 2 bytes are 0xff and the third is nonzero.
3721     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
3722     if ((SplatBits & ~0xff) == 0) {
3723       // Value = 0x000000nn: Op=x, Cmode=000x.
3724       OpCmode = 0;
3725       Imm = SplatBits;
3726       break;
3727     }
3728     if ((SplatBits & ~0xff00) == 0) {
3729       // Value = 0x0000nn00: Op=x, Cmode=001x.
3730       OpCmode = 0x2;
3731       Imm = SplatBits >> 8;
3732       break;
3733     }
3734     if ((SplatBits & ~0xff0000) == 0) {
3735       // Value = 0x00nn0000: Op=x, Cmode=010x.
3736       OpCmode = 0x4;
3737       Imm = SplatBits >> 16;
3738       break;
3739     }
3740     if ((SplatBits & ~0xff000000) == 0) {
3741       // Value = 0xnn000000: Op=x, Cmode=011x.
3742       OpCmode = 0x6;
3743       Imm = SplatBits >> 24;
3744       break;
3745     }
3746
3747     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
3748     if (type == OtherModImm) return SDValue();
3749
3750     if ((SplatBits & ~0xffff) == 0 &&
3751         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
3752       // Value = 0x0000nnff: Op=x, Cmode=1100.
3753       OpCmode = 0xc;
3754       Imm = SplatBits >> 8;
3755       SplatBits |= 0xff;
3756       break;
3757     }
3758
3759     if ((SplatBits & ~0xffffff) == 0 &&
3760         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
3761       // Value = 0x00nnffff: Op=x, Cmode=1101.
3762       OpCmode = 0xd;
3763       Imm = SplatBits >> 16;
3764       SplatBits |= 0xffff;
3765       break;
3766     }
3767
3768     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
3769     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
3770     // VMOV.I32.  A (very) minor optimization would be to replicate the value
3771     // and fall through here to test for a valid 64-bit splat.  But, then the
3772     // caller would also need to check and handle the change in size.
3773     return SDValue();
3774
3775   case 64: {
3776     if (type != VMOVModImm)
3777       return SDValue();
3778     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
3779     uint64_t BitMask = 0xff;
3780     uint64_t Val = 0;
3781     unsigned ImmMask = 1;
3782     Imm = 0;
3783     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
3784       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
3785         Val |= BitMask;
3786         Imm |= ImmMask;
3787       } else if ((SplatBits & BitMask) != 0) {
3788         return SDValue();
3789       }
3790       BitMask <<= 8;
3791       ImmMask <<= 1;
3792     }
3793     // Op=1, Cmode=1110.
3794     OpCmode = 0x1e;
3795     SplatBits = Val;
3796     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
3797     break;
3798   }
3799
3800   default:
3801     llvm_unreachable("unexpected size for isNEONModifiedImm");
3802   }
3803
3804   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
3805   return DAG.getTargetConstant(EncodedVal, MVT::i32);
3806 }
3807
3808 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
3809                        bool &ReverseVEXT, unsigned &Imm) {
3810   unsigned NumElts = VT.getVectorNumElements();
3811   ReverseVEXT = false;
3812
3813   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
3814   if (M[0] < 0)
3815     return false;
3816
3817   Imm = M[0];
3818
3819   // If this is a VEXT shuffle, the immediate value is the index of the first
3820   // element.  The other shuffle indices must be the successive elements after
3821   // the first one.
3822   unsigned ExpectedElt = Imm;
3823   for (unsigned i = 1; i < NumElts; ++i) {
3824     // Increment the expected index.  If it wraps around, it may still be
3825     // a VEXT but the source vectors must be swapped.
3826     ExpectedElt += 1;
3827     if (ExpectedElt == NumElts * 2) {
3828       ExpectedElt = 0;
3829       ReverseVEXT = true;
3830     }
3831
3832     if (M[i] < 0) continue; // ignore UNDEF indices
3833     if (ExpectedElt != static_cast<unsigned>(M[i]))
3834       return false;
3835   }
3836
3837   // Adjust the index value if the source operands will be swapped.
3838   if (ReverseVEXT)
3839     Imm -= NumElts;
3840
3841   return true;
3842 }
3843
3844 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
3845 /// instruction with the specified blocksize.  (The order of the elements
3846 /// within each block of the vector is reversed.)
3847 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3848   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
3849          "Only possible block sizes for VREV are: 16, 32, 64");
3850
3851   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3852   if (EltSz == 64)
3853     return false;
3854
3855   unsigned NumElts = VT.getVectorNumElements();
3856   unsigned BlockElts = M[0] + 1;
3857   // If the first shuffle index is UNDEF, be optimistic.
3858   if (M[0] < 0)
3859     BlockElts = BlockSize / EltSz;
3860
3861   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3862     return false;
3863
3864   for (unsigned i = 0; i < NumElts; ++i) {
3865     if (M[i] < 0) continue; // ignore UNDEF indices
3866     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
3867       return false;
3868   }
3869
3870   return true;
3871 }
3872
3873 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
3874   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
3875   // range, then 0 is placed into the resulting vector. So pretty much any mask
3876   // of 8 elements can work here.
3877   return VT == MVT::v8i8 && M.size() == 8;
3878 }
3879
3880 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3881   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3882   if (EltSz == 64)
3883     return false;
3884
3885   unsigned NumElts = VT.getVectorNumElements();
3886   WhichResult = (M[0] == 0 ? 0 : 1);
3887   for (unsigned i = 0; i < NumElts; i += 2) {
3888     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3889         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
3890       return false;
3891   }
3892   return true;
3893 }
3894
3895 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
3896 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3897 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
3898 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3899   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3900   if (EltSz == 64)
3901     return false;
3902
3903   unsigned NumElts = VT.getVectorNumElements();
3904   WhichResult = (M[0] == 0 ? 0 : 1);
3905   for (unsigned i = 0; i < NumElts; i += 2) {
3906     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
3907         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
3908       return false;
3909   }
3910   return true;
3911 }
3912
3913 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3914   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3915   if (EltSz == 64)
3916     return false;
3917
3918   unsigned NumElts = VT.getVectorNumElements();
3919   WhichResult = (M[0] == 0 ? 0 : 1);
3920   for (unsigned i = 0; i != NumElts; ++i) {
3921     if (M[i] < 0) continue; // ignore UNDEF indices
3922     if ((unsigned) M[i] != 2 * i + WhichResult)
3923       return false;
3924   }
3925
3926   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3927   if (VT.is64BitVector() && EltSz == 32)
3928     return false;
3929
3930   return true;
3931 }
3932
3933 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
3934 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3935 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
3936 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3937   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3938   if (EltSz == 64)
3939     return false;
3940
3941   unsigned Half = VT.getVectorNumElements() / 2;
3942   WhichResult = (M[0] == 0 ? 0 : 1);
3943   for (unsigned j = 0; j != 2; ++j) {
3944     unsigned Idx = WhichResult;
3945     for (unsigned i = 0; i != Half; ++i) {
3946       int MIdx = M[i + j * Half];
3947       if (MIdx >= 0 && (unsigned) MIdx != Idx)
3948         return false;
3949       Idx += 2;
3950     }
3951   }
3952
3953   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3954   if (VT.is64BitVector() && EltSz == 32)
3955     return false;
3956
3957   return true;
3958 }
3959
3960 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
3961   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3962   if (EltSz == 64)
3963     return false;
3964
3965   unsigned NumElts = VT.getVectorNumElements();
3966   WhichResult = (M[0] == 0 ? 0 : 1);
3967   unsigned Idx = WhichResult * NumElts / 2;
3968   for (unsigned i = 0; i != NumElts; i += 2) {
3969     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3970         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
3971       return false;
3972     Idx += 1;
3973   }
3974
3975   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
3976   if (VT.is64BitVector() && EltSz == 32)
3977     return false;
3978
3979   return true;
3980 }
3981
3982 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
3983 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
3984 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
3985 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
3986   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3987   if (EltSz == 64)
3988     return false;
3989
3990   unsigned NumElts = VT.getVectorNumElements();
3991   WhichResult = (M[0] == 0 ? 0 : 1);
3992   unsigned Idx = WhichResult * NumElts / 2;
3993   for (unsigned i = 0; i != NumElts; i += 2) {
3994     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
3995         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
3996       return false;
3997     Idx += 1;
3998   }
3999
4000   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4001   if (VT.is64BitVector() && EltSz == 32)
4002     return false;
4003
4004   return true;
4005 }
4006
4007 // If N is an integer constant that can be moved into a register in one
4008 // instruction, return an SDValue of such a constant (will become a MOV
4009 // instruction).  Otherwise return null.
4010 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4011                                      const ARMSubtarget *ST, DebugLoc dl) {
4012   uint64_t Val;
4013   if (!isa<ConstantSDNode>(N))
4014     return SDValue();
4015   Val = cast<ConstantSDNode>(N)->getZExtValue();
4016
4017   if (ST->isThumb1Only()) {
4018     if (Val <= 255 || ~Val <= 255)
4019       return DAG.getConstant(Val, MVT::i32);
4020   } else {
4021     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4022       return DAG.getConstant(Val, MVT::i32);
4023   }
4024   return SDValue();
4025 }
4026
4027 // If this is a case we can't handle, return null and let the default
4028 // expansion code take care of it.
4029 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4030                                              const ARMSubtarget *ST) const {
4031   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4032   DebugLoc dl = Op.getDebugLoc();
4033   EVT VT = Op.getValueType();
4034
4035   APInt SplatBits, SplatUndef;
4036   unsigned SplatBitSize;
4037   bool HasAnyUndefs;
4038   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4039     if (SplatBitSize <= 64) {
4040       // Check if an immediate VMOV works.
4041       EVT VmovVT;
4042       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4043                                       SplatUndef.getZExtValue(), SplatBitSize,
4044                                       DAG, VmovVT, VT.is128BitVector(),
4045                                       VMOVModImm);
4046       if (Val.getNode()) {
4047         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4048         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4049       }
4050
4051       // Try an immediate VMVN.
4052       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4053       Val = isNEONModifiedImm(NegatedImm,
4054                                       SplatUndef.getZExtValue(), SplatBitSize,
4055                                       DAG, VmovVT, VT.is128BitVector(),
4056                                       VMVNModImm);
4057       if (Val.getNode()) {
4058         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4059         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4060       }
4061
4062       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4063       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4064         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4065         if (ImmVal != -1) {
4066           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4067           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4068         }
4069       }
4070     }
4071   }
4072
4073   // Scan through the operands to see if only one value is used.
4074   unsigned NumElts = VT.getVectorNumElements();
4075   bool isOnlyLowElement = true;
4076   bool usesOnlyOneValue = true;
4077   bool isConstant = true;
4078   SDValue Value;
4079   for (unsigned i = 0; i < NumElts; ++i) {
4080     SDValue V = Op.getOperand(i);
4081     if (V.getOpcode() == ISD::UNDEF)
4082       continue;
4083     if (i > 0)
4084       isOnlyLowElement = false;
4085     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4086       isConstant = false;
4087
4088     if (!Value.getNode())
4089       Value = V;
4090     else if (V != Value)
4091       usesOnlyOneValue = false;
4092   }
4093
4094   if (!Value.getNode())
4095     return DAG.getUNDEF(VT);
4096
4097   if (isOnlyLowElement)
4098     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4099
4100   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4101
4102   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4103   // i32 and try again.
4104   if (usesOnlyOneValue && EltSize <= 32) {
4105     if (!isConstant)
4106       return DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4107     if (VT.getVectorElementType().isFloatingPoint()) {
4108       SmallVector<SDValue, 8> Ops;
4109       for (unsigned i = 0; i < NumElts; ++i)
4110         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4111                                   Op.getOperand(i)));
4112       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4113       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4114       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4115       if (Val.getNode())
4116         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4117     }
4118     SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4119     if (Val.getNode())
4120       return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4121   }
4122
4123   // If all elements are constants and the case above didn't get hit, fall back
4124   // to the default expansion, which will generate a load from the constant
4125   // pool.
4126   if (isConstant)
4127     return SDValue();
4128
4129   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4130   if (NumElts >= 4) {
4131     SDValue shuffle = ReconstructShuffle(Op, DAG);
4132     if (shuffle != SDValue())
4133       return shuffle;
4134   }
4135
4136   // Vectors with 32- or 64-bit elements can be built by directly assigning
4137   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4138   // will be legalized.
4139   if (EltSize >= 32) {
4140     // Do the expansion with floating-point types, since that is what the VFP
4141     // registers are defined to use, and since i64 is not legal.
4142     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4143     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4144     SmallVector<SDValue, 8> Ops;
4145     for (unsigned i = 0; i < NumElts; ++i)
4146       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4147     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4148     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4149   }
4150
4151   return SDValue();
4152 }
4153
4154 // Gather data to see if the operation can be modelled as a
4155 // shuffle in combination with VEXTs.
4156 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4157                                               SelectionDAG &DAG) const {
4158   DebugLoc dl = Op.getDebugLoc();
4159   EVT VT = Op.getValueType();
4160   unsigned NumElts = VT.getVectorNumElements();
4161
4162   SmallVector<SDValue, 2> SourceVecs;
4163   SmallVector<unsigned, 2> MinElts;
4164   SmallVector<unsigned, 2> MaxElts;
4165
4166   for (unsigned i = 0; i < NumElts; ++i) {
4167     SDValue V = Op.getOperand(i);
4168     if (V.getOpcode() == ISD::UNDEF)
4169       continue;
4170     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4171       // A shuffle can only come from building a vector from various
4172       // elements of other vectors.
4173       return SDValue();
4174     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4175                VT.getVectorElementType()) {
4176       // This code doesn't know how to handle shuffles where the vector
4177       // element types do not match (this happens because type legalization
4178       // promotes the return type of EXTRACT_VECTOR_ELT).
4179       // FIXME: It might be appropriate to extend this code to handle
4180       // mismatched types.
4181       return SDValue();
4182     }
4183
4184     // Record this extraction against the appropriate vector if possible...
4185     SDValue SourceVec = V.getOperand(0);
4186     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4187     bool FoundSource = false;
4188     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
4189       if (SourceVecs[j] == SourceVec) {
4190         if (MinElts[j] > EltNo)
4191           MinElts[j] = EltNo;
4192         if (MaxElts[j] < EltNo)
4193           MaxElts[j] = EltNo;
4194         FoundSource = true;
4195         break;
4196       }
4197     }
4198
4199     // Or record a new source if not...
4200     if (!FoundSource) {
4201       SourceVecs.push_back(SourceVec);
4202       MinElts.push_back(EltNo);
4203       MaxElts.push_back(EltNo);
4204     }
4205   }
4206
4207   // Currently only do something sane when at most two source vectors
4208   // involved.
4209   if (SourceVecs.size() > 2)
4210     return SDValue();
4211
4212   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
4213   int VEXTOffsets[2] = {0, 0};
4214
4215   // This loop extracts the usage patterns of the source vectors
4216   // and prepares appropriate SDValues for a shuffle if possible.
4217   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
4218     if (SourceVecs[i].getValueType() == VT) {
4219       // No VEXT necessary
4220       ShuffleSrcs[i] = SourceVecs[i];
4221       VEXTOffsets[i] = 0;
4222       continue;
4223     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
4224       // It probably isn't worth padding out a smaller vector just to
4225       // break it down again in a shuffle.
4226       return SDValue();
4227     }
4228
4229     // Since only 64-bit and 128-bit vectors are legal on ARM and
4230     // we've eliminated the other cases...
4231     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
4232            "unexpected vector sizes in ReconstructShuffle");
4233
4234     if (MaxElts[i] - MinElts[i] >= NumElts) {
4235       // Span too large for a VEXT to cope
4236       return SDValue();
4237     }
4238
4239     if (MinElts[i] >= NumElts) {
4240       // The extraction can just take the second half
4241       VEXTOffsets[i] = NumElts;
4242       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4243                                    SourceVecs[i],
4244                                    DAG.getIntPtrConstant(NumElts));
4245     } else if (MaxElts[i] < NumElts) {
4246       // The extraction can just take the first half
4247       VEXTOffsets[i] = 0;
4248       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4249                                    SourceVecs[i],
4250                                    DAG.getIntPtrConstant(0));
4251     } else {
4252       // An actual VEXT is needed
4253       VEXTOffsets[i] = MinElts[i];
4254       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4255                                      SourceVecs[i],
4256                                      DAG.getIntPtrConstant(0));
4257       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
4258                                      SourceVecs[i],
4259                                      DAG.getIntPtrConstant(NumElts));
4260       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
4261                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
4262     }
4263   }
4264
4265   SmallVector<int, 8> Mask;
4266
4267   for (unsigned i = 0; i < NumElts; ++i) {
4268     SDValue Entry = Op.getOperand(i);
4269     if (Entry.getOpcode() == ISD::UNDEF) {
4270       Mask.push_back(-1);
4271       continue;
4272     }
4273
4274     SDValue ExtractVec = Entry.getOperand(0);
4275     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
4276                                           .getOperand(1))->getSExtValue();
4277     if (ExtractVec == SourceVecs[0]) {
4278       Mask.push_back(ExtractElt - VEXTOffsets[0]);
4279     } else {
4280       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
4281     }
4282   }
4283
4284   // Final check before we try to produce nonsense...
4285   if (isShuffleMaskLegal(Mask, VT))
4286     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
4287                                 &Mask[0]);
4288
4289   return SDValue();
4290 }
4291
4292 /// isShuffleMaskLegal - Targets can use this to indicate that they only
4293 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
4294 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
4295 /// are assumed to be legal.
4296 bool
4297 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
4298                                       EVT VT) const {
4299   if (VT.getVectorNumElements() == 4 &&
4300       (VT.is128BitVector() || VT.is64BitVector())) {
4301     unsigned PFIndexes[4];
4302     for (unsigned i = 0; i != 4; ++i) {
4303       if (M[i] < 0)
4304         PFIndexes[i] = 8;
4305       else
4306         PFIndexes[i] = M[i];
4307     }
4308
4309     // Compute the index in the perfect shuffle table.
4310     unsigned PFTableIndex =
4311       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4312     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4313     unsigned Cost = (PFEntry >> 30);
4314
4315     if (Cost <= 4)
4316       return true;
4317   }
4318
4319   bool ReverseVEXT;
4320   unsigned Imm, WhichResult;
4321
4322   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4323   return (EltSize >= 32 ||
4324           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
4325           isVREVMask(M, VT, 64) ||
4326           isVREVMask(M, VT, 32) ||
4327           isVREVMask(M, VT, 16) ||
4328           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
4329           isVTBLMask(M, VT) ||
4330           isVTRNMask(M, VT, WhichResult) ||
4331           isVUZPMask(M, VT, WhichResult) ||
4332           isVZIPMask(M, VT, WhichResult) ||
4333           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
4334           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
4335           isVZIP_v_undef_Mask(M, VT, WhichResult));
4336 }
4337
4338 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4339 /// the specified operations to build the shuffle.
4340 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4341                                       SDValue RHS, SelectionDAG &DAG,
4342                                       DebugLoc dl) {
4343   unsigned OpNum = (PFEntry >> 26) & 0x0F;
4344   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4345   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
4346
4347   enum {
4348     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4349     OP_VREV,
4350     OP_VDUP0,
4351     OP_VDUP1,
4352     OP_VDUP2,
4353     OP_VDUP3,
4354     OP_VEXT1,
4355     OP_VEXT2,
4356     OP_VEXT3,
4357     OP_VUZPL, // VUZP, left result
4358     OP_VUZPR, // VUZP, right result
4359     OP_VZIPL, // VZIP, left result
4360     OP_VZIPR, // VZIP, right result
4361     OP_VTRNL, // VTRN, left result
4362     OP_VTRNR  // VTRN, right result
4363   };
4364
4365   if (OpNum == OP_COPY) {
4366     if (LHSID == (1*9+2)*9+3) return LHS;
4367     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4368     return RHS;
4369   }
4370
4371   SDValue OpLHS, OpRHS;
4372   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4373   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4374   EVT VT = OpLHS.getValueType();
4375
4376   switch (OpNum) {
4377   default: llvm_unreachable("Unknown shuffle opcode!");
4378   case OP_VREV:
4379     // VREV divides the vector in half and swaps within the half.
4380     if (VT.getVectorElementType() == MVT::i32 ||
4381         VT.getVectorElementType() == MVT::f32)
4382       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
4383     // vrev <4 x i16> -> VREV32
4384     if (VT.getVectorElementType() == MVT::i16)
4385       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
4386     // vrev <4 x i8> -> VREV16
4387     assert(VT.getVectorElementType() == MVT::i8);
4388     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
4389   case OP_VDUP0:
4390   case OP_VDUP1:
4391   case OP_VDUP2:
4392   case OP_VDUP3:
4393     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4394                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
4395   case OP_VEXT1:
4396   case OP_VEXT2:
4397   case OP_VEXT3:
4398     return DAG.getNode(ARMISD::VEXT, dl, VT,
4399                        OpLHS, OpRHS,
4400                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
4401   case OP_VUZPL:
4402   case OP_VUZPR:
4403     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4404                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
4405   case OP_VZIPL:
4406   case OP_VZIPR:
4407     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4408                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
4409   case OP_VTRNL:
4410   case OP_VTRNR:
4411     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4412                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
4413   }
4414 }
4415
4416 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
4417                                        ArrayRef<int> ShuffleMask,
4418                                        SelectionDAG &DAG) {
4419   // Check to see if we can use the VTBL instruction.
4420   SDValue V1 = Op.getOperand(0);
4421   SDValue V2 = Op.getOperand(1);
4422   DebugLoc DL = Op.getDebugLoc();
4423
4424   SmallVector<SDValue, 8> VTBLMask;
4425   for (ArrayRef<int>::iterator
4426          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
4427     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
4428
4429   if (V2.getNode()->getOpcode() == ISD::UNDEF)
4430     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
4431                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4432                                    &VTBLMask[0], 8));
4433
4434   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
4435                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
4436                                  &VTBLMask[0], 8));
4437 }
4438
4439 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4440   SDValue V1 = Op.getOperand(0);
4441   SDValue V2 = Op.getOperand(1);
4442   DebugLoc dl = Op.getDebugLoc();
4443   EVT VT = Op.getValueType();
4444   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4445
4446   // Convert shuffles that are directly supported on NEON to target-specific
4447   // DAG nodes, instead of keeping them as shuffles and matching them again
4448   // during code selection.  This is more efficient and avoids the possibility
4449   // of inconsistencies between legalization and selection.
4450   // FIXME: floating-point vectors should be canonicalized to integer vectors
4451   // of the same time so that they get CSEd properly.
4452   ArrayRef<int> ShuffleMask = SVN->getMask();
4453
4454   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4455   if (EltSize <= 32) {
4456     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
4457       int Lane = SVN->getSplatIndex();
4458       // If this is undef splat, generate it via "just" vdup, if possible.
4459       if (Lane == -1) Lane = 0;
4460
4461       // Test if V1 is a SCALAR_TO_VECTOR.
4462       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4463         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4464       }
4465       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
4466       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
4467       // reaches it).
4468       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
4469           !isa<ConstantSDNode>(V1.getOperand(0))) {
4470         bool IsScalarToVector = true;
4471         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
4472           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
4473             IsScalarToVector = false;
4474             break;
4475           }
4476         if (IsScalarToVector)
4477           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
4478       }
4479       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
4480                          DAG.getConstant(Lane, MVT::i32));
4481     }
4482
4483     bool ReverseVEXT;
4484     unsigned Imm;
4485     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
4486       if (ReverseVEXT)
4487         std::swap(V1, V2);
4488       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
4489                          DAG.getConstant(Imm, MVT::i32));
4490     }
4491
4492     if (isVREVMask(ShuffleMask, VT, 64))
4493       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
4494     if (isVREVMask(ShuffleMask, VT, 32))
4495       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
4496     if (isVREVMask(ShuffleMask, VT, 16))
4497       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
4498
4499     // Check for Neon shuffles that modify both input vectors in place.
4500     // If both results are used, i.e., if there are two shuffles with the same
4501     // source operands and with masks corresponding to both results of one of
4502     // these operations, DAG memoization will ensure that a single node is
4503     // used for both shuffles.
4504     unsigned WhichResult;
4505     if (isVTRNMask(ShuffleMask, VT, WhichResult))
4506       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4507                          V1, V2).getValue(WhichResult);
4508     if (isVUZPMask(ShuffleMask, VT, WhichResult))
4509       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4510                          V1, V2).getValue(WhichResult);
4511     if (isVZIPMask(ShuffleMask, VT, WhichResult))
4512       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4513                          V1, V2).getValue(WhichResult);
4514
4515     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
4516       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
4517                          V1, V1).getValue(WhichResult);
4518     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4519       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
4520                          V1, V1).getValue(WhichResult);
4521     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
4522       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
4523                          V1, V1).getValue(WhichResult);
4524   }
4525
4526   // If the shuffle is not directly supported and it has 4 elements, use
4527   // the PerfectShuffle-generated table to synthesize it from other shuffles.
4528   unsigned NumElts = VT.getVectorNumElements();
4529   if (NumElts == 4) {
4530     unsigned PFIndexes[4];
4531     for (unsigned i = 0; i != 4; ++i) {
4532       if (ShuffleMask[i] < 0)
4533         PFIndexes[i] = 8;
4534       else
4535         PFIndexes[i] = ShuffleMask[i];
4536     }
4537
4538     // Compute the index in the perfect shuffle table.
4539     unsigned PFTableIndex =
4540       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4541     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4542     unsigned Cost = (PFEntry >> 30);
4543
4544     if (Cost <= 4)
4545       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4546   }
4547
4548   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
4549   if (EltSize >= 32) {
4550     // Do the expansion with floating-point types, since that is what the VFP
4551     // registers are defined to use, and since i64 is not legal.
4552     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4553     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4554     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
4555     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
4556     SmallVector<SDValue, 8> Ops;
4557     for (unsigned i = 0; i < NumElts; ++i) {
4558       if (ShuffleMask[i] < 0)
4559         Ops.push_back(DAG.getUNDEF(EltVT));
4560       else
4561         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
4562                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
4563                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
4564                                                   MVT::i32)));
4565     }
4566     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4567     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4568   }
4569
4570   if (VT == MVT::v8i8) {
4571     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
4572     if (NewOp.getNode())
4573       return NewOp;
4574   }
4575
4576   return SDValue();
4577 }
4578
4579 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4580   // INSERT_VECTOR_ELT is legal only for immediate indexes.
4581   SDValue Lane = Op.getOperand(2);
4582   if (!isa<ConstantSDNode>(Lane))
4583     return SDValue();
4584
4585   return Op;
4586 }
4587
4588 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4589   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
4590   SDValue Lane = Op.getOperand(1);
4591   if (!isa<ConstantSDNode>(Lane))
4592     return SDValue();
4593
4594   SDValue Vec = Op.getOperand(0);
4595   if (Op.getValueType() == MVT::i32 &&
4596       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
4597     DebugLoc dl = Op.getDebugLoc();
4598     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
4599   }
4600
4601   return Op;
4602 }
4603
4604 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
4605   // The only time a CONCAT_VECTORS operation can have legal types is when
4606   // two 64-bit vectors are concatenated to a 128-bit vector.
4607   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
4608          "unexpected CONCAT_VECTORS");
4609   DebugLoc dl = Op.getDebugLoc();
4610   SDValue Val = DAG.getUNDEF(MVT::v2f64);
4611   SDValue Op0 = Op.getOperand(0);
4612   SDValue Op1 = Op.getOperand(1);
4613   if (Op0.getOpcode() != ISD::UNDEF)
4614     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4615                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
4616                       DAG.getIntPtrConstant(0));
4617   if (Op1.getOpcode() != ISD::UNDEF)
4618     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
4619                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
4620                       DAG.getIntPtrConstant(1));
4621   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
4622 }
4623
4624 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
4625 /// element has been zero/sign-extended, depending on the isSigned parameter,
4626 /// from an integer type half its size.
4627 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
4628                                    bool isSigned) {
4629   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
4630   EVT VT = N->getValueType(0);
4631   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
4632     SDNode *BVN = N->getOperand(0).getNode();
4633     if (BVN->getValueType(0) != MVT::v4i32 ||
4634         BVN->getOpcode() != ISD::BUILD_VECTOR)
4635       return false;
4636     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4637     unsigned HiElt = 1 - LoElt;
4638     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
4639     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
4640     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
4641     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
4642     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
4643       return false;
4644     if (isSigned) {
4645       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
4646           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
4647         return true;
4648     } else {
4649       if (Hi0->isNullValue() && Hi1->isNullValue())
4650         return true;
4651     }
4652     return false;
4653   }
4654
4655   if (N->getOpcode() != ISD::BUILD_VECTOR)
4656     return false;
4657
4658   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
4659     SDNode *Elt = N->getOperand(i).getNode();
4660     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
4661       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4662       unsigned HalfSize = EltSize / 2;
4663       if (isSigned) {
4664         if (!isIntN(HalfSize, C->getSExtValue()))
4665           return false;
4666       } else {
4667         if (!isUIntN(HalfSize, C->getZExtValue()))
4668           return false;
4669       }
4670       continue;
4671     }
4672     return false;
4673   }
4674
4675   return true;
4676 }
4677
4678 /// isSignExtended - Check if a node is a vector value that is sign-extended
4679 /// or a constant BUILD_VECTOR with sign-extended elements.
4680 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
4681   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
4682     return true;
4683   if (isExtendedBUILD_VECTOR(N, DAG, true))
4684     return true;
4685   return false;
4686 }
4687
4688 /// isZeroExtended - Check if a node is a vector value that is zero-extended
4689 /// or a constant BUILD_VECTOR with zero-extended elements.
4690 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
4691   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
4692     return true;
4693   if (isExtendedBUILD_VECTOR(N, DAG, false))
4694     return true;
4695   return false;
4696 }
4697
4698 /// SkipExtension - For a node that is a SIGN_EXTEND, ZERO_EXTEND, extending
4699 /// load, or BUILD_VECTOR with extended elements, return the unextended value.
4700 static SDValue SkipExtension(SDNode *N, SelectionDAG &DAG) {
4701   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
4702     return N->getOperand(0);
4703   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
4704     return DAG.getLoad(LD->getMemoryVT(), N->getDebugLoc(), LD->getChain(),
4705                        LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
4706                        LD->isNonTemporal(), LD->isInvariant(),
4707                        LD->getAlignment());
4708   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
4709   // have been legalized as a BITCAST from v4i32.
4710   if (N->getOpcode() == ISD::BITCAST) {
4711     SDNode *BVN = N->getOperand(0).getNode();
4712     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
4713            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
4714     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
4715     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), MVT::v2i32,
4716                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
4717   }
4718   // Construct a new BUILD_VECTOR with elements truncated to half the size.
4719   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
4720   EVT VT = N->getValueType(0);
4721   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
4722   unsigned NumElts = VT.getVectorNumElements();
4723   MVT TruncVT = MVT::getIntegerVT(EltSize);
4724   SmallVector<SDValue, 8> Ops;
4725   for (unsigned i = 0; i != NumElts; ++i) {
4726     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
4727     const APInt &CInt = C->getAPIntValue();
4728     Ops.push_back(DAG.getConstant(CInt.trunc(EltSize), TruncVT));
4729   }
4730   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
4731                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
4732 }
4733
4734 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
4735   unsigned Opcode = N->getOpcode();
4736   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4737     SDNode *N0 = N->getOperand(0).getNode();
4738     SDNode *N1 = N->getOperand(1).getNode();
4739     return N0->hasOneUse() && N1->hasOneUse() &&
4740       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
4741   }
4742   return false;
4743 }
4744
4745 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
4746   unsigned Opcode = N->getOpcode();
4747   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
4748     SDNode *N0 = N->getOperand(0).getNode();
4749     SDNode *N1 = N->getOperand(1).getNode();
4750     return N0->hasOneUse() && N1->hasOneUse() &&
4751       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
4752   }
4753   return false;
4754 }
4755
4756 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
4757   // Multiplications are only custom-lowered for 128-bit vectors so that
4758   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
4759   EVT VT = Op.getValueType();
4760   assert(VT.is128BitVector() && "unexpected type for custom-lowering ISD::MUL");
4761   SDNode *N0 = Op.getOperand(0).getNode();
4762   SDNode *N1 = Op.getOperand(1).getNode();
4763   unsigned NewOpc = 0;
4764   bool isMLA = false;
4765   bool isN0SExt = isSignExtended(N0, DAG);
4766   bool isN1SExt = isSignExtended(N1, DAG);
4767   if (isN0SExt && isN1SExt)
4768     NewOpc = ARMISD::VMULLs;
4769   else {
4770     bool isN0ZExt = isZeroExtended(N0, DAG);
4771     bool isN1ZExt = isZeroExtended(N1, DAG);
4772     if (isN0ZExt && isN1ZExt)
4773       NewOpc = ARMISD::VMULLu;
4774     else if (isN1SExt || isN1ZExt) {
4775       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
4776       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
4777       if (isN1SExt && isAddSubSExt(N0, DAG)) {
4778         NewOpc = ARMISD::VMULLs;
4779         isMLA = true;
4780       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
4781         NewOpc = ARMISD::VMULLu;
4782         isMLA = true;
4783       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
4784         std::swap(N0, N1);
4785         NewOpc = ARMISD::VMULLu;
4786         isMLA = true;
4787       }
4788     }
4789
4790     if (!NewOpc) {
4791       if (VT == MVT::v2i64)
4792         // Fall through to expand this.  It is not legal.
4793         return SDValue();
4794       else
4795         // Other vector multiplications are legal.
4796         return Op;
4797     }
4798   }
4799
4800   // Legalize to a VMULL instruction.
4801   DebugLoc DL = Op.getDebugLoc();
4802   SDValue Op0;
4803   SDValue Op1 = SkipExtension(N1, DAG);
4804   if (!isMLA) {
4805     Op0 = SkipExtension(N0, DAG);
4806     assert(Op0.getValueType().is64BitVector() &&
4807            Op1.getValueType().is64BitVector() &&
4808            "unexpected types for extended operands to VMULL");
4809     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
4810   }
4811
4812   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
4813   // isel lowering to take advantage of no-stall back to back vmul + vmla.
4814   //   vmull q0, d4, d6
4815   //   vmlal q0, d5, d6
4816   // is faster than
4817   //   vaddl q0, d4, d5
4818   //   vmovl q1, d6
4819   //   vmul  q0, q0, q1
4820   SDValue N00 = SkipExtension(N0->getOperand(0).getNode(), DAG);
4821   SDValue N01 = SkipExtension(N0->getOperand(1).getNode(), DAG);
4822   EVT Op1VT = Op1.getValueType();
4823   return DAG.getNode(N0->getOpcode(), DL, VT,
4824                      DAG.getNode(NewOpc, DL, VT,
4825                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
4826                      DAG.getNode(NewOpc, DL, VT,
4827                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
4828 }
4829
4830 static SDValue
4831 LowerSDIV_v4i8(SDValue X, SDValue Y, DebugLoc dl, SelectionDAG &DAG) {
4832   // Convert to float
4833   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
4834   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
4835   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
4836   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
4837   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
4838   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
4839   // Get reciprocal estimate.
4840   // float4 recip = vrecpeq_f32(yf);
4841   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4842                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
4843   // Because char has a smaller range than uchar, we can actually get away
4844   // without any newton steps.  This requires that we use a weird bias
4845   // of 0xb000, however (again, this has been exhaustively tested).
4846   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
4847   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
4848   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
4849   Y = DAG.getConstant(0xb000, MVT::i32);
4850   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
4851   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
4852   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
4853   // Convert back to short.
4854   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
4855   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
4856   return X;
4857 }
4858
4859 static SDValue
4860 LowerSDIV_v4i16(SDValue N0, SDValue N1, DebugLoc dl, SelectionDAG &DAG) {
4861   SDValue N2;
4862   // Convert to float.
4863   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
4864   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
4865   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
4866   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
4867   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4868   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4869
4870   // Use reciprocal estimate and one refinement step.
4871   // float4 recip = vrecpeq_f32(yf);
4872   // recip *= vrecpsq_f32(yf, recip);
4873   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4874                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
4875   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4876                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4877                    N1, N2);
4878   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4879   // Because short has a smaller range than ushort, we can actually get away
4880   // with only a single newton step.  This requires that we use a weird bias
4881   // of 89, however (again, this has been exhaustively tested).
4882   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
4883   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4884   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4885   N1 = DAG.getConstant(0x89, MVT::i32);
4886   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4887   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4888   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4889   // Convert back to integer and return.
4890   // return vmovn_s32(vcvt_s32_f32(result));
4891   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
4892   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
4893   return N0;
4894 }
4895
4896 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
4897   EVT VT = Op.getValueType();
4898   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4899          "unexpected type for custom-lowering ISD::SDIV");
4900
4901   DebugLoc dl = Op.getDebugLoc();
4902   SDValue N0 = Op.getOperand(0);
4903   SDValue N1 = Op.getOperand(1);
4904   SDValue N2, N3;
4905
4906   if (VT == MVT::v8i8) {
4907     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
4908     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
4909
4910     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4911                      DAG.getIntPtrConstant(4));
4912     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4913                      DAG.getIntPtrConstant(4));
4914     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4915                      DAG.getIntPtrConstant(0));
4916     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4917                      DAG.getIntPtrConstant(0));
4918
4919     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
4920     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
4921
4922     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4923     N0 = LowerCONCAT_VECTORS(N0, DAG);
4924
4925     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
4926     return N0;
4927   }
4928   return LowerSDIV_v4i16(N0, N1, dl, DAG);
4929 }
4930
4931 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
4932   EVT VT = Op.getValueType();
4933   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
4934          "unexpected type for custom-lowering ISD::UDIV");
4935
4936   DebugLoc dl = Op.getDebugLoc();
4937   SDValue N0 = Op.getOperand(0);
4938   SDValue N1 = Op.getOperand(1);
4939   SDValue N2, N3;
4940
4941   if (VT == MVT::v8i8) {
4942     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
4943     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
4944
4945     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4946                      DAG.getIntPtrConstant(4));
4947     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4948                      DAG.getIntPtrConstant(4));
4949     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
4950                      DAG.getIntPtrConstant(0));
4951     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
4952                      DAG.getIntPtrConstant(0));
4953
4954     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
4955     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
4956
4957     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
4958     N0 = LowerCONCAT_VECTORS(N0, DAG);
4959
4960     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
4961                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
4962                      N0);
4963     return N0;
4964   }
4965
4966   // v4i16 sdiv ... Convert to float.
4967   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
4968   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
4969   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
4970   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
4971   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
4972   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
4973
4974   // Use reciprocal estimate and two refinement steps.
4975   // float4 recip = vrecpeq_f32(yf);
4976   // recip *= vrecpsq_f32(yf, recip);
4977   // recip *= vrecpsq_f32(yf, recip);
4978   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4979                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
4980   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4981                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4982                    BN1, N2);
4983   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4984   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
4985                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
4986                    BN1, N2);
4987   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
4988   // Simply multiplying by the reciprocal estimate can leave us a few ulps
4989   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
4990   // and that it will never cause us to return an answer too large).
4991   // float4 result = as_float4(as_int4(xf*recip) + 2);
4992   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
4993   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
4994   N1 = DAG.getConstant(2, MVT::i32);
4995   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
4996   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
4997   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
4998   // Convert back to integer and return.
4999   // return vmovn_u32(vcvt_s32_f32(result));
5000   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5001   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5002   return N0;
5003 }
5004
5005 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5006   EVT VT = Op.getNode()->getValueType(0);
5007   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5008
5009   unsigned Opc;
5010   bool ExtraOp = false;
5011   switch (Op.getOpcode()) {
5012   default: llvm_unreachable("Invalid code");
5013   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5014   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5015   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5016   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5017   }
5018
5019   if (!ExtraOp)
5020     return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5021                        Op.getOperand(1));
5022   return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
5023                      Op.getOperand(1), Op.getOperand(2));
5024 }
5025
5026 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
5027   // Monotonic load/store is legal for all targets
5028   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
5029     return Op;
5030
5031   // Aquire/Release load/store is not legal for targets without a
5032   // dmb or equivalent available.
5033   return SDValue();
5034 }
5035
5036
5037 static void
5038 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
5039                     SelectionDAG &DAG, unsigned NewOp) {
5040   DebugLoc dl = Node->getDebugLoc();
5041   assert (Node->getValueType(0) == MVT::i64 &&
5042           "Only know how to expand i64 atomics");
5043
5044   SmallVector<SDValue, 6> Ops;
5045   Ops.push_back(Node->getOperand(0)); // Chain
5046   Ops.push_back(Node->getOperand(1)); // Ptr
5047   // Low part of Val1
5048   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5049                             Node->getOperand(2), DAG.getIntPtrConstant(0)));
5050   // High part of Val1
5051   Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5052                             Node->getOperand(2), DAG.getIntPtrConstant(1)));
5053   if (NewOp == ARMISD::ATOMCMPXCHG64_DAG) {
5054     // High part of Val1
5055     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5056                               Node->getOperand(3), DAG.getIntPtrConstant(0)));
5057     // High part of Val2
5058     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5059                               Node->getOperand(3), DAG.getIntPtrConstant(1)));
5060   }
5061   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
5062   SDValue Result =
5063     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops.data(), Ops.size(), MVT::i64,
5064                             cast<MemSDNode>(Node)->getMemOperand());
5065   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
5066   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
5067   Results.push_back(Result.getValue(2));
5068 }
5069
5070 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5071   switch (Op.getOpcode()) {
5072   default: llvm_unreachable("Don't know how to custom lower this!");
5073   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
5074   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
5075   case ISD::GlobalAddress:
5076     return Subtarget->isTargetDarwin() ? LowerGlobalAddressDarwin(Op, DAG) :
5077       LowerGlobalAddressELF(Op, DAG);
5078   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5079   case ISD::SELECT:        return LowerSELECT(Op, DAG);
5080   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
5081   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
5082   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
5083   case ISD::VASTART:       return LowerVASTART(Op, DAG);
5084   case ISD::MEMBARRIER:    return LowerMEMBARRIER(Op, DAG, Subtarget);
5085   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
5086   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
5087   case ISD::SINT_TO_FP:
5088   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
5089   case ISD::FP_TO_SINT:
5090   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
5091   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
5092   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
5093   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
5094   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
5095   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
5096   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
5097   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
5098                                                                Subtarget);
5099   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
5100   case ISD::SHL:
5101   case ISD::SRL:
5102   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
5103   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
5104   case ISD::SRL_PARTS:
5105   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
5106   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
5107   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
5108   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
5109   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5110   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5111   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5112   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
5113   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
5114   case ISD::MUL:           return LowerMUL(Op, DAG);
5115   case ISD::SDIV:          return LowerSDIV(Op, DAG);
5116   case ISD::UDIV:          return LowerUDIV(Op, DAG);
5117   case ISD::ADDC:
5118   case ISD::ADDE:
5119   case ISD::SUBC:
5120   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
5121   case ISD::ATOMIC_LOAD:
5122   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
5123   }
5124 }
5125
5126 /// ReplaceNodeResults - Replace the results of node with an illegal result
5127 /// type with new values built out of custom code.
5128 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
5129                                            SmallVectorImpl<SDValue>&Results,
5130                                            SelectionDAG &DAG) const {
5131   SDValue Res;
5132   switch (N->getOpcode()) {
5133   default:
5134     llvm_unreachable("Don't know how to custom expand this!");
5135   case ISD::BITCAST:
5136     Res = ExpandBITCAST(N, DAG);
5137     break;
5138   case ISD::SRL:
5139   case ISD::SRA:
5140     Res = Expand64BitShift(N, DAG, Subtarget);
5141     break;
5142   case ISD::ATOMIC_LOAD_ADD:
5143     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMADD64_DAG);
5144     return;
5145   case ISD::ATOMIC_LOAD_AND:
5146     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMAND64_DAG);
5147     return;
5148   case ISD::ATOMIC_LOAD_NAND:
5149     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMNAND64_DAG);
5150     return;
5151   case ISD::ATOMIC_LOAD_OR:
5152     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMOR64_DAG);
5153     return;
5154   case ISD::ATOMIC_LOAD_SUB:
5155     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSUB64_DAG);
5156     return;
5157   case ISD::ATOMIC_LOAD_XOR:
5158     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMXOR64_DAG);
5159     return;
5160   case ISD::ATOMIC_SWAP:
5161     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMSWAP64_DAG);
5162     return;
5163   case ISD::ATOMIC_CMP_SWAP:
5164     ReplaceATOMIC_OP_64(N, Results, DAG, ARMISD::ATOMCMPXCHG64_DAG);
5165     return;
5166   }
5167   if (Res.getNode())
5168     Results.push_back(Res);
5169 }
5170
5171 //===----------------------------------------------------------------------===//
5172 //                           ARM Scheduler Hooks
5173 //===----------------------------------------------------------------------===//
5174
5175 MachineBasicBlock *
5176 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
5177                                      MachineBasicBlock *BB,
5178                                      unsigned Size) const {
5179   unsigned dest    = MI->getOperand(0).getReg();
5180   unsigned ptr     = MI->getOperand(1).getReg();
5181   unsigned oldval  = MI->getOperand(2).getReg();
5182   unsigned newval  = MI->getOperand(3).getReg();
5183   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5184   DebugLoc dl = MI->getDebugLoc();
5185   bool isThumb2 = Subtarget->isThumb2();
5186
5187   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5188   unsigned scratch =
5189     MRI.createVirtualRegister(isThumb2 ? ARM::rGPRRegisterClass
5190                                        : ARM::GPRRegisterClass);
5191
5192   if (isThumb2) {
5193     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5194     MRI.constrainRegClass(oldval, ARM::rGPRRegisterClass);
5195     MRI.constrainRegClass(newval, ARM::rGPRRegisterClass);
5196   }
5197
5198   unsigned ldrOpc, strOpc;
5199   switch (Size) {
5200   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5201   case 1:
5202     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5203     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5204     break;
5205   case 2:
5206     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5207     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5208     break;
5209   case 4:
5210     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5211     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5212     break;
5213   }
5214
5215   MachineFunction *MF = BB->getParent();
5216   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5217   MachineFunction::iterator It = BB;
5218   ++It; // insert the new blocks after the current block
5219
5220   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5221   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
5222   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5223   MF->insert(It, loop1MBB);
5224   MF->insert(It, loop2MBB);
5225   MF->insert(It, exitMBB);
5226
5227   // Transfer the remainder of BB and its successor edges to exitMBB.
5228   exitMBB->splice(exitMBB->begin(), BB,
5229                   llvm::next(MachineBasicBlock::iterator(MI)),
5230                   BB->end());
5231   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5232
5233   //  thisMBB:
5234   //   ...
5235   //   fallthrough --> loop1MBB
5236   BB->addSuccessor(loop1MBB);
5237
5238   // loop1MBB:
5239   //   ldrex dest, [ptr]
5240   //   cmp dest, oldval
5241   //   bne exitMBB
5242   BB = loop1MBB;
5243   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5244   if (ldrOpc == ARM::t2LDREX)
5245     MIB.addImm(0);
5246   AddDefaultPred(MIB);
5247   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5248                  .addReg(dest).addReg(oldval));
5249   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5250     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5251   BB->addSuccessor(loop2MBB);
5252   BB->addSuccessor(exitMBB);
5253
5254   // loop2MBB:
5255   //   strex scratch, newval, [ptr]
5256   //   cmp scratch, #0
5257   //   bne loop1MBB
5258   BB = loop2MBB;
5259   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
5260   if (strOpc == ARM::t2STREX)
5261     MIB.addImm(0);
5262   AddDefaultPred(MIB);
5263   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5264                  .addReg(scratch).addImm(0));
5265   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5266     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5267   BB->addSuccessor(loop1MBB);
5268   BB->addSuccessor(exitMBB);
5269
5270   //  exitMBB:
5271   //   ...
5272   BB = exitMBB;
5273
5274   MI->eraseFromParent();   // The instruction is gone now.
5275
5276   return BB;
5277 }
5278
5279 MachineBasicBlock *
5280 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5281                                     unsigned Size, unsigned BinOpcode) const {
5282   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5283   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5284
5285   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5286   MachineFunction *MF = BB->getParent();
5287   MachineFunction::iterator It = BB;
5288   ++It;
5289
5290   unsigned dest = MI->getOperand(0).getReg();
5291   unsigned ptr = MI->getOperand(1).getReg();
5292   unsigned incr = MI->getOperand(2).getReg();
5293   DebugLoc dl = MI->getDebugLoc();
5294   bool isThumb2 = Subtarget->isThumb2();
5295
5296   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5297   if (isThumb2) {
5298     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5299     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5300   }
5301
5302   unsigned ldrOpc, strOpc;
5303   switch (Size) {
5304   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5305   case 1:
5306     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5307     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5308     break;
5309   case 2:
5310     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5311     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5312     break;
5313   case 4:
5314     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5315     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5316     break;
5317   }
5318
5319   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5320   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5321   MF->insert(It, loopMBB);
5322   MF->insert(It, exitMBB);
5323
5324   // Transfer the remainder of BB and its successor edges to exitMBB.
5325   exitMBB->splice(exitMBB->begin(), BB,
5326                   llvm::next(MachineBasicBlock::iterator(MI)),
5327                   BB->end());
5328   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5329
5330   const TargetRegisterClass *TRC =
5331     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5332   unsigned scratch = MRI.createVirtualRegister(TRC);
5333   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
5334
5335   //  thisMBB:
5336   //   ...
5337   //   fallthrough --> loopMBB
5338   BB->addSuccessor(loopMBB);
5339
5340   //  loopMBB:
5341   //   ldrex dest, ptr
5342   //   <binop> scratch2, dest, incr
5343   //   strex scratch, scratch2, ptr
5344   //   cmp scratch, #0
5345   //   bne- loopMBB
5346   //   fallthrough --> exitMBB
5347   BB = loopMBB;
5348   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5349   if (ldrOpc == ARM::t2LDREX)
5350     MIB.addImm(0);
5351   AddDefaultPred(MIB);
5352   if (BinOpcode) {
5353     // operand order needs to go the other way for NAND
5354     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
5355       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5356                      addReg(incr).addReg(dest)).addReg(0);
5357     else
5358       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
5359                      addReg(dest).addReg(incr)).addReg(0);
5360   }
5361
5362   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5363   if (strOpc == ARM::t2STREX)
5364     MIB.addImm(0);
5365   AddDefaultPred(MIB);
5366   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5367                  .addReg(scratch).addImm(0));
5368   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5369     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5370
5371   BB->addSuccessor(loopMBB);
5372   BB->addSuccessor(exitMBB);
5373
5374   //  exitMBB:
5375   //   ...
5376   BB = exitMBB;
5377
5378   MI->eraseFromParent();   // The instruction is gone now.
5379
5380   return BB;
5381 }
5382
5383 MachineBasicBlock *
5384 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
5385                                           MachineBasicBlock *BB,
5386                                           unsigned Size,
5387                                           bool signExtend,
5388                                           ARMCC::CondCodes Cond) const {
5389   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5390
5391   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5392   MachineFunction *MF = BB->getParent();
5393   MachineFunction::iterator It = BB;
5394   ++It;
5395
5396   unsigned dest = MI->getOperand(0).getReg();
5397   unsigned ptr = MI->getOperand(1).getReg();
5398   unsigned incr = MI->getOperand(2).getReg();
5399   unsigned oldval = dest;
5400   DebugLoc dl = MI->getDebugLoc();
5401   bool isThumb2 = Subtarget->isThumb2();
5402
5403   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5404   if (isThumb2) {
5405     MRI.constrainRegClass(dest, ARM::rGPRRegisterClass);
5406     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5407   }
5408
5409   unsigned ldrOpc, strOpc, extendOpc;
5410   switch (Size) {
5411   default: llvm_unreachable("unsupported size for AtomicCmpSwap!");
5412   case 1:
5413     ldrOpc = isThumb2 ? ARM::t2LDREXB : ARM::LDREXB;
5414     strOpc = isThumb2 ? ARM::t2STREXB : ARM::STREXB;
5415     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
5416     break;
5417   case 2:
5418     ldrOpc = isThumb2 ? ARM::t2LDREXH : ARM::LDREXH;
5419     strOpc = isThumb2 ? ARM::t2STREXH : ARM::STREXH;
5420     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
5421     break;
5422   case 4:
5423     ldrOpc = isThumb2 ? ARM::t2LDREX : ARM::LDREX;
5424     strOpc = isThumb2 ? ARM::t2STREX : ARM::STREX;
5425     extendOpc = 0;
5426     break;
5427   }
5428
5429   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5430   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5431   MF->insert(It, loopMBB);
5432   MF->insert(It, exitMBB);
5433
5434   // Transfer the remainder of BB and its successor edges to exitMBB.
5435   exitMBB->splice(exitMBB->begin(), BB,
5436                   llvm::next(MachineBasicBlock::iterator(MI)),
5437                   BB->end());
5438   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5439
5440   const TargetRegisterClass *TRC =
5441     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5442   unsigned scratch = MRI.createVirtualRegister(TRC);
5443   unsigned scratch2 = MRI.createVirtualRegister(TRC);
5444
5445   //  thisMBB:
5446   //   ...
5447   //   fallthrough --> loopMBB
5448   BB->addSuccessor(loopMBB);
5449
5450   //  loopMBB:
5451   //   ldrex dest, ptr
5452   //   (sign extend dest, if required)
5453   //   cmp dest, incr
5454   //   cmov.cond scratch2, dest, incr
5455   //   strex scratch, scratch2, ptr
5456   //   cmp scratch, #0
5457   //   bne- loopMBB
5458   //   fallthrough --> exitMBB
5459   BB = loopMBB;
5460   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
5461   if (ldrOpc == ARM::t2LDREX)
5462     MIB.addImm(0);
5463   AddDefaultPred(MIB);
5464
5465   // Sign extend the value, if necessary.
5466   if (signExtend && extendOpc) {
5467     oldval = MRI.createVirtualRegister(ARM::GPRRegisterClass);
5468     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
5469                      .addReg(dest)
5470                      .addImm(0));
5471   }
5472
5473   // Build compare and cmov instructions.
5474   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
5475                  .addReg(oldval).addReg(incr));
5476   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
5477          .addReg(oldval).addReg(incr).addImm(Cond).addReg(ARM::CPSR);
5478
5479   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
5480   if (strOpc == ARM::t2STREX)
5481     MIB.addImm(0);
5482   AddDefaultPred(MIB);
5483   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5484                  .addReg(scratch).addImm(0));
5485   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5486     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5487
5488   BB->addSuccessor(loopMBB);
5489   BB->addSuccessor(exitMBB);
5490
5491   //  exitMBB:
5492   //   ...
5493   BB = exitMBB;
5494
5495   MI->eraseFromParent();   // The instruction is gone now.
5496
5497   return BB;
5498 }
5499
5500 MachineBasicBlock *
5501 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
5502                                       unsigned Op1, unsigned Op2,
5503                                       bool NeedsCarry, bool IsCmpxchg) const {
5504   // This also handles ATOMIC_SWAP, indicated by Op1==0.
5505   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5506
5507   const BasicBlock *LLVM_BB = BB->getBasicBlock();
5508   MachineFunction *MF = BB->getParent();
5509   MachineFunction::iterator It = BB;
5510   ++It;
5511
5512   unsigned destlo = MI->getOperand(0).getReg();
5513   unsigned desthi = MI->getOperand(1).getReg();
5514   unsigned ptr = MI->getOperand(2).getReg();
5515   unsigned vallo = MI->getOperand(3).getReg();
5516   unsigned valhi = MI->getOperand(4).getReg();
5517   DebugLoc dl = MI->getDebugLoc();
5518   bool isThumb2 = Subtarget->isThumb2();
5519
5520   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
5521   if (isThumb2) {
5522     MRI.constrainRegClass(destlo, ARM::rGPRRegisterClass);
5523     MRI.constrainRegClass(desthi, ARM::rGPRRegisterClass);
5524     MRI.constrainRegClass(ptr, ARM::rGPRRegisterClass);
5525   }
5526
5527   unsigned ldrOpc = isThumb2 ? ARM::t2LDREXD : ARM::LDREXD;
5528   unsigned strOpc = isThumb2 ? ARM::t2STREXD : ARM::STREXD;
5529
5530   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5531   MachineBasicBlock *contBB = 0, *cont2BB = 0;
5532   if (IsCmpxchg) {
5533     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
5534     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
5535   }
5536   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
5537   MF->insert(It, loopMBB);
5538   if (IsCmpxchg) {
5539     MF->insert(It, contBB);
5540     MF->insert(It, cont2BB);
5541   }
5542   MF->insert(It, exitMBB);
5543
5544   // Transfer the remainder of BB and its successor edges to exitMBB.
5545   exitMBB->splice(exitMBB->begin(), BB,
5546                   llvm::next(MachineBasicBlock::iterator(MI)),
5547                   BB->end());
5548   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5549
5550   const TargetRegisterClass *TRC =
5551     isThumb2 ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5552   unsigned storesuccess = MRI.createVirtualRegister(TRC);
5553
5554   //  thisMBB:
5555   //   ...
5556   //   fallthrough --> loopMBB
5557   BB->addSuccessor(loopMBB);
5558
5559   //  loopMBB:
5560   //   ldrexd r2, r3, ptr
5561   //   <binopa> r0, r2, incr
5562   //   <binopb> r1, r3, incr
5563   //   strexd storesuccess, r0, r1, ptr
5564   //   cmp storesuccess, #0
5565   //   bne- loopMBB
5566   //   fallthrough --> exitMBB
5567   //
5568   // Note that the registers are explicitly specified because there is not any
5569   // way to force the register allocator to allocate a register pair.
5570   //
5571   // FIXME: The hardcoded registers are not necessary for Thumb2, but we
5572   // need to properly enforce the restriction that the two output registers
5573   // for ldrexd must be different.
5574   BB = loopMBB;
5575   // Load
5576   AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
5577                  .addReg(ARM::R2, RegState::Define)
5578                  .addReg(ARM::R3, RegState::Define).addReg(ptr));
5579   // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
5580   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo).addReg(ARM::R2);
5581   BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi).addReg(ARM::R3);
5582
5583   if (IsCmpxchg) {
5584     // Add early exit
5585     for (unsigned i = 0; i < 2; i++) {
5586       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
5587                                                          ARM::CMPrr))
5588                      .addReg(i == 0 ? destlo : desthi)
5589                      .addReg(i == 0 ? vallo : valhi));
5590       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5591         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5592       BB->addSuccessor(exitMBB);
5593       BB->addSuccessor(i == 0 ? contBB : cont2BB);
5594       BB = (i == 0 ? contBB : cont2BB);
5595     }
5596
5597     // Copy to physregs for strexd
5598     unsigned setlo = MI->getOperand(5).getReg();
5599     unsigned sethi = MI->getOperand(6).getReg();
5600     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(setlo);
5601     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(sethi);
5602   } else if (Op1) {
5603     // Perform binary operation
5604     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), ARM::R0)
5605                    .addReg(destlo).addReg(vallo))
5606         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
5607     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), ARM::R1)
5608                    .addReg(desthi).addReg(valhi)).addReg(0);
5609   } else {
5610     // Copy to physregs for strexd
5611     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R0).addReg(vallo);
5612     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), ARM::R1).addReg(valhi);
5613   }
5614
5615   // Store
5616   AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
5617                  .addReg(ARM::R0).addReg(ARM::R1).addReg(ptr));
5618   // Cmp+jump
5619   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
5620                  .addReg(storesuccess).addImm(0));
5621   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
5622     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
5623
5624   BB->addSuccessor(loopMBB);
5625   BB->addSuccessor(exitMBB);
5626
5627   //  exitMBB:
5628   //   ...
5629   BB = exitMBB;
5630
5631   MI->eraseFromParent();   // The instruction is gone now.
5632
5633   return BB;
5634 }
5635
5636 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
5637 /// registers the function context.
5638 void ARMTargetLowering::
5639 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
5640                        MachineBasicBlock *DispatchBB, int FI) const {
5641   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5642   DebugLoc dl = MI->getDebugLoc();
5643   MachineFunction *MF = MBB->getParent();
5644   MachineRegisterInfo *MRI = &MF->getRegInfo();
5645   MachineConstantPool *MCP = MF->getConstantPool();
5646   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5647   const Function *F = MF->getFunction();
5648
5649   bool isThumb = Subtarget->isThumb();
5650   bool isThumb2 = Subtarget->isThumb2();
5651
5652   unsigned PCLabelId = AFI->createPICLabelUId();
5653   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
5654   ARMConstantPoolValue *CPV =
5655     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
5656   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
5657
5658   const TargetRegisterClass *TRC =
5659     isThumb ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5660
5661   // Grab constant pool and fixed stack memory operands.
5662   MachineMemOperand *CPMMO =
5663     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
5664                              MachineMemOperand::MOLoad, 4, 4);
5665
5666   MachineMemOperand *FIMMOSt =
5667     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5668                              MachineMemOperand::MOStore, 4, 4);
5669
5670   // Load the address of the dispatch MBB into the jump buffer.
5671   if (isThumb2) {
5672     // Incoming value: jbuf
5673     //   ldr.n  r5, LCPI1_1
5674     //   orr    r5, r5, #1
5675     //   add    r5, pc
5676     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
5677     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5678     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
5679                    .addConstantPoolIndex(CPI)
5680                    .addMemOperand(CPMMO));
5681     // Set the low bit because of thumb mode.
5682     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5683     AddDefaultCC(
5684       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
5685                      .addReg(NewVReg1, RegState::Kill)
5686                      .addImm(0x01)));
5687     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5688     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
5689       .addReg(NewVReg2, RegState::Kill)
5690       .addImm(PCLabelId);
5691     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
5692                    .addReg(NewVReg3, RegState::Kill)
5693                    .addFrameIndex(FI)
5694                    .addImm(36)  // &jbuf[1] :: pc
5695                    .addMemOperand(FIMMOSt));
5696   } else if (isThumb) {
5697     // Incoming value: jbuf
5698     //   ldr.n  r1, LCPI1_4
5699     //   add    r1, pc
5700     //   mov    r2, #1
5701     //   orrs   r1, r2
5702     //   add    r2, $jbuf, #+4 ; &jbuf[1]
5703     //   str    r1, [r2]
5704     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5705     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
5706                    .addConstantPoolIndex(CPI)
5707                    .addMemOperand(CPMMO));
5708     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5709     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
5710       .addReg(NewVReg1, RegState::Kill)
5711       .addImm(PCLabelId);
5712     // Set the low bit because of thumb mode.
5713     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5714     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
5715                    .addReg(ARM::CPSR, RegState::Define)
5716                    .addImm(1));
5717     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5718     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
5719                    .addReg(ARM::CPSR, RegState::Define)
5720                    .addReg(NewVReg2, RegState::Kill)
5721                    .addReg(NewVReg3, RegState::Kill));
5722     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5723     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
5724                    .addFrameIndex(FI)
5725                    .addImm(36)); // &jbuf[1] :: pc
5726     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
5727                    .addReg(NewVReg4, RegState::Kill)
5728                    .addReg(NewVReg5, RegState::Kill)
5729                    .addImm(0)
5730                    .addMemOperand(FIMMOSt));
5731   } else {
5732     // Incoming value: jbuf
5733     //   ldr  r1, LCPI1_1
5734     //   add  r1, pc, r1
5735     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
5736     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5737     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
5738                    .addConstantPoolIndex(CPI)
5739                    .addImm(0)
5740                    .addMemOperand(CPMMO));
5741     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5742     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
5743                    .addReg(NewVReg1, RegState::Kill)
5744                    .addImm(PCLabelId));
5745     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
5746                    .addReg(NewVReg2, RegState::Kill)
5747                    .addFrameIndex(FI)
5748                    .addImm(36)  // &jbuf[1] :: pc
5749                    .addMemOperand(FIMMOSt));
5750   }
5751 }
5752
5753 MachineBasicBlock *ARMTargetLowering::
5754 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
5755   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5756   DebugLoc dl = MI->getDebugLoc();
5757   MachineFunction *MF = MBB->getParent();
5758   MachineRegisterInfo *MRI = &MF->getRegInfo();
5759   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
5760   MachineFrameInfo *MFI = MF->getFrameInfo();
5761   int FI = MFI->getFunctionContextIndex();
5762
5763   const TargetRegisterClass *TRC =
5764     Subtarget->isThumb() ? ARM::tGPRRegisterClass : ARM::GPRRegisterClass;
5765
5766   // Get a mapping of the call site numbers to all of the landing pads they're
5767   // associated with.
5768   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
5769   unsigned MaxCSNum = 0;
5770   MachineModuleInfo &MMI = MF->getMMI();
5771   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E; ++BB) {
5772     if (!BB->isLandingPad()) continue;
5773
5774     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
5775     // pad.
5776     for (MachineBasicBlock::iterator
5777            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
5778       if (!II->isEHLabel()) continue;
5779
5780       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
5781       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
5782
5783       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
5784       for (SmallVectorImpl<unsigned>::iterator
5785              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
5786            CSI != CSE; ++CSI) {
5787         CallSiteNumToLPad[*CSI].push_back(BB);
5788         MaxCSNum = std::max(MaxCSNum, *CSI);
5789       }
5790       break;
5791     }
5792   }
5793
5794   // Get an ordered list of the machine basic blocks for the jump table.
5795   std::vector<MachineBasicBlock*> LPadList;
5796   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
5797   LPadList.reserve(CallSiteNumToLPad.size());
5798   for (unsigned I = 1; I <= MaxCSNum; ++I) {
5799     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
5800     for (SmallVectorImpl<MachineBasicBlock*>::iterator
5801            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
5802       LPadList.push_back(*II);
5803       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
5804     }
5805   }
5806
5807   assert(!LPadList.empty() &&
5808          "No landing pad destinations for the dispatch jump table!");
5809
5810   // Create the jump table and associated information.
5811   MachineJumpTableInfo *JTI =
5812     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
5813   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
5814   unsigned UId = AFI->createJumpTableUId();
5815
5816   // Create the MBBs for the dispatch code.
5817
5818   // Shove the dispatch's address into the return slot in the function context.
5819   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
5820   DispatchBB->setIsLandingPad();
5821
5822   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
5823   BuildMI(TrapBB, dl, TII->get(Subtarget->isThumb() ? ARM::tTRAP : ARM::TRAP));
5824   DispatchBB->addSuccessor(TrapBB);
5825
5826   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
5827   DispatchBB->addSuccessor(DispContBB);
5828
5829   // Insert and MBBs.
5830   MF->insert(MF->end(), DispatchBB);
5831   MF->insert(MF->end(), DispContBB);
5832   MF->insert(MF->end(), TrapBB);
5833
5834   // Insert code into the entry block that creates and registers the function
5835   // context.
5836   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
5837
5838   MachineMemOperand *FIMMOLd =
5839     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
5840                              MachineMemOperand::MOLoad |
5841                              MachineMemOperand::MOVolatile, 4, 4);
5842
5843   if (AFI->isThumb1OnlyFunction())
5844     BuildMI(DispatchBB, dl, TII->get(ARM::tInt_eh_sjlj_dispatchsetup));
5845   else if (!Subtarget->hasVFP2())
5846     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup_nofp));
5847   else 
5848     BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
5849
5850   unsigned NumLPads = LPadList.size();
5851   if (Subtarget->isThumb2()) {
5852     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5853     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
5854                    .addFrameIndex(FI)
5855                    .addImm(4)
5856                    .addMemOperand(FIMMOLd));
5857
5858     if (NumLPads < 256) {
5859       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
5860                      .addReg(NewVReg1)
5861                      .addImm(LPadList.size()));
5862     } else {
5863       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5864       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
5865                      .addImm(NumLPads & 0xFFFF));
5866
5867       unsigned VReg2 = VReg1;
5868       if ((NumLPads & 0xFFFF0000) != 0) {
5869         VReg2 = MRI->createVirtualRegister(TRC);
5870         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
5871                        .addReg(VReg1)
5872                        .addImm(NumLPads >> 16));
5873       }
5874
5875       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
5876                      .addReg(NewVReg1)
5877                      .addReg(VReg2));
5878     }
5879
5880     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
5881       .addMBB(TrapBB)
5882       .addImm(ARMCC::HI)
5883       .addReg(ARM::CPSR);
5884
5885     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5886     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
5887                    .addJumpTableIndex(MJTI)
5888                    .addImm(UId));
5889
5890     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5891     AddDefaultCC(
5892       AddDefaultPred(
5893         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
5894         .addReg(NewVReg3, RegState::Kill)
5895         .addReg(NewVReg1)
5896         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
5897
5898     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
5899       .addReg(NewVReg4, RegState::Kill)
5900       .addReg(NewVReg1)
5901       .addJumpTableIndex(MJTI)
5902       .addImm(UId);
5903   } else if (Subtarget->isThumb()) {
5904     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5905     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
5906                    .addFrameIndex(FI)
5907                    .addImm(1)
5908                    .addMemOperand(FIMMOLd));
5909
5910     if (NumLPads < 256) {
5911       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
5912                      .addReg(NewVReg1)
5913                      .addImm(NumLPads));
5914     } else {
5915       MachineConstantPool *ConstantPool = MF->getConstantPool();
5916       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
5917       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
5918
5919       // MachineConstantPool wants an explicit alignment.
5920       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
5921       if (Align == 0)
5922         Align = getTargetData()->getTypeAllocSize(C->getType());
5923       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
5924
5925       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5926       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
5927                      .addReg(VReg1, RegState::Define)
5928                      .addConstantPoolIndex(Idx));
5929       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
5930                      .addReg(NewVReg1)
5931                      .addReg(VReg1));
5932     }
5933
5934     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
5935       .addMBB(TrapBB)
5936       .addImm(ARMCC::HI)
5937       .addReg(ARM::CPSR);
5938
5939     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
5940     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
5941                    .addReg(ARM::CPSR, RegState::Define)
5942                    .addReg(NewVReg1)
5943                    .addImm(2));
5944
5945     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
5946     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
5947                    .addJumpTableIndex(MJTI)
5948                    .addImm(UId));
5949
5950     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
5951     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
5952                    .addReg(ARM::CPSR, RegState::Define)
5953                    .addReg(NewVReg2, RegState::Kill)
5954                    .addReg(NewVReg3));
5955
5956     MachineMemOperand *JTMMOLd =
5957       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
5958                                MachineMemOperand::MOLoad, 4, 4);
5959
5960     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
5961     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
5962                    .addReg(NewVReg4, RegState::Kill)
5963                    .addImm(0)
5964                    .addMemOperand(JTMMOLd));
5965
5966     unsigned NewVReg6 = MRI->createVirtualRegister(TRC);
5967     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
5968                    .addReg(ARM::CPSR, RegState::Define)
5969                    .addReg(NewVReg5, RegState::Kill)
5970                    .addReg(NewVReg3));
5971
5972     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
5973       .addReg(NewVReg6, RegState::Kill)
5974       .addJumpTableIndex(MJTI)
5975       .addImm(UId);
5976   } else {
5977     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
5978     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
5979                    .addFrameIndex(FI)
5980                    .addImm(4)
5981                    .addMemOperand(FIMMOLd));
5982
5983     if (NumLPads < 256) {
5984       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
5985                      .addReg(NewVReg1)
5986                      .addImm(NumLPads));
5987     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
5988       unsigned VReg1 = MRI->createVirtualRegister(TRC);
5989       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
5990                      .addImm(NumLPads & 0xFFFF));
5991
5992       unsigned VReg2 = VReg1;
5993       if ((NumLPads & 0xFFFF0000) != 0) {
5994         VReg2 = MRI->createVirtualRegister(TRC);
5995         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
5996                        .addReg(VReg1)
5997                        .addImm(NumLPads >> 16));
5998       }
5999
6000       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6001                      .addReg(NewVReg1)
6002                      .addReg(VReg2));
6003     } else {
6004       MachineConstantPool *ConstantPool = MF->getConstantPool();
6005       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6006       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6007
6008       // MachineConstantPool wants an explicit alignment.
6009       unsigned Align = getTargetData()->getPrefTypeAlignment(Int32Ty);
6010       if (Align == 0)
6011         Align = getTargetData()->getTypeAllocSize(C->getType());
6012       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6013
6014       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6015       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6016                      .addReg(VReg1, RegState::Define)
6017                      .addConstantPoolIndex(Idx)
6018                      .addImm(0));
6019       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6020                      .addReg(NewVReg1)
6021                      .addReg(VReg1, RegState::Kill));
6022     }
6023
6024     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6025       .addMBB(TrapBB)
6026       .addImm(ARMCC::HI)
6027       .addReg(ARM::CPSR);
6028
6029     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6030     AddDefaultCC(
6031       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6032                      .addReg(NewVReg1)
6033                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6034     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6035     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6036                    .addJumpTableIndex(MJTI)
6037                    .addImm(UId));
6038
6039     MachineMemOperand *JTMMOLd =
6040       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6041                                MachineMemOperand::MOLoad, 4, 4);
6042     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6043     AddDefaultPred(
6044       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6045       .addReg(NewVReg3, RegState::Kill)
6046       .addReg(NewVReg4)
6047       .addImm(0)
6048       .addMemOperand(JTMMOLd));
6049
6050     BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6051       .addReg(NewVReg5, RegState::Kill)
6052       .addReg(NewVReg4)
6053       .addJumpTableIndex(MJTI)
6054       .addImm(UId);
6055   }
6056
6057   // Add the jump table entries as successors to the MBB.
6058   MachineBasicBlock *PrevMBB = 0;
6059   for (std::vector<MachineBasicBlock*>::iterator
6060          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6061     MachineBasicBlock *CurMBB = *I;
6062     if (PrevMBB != CurMBB)
6063       DispContBB->addSuccessor(CurMBB);
6064     PrevMBB = CurMBB;
6065   }
6066
6067   // N.B. the order the invoke BBs are processed in doesn't matter here.
6068   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6069   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6070   const unsigned *SavedRegs = RI.getCalleeSavedRegs(MF);
6071   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6072   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6073          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6074     MachineBasicBlock *BB = *I;
6075
6076     // Remove the landing pad successor from the invoke block and replace it
6077     // with the new dispatch block.
6078     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6079                                                   BB->succ_end());
6080     while (!Successors.empty()) {
6081       MachineBasicBlock *SMBB = Successors.pop_back_val();
6082       if (SMBB->isLandingPad()) {
6083         BB->removeSuccessor(SMBB);
6084         MBBLPads.push_back(SMBB);
6085       }
6086     }
6087
6088     BB->addSuccessor(DispatchBB);
6089
6090     // Find the invoke call and mark all of the callee-saved registers as
6091     // 'implicit defined' so that they're spilled. This prevents code from
6092     // moving instructions to before the EH block, where they will never be
6093     // executed.
6094     for (MachineBasicBlock::reverse_iterator
6095            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6096       if (!II->isCall()) continue;
6097
6098       DenseMap<unsigned, bool> DefRegs;
6099       for (MachineInstr::mop_iterator
6100              OI = II->operands_begin(), OE = II->operands_end();
6101            OI != OE; ++OI) {
6102         if (!OI->isReg()) continue;
6103         DefRegs[OI->getReg()] = true;
6104       }
6105
6106       MachineInstrBuilder MIB(&*II);
6107
6108       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6109         unsigned Reg = SavedRegs[i];
6110         if (Subtarget->isThumb2() &&
6111             !ARM::tGPRRegisterClass->contains(Reg) &&
6112             !ARM::hGPRRegisterClass->contains(Reg))
6113           continue;
6114         else if (Subtarget->isThumb1Only() &&
6115                  !ARM::tGPRRegisterClass->contains(Reg))
6116           continue;
6117         else if (!Subtarget->isThumb() &&
6118                  !ARM::GPRRegisterClass->contains(Reg))
6119           continue;
6120         if (!DefRegs[Reg])
6121           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6122       }
6123
6124       break;
6125     }
6126   }
6127
6128   // Mark all former landing pads as non-landing pads. The dispatch is the only
6129   // landing pad now.
6130   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6131          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6132     (*I)->setIsLandingPad(false);
6133
6134   // The instruction is gone now.
6135   MI->eraseFromParent();
6136
6137   return MBB;
6138 }
6139
6140 static
6141 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6142   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6143        E = MBB->succ_end(); I != E; ++I)
6144     if (*I != Succ)
6145       return *I;
6146   llvm_unreachable("Expecting a BB with two successors!");
6147 }
6148
6149 MachineBasicBlock *
6150 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6151                                                MachineBasicBlock *BB) const {
6152   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6153   DebugLoc dl = MI->getDebugLoc();
6154   bool isThumb2 = Subtarget->isThumb2();
6155   switch (MI->getOpcode()) {
6156   default: {
6157     MI->dump();
6158     llvm_unreachable("Unexpected instr type to insert");
6159   }
6160   // The Thumb2 pre-indexed stores have the same MI operands, they just
6161   // define them differently in the .td files from the isel patterns, so
6162   // they need pseudos.
6163   case ARM::t2STR_preidx:
6164     MI->setDesc(TII->get(ARM::t2STR_PRE));
6165     return BB;
6166   case ARM::t2STRB_preidx:
6167     MI->setDesc(TII->get(ARM::t2STRB_PRE));
6168     return BB;
6169   case ARM::t2STRH_preidx:
6170     MI->setDesc(TII->get(ARM::t2STRH_PRE));
6171     return BB;
6172
6173   case ARM::STRi_preidx:
6174   case ARM::STRBi_preidx: {
6175     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
6176       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
6177     // Decode the offset.
6178     unsigned Offset = MI->getOperand(4).getImm();
6179     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
6180     Offset = ARM_AM::getAM2Offset(Offset);
6181     if (isSub)
6182       Offset = -Offset;
6183
6184     MachineMemOperand *MMO = *MI->memoperands_begin();
6185     BuildMI(*BB, MI, dl, TII->get(NewOpc))
6186       .addOperand(MI->getOperand(0))  // Rn_wb
6187       .addOperand(MI->getOperand(1))  // Rt
6188       .addOperand(MI->getOperand(2))  // Rn
6189       .addImm(Offset)                 // offset (skip GPR==zero_reg)
6190       .addOperand(MI->getOperand(5))  // pred
6191       .addOperand(MI->getOperand(6))
6192       .addMemOperand(MMO);
6193     MI->eraseFromParent();
6194     return BB;
6195   }
6196   case ARM::STRr_preidx:
6197   case ARM::STRBr_preidx:
6198   case ARM::STRH_preidx: {
6199     unsigned NewOpc;
6200     switch (MI->getOpcode()) {
6201     default: llvm_unreachable("unexpected opcode!");
6202     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
6203     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
6204     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
6205     }
6206     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
6207     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
6208       MIB.addOperand(MI->getOperand(i));
6209     MI->eraseFromParent();
6210     return BB;
6211   }
6212   case ARM::ATOMIC_LOAD_ADD_I8:
6213      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6214   case ARM::ATOMIC_LOAD_ADD_I16:
6215      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6216   case ARM::ATOMIC_LOAD_ADD_I32:
6217      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
6218
6219   case ARM::ATOMIC_LOAD_AND_I8:
6220      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6221   case ARM::ATOMIC_LOAD_AND_I16:
6222      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6223   case ARM::ATOMIC_LOAD_AND_I32:
6224      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6225
6226   case ARM::ATOMIC_LOAD_OR_I8:
6227      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6228   case ARM::ATOMIC_LOAD_OR_I16:
6229      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6230   case ARM::ATOMIC_LOAD_OR_I32:
6231      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6232
6233   case ARM::ATOMIC_LOAD_XOR_I8:
6234      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6235   case ARM::ATOMIC_LOAD_XOR_I16:
6236      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6237   case ARM::ATOMIC_LOAD_XOR_I32:
6238      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6239
6240   case ARM::ATOMIC_LOAD_NAND_I8:
6241      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6242   case ARM::ATOMIC_LOAD_NAND_I16:
6243      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6244   case ARM::ATOMIC_LOAD_NAND_I32:
6245      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
6246
6247   case ARM::ATOMIC_LOAD_SUB_I8:
6248      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6249   case ARM::ATOMIC_LOAD_SUB_I16:
6250      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6251   case ARM::ATOMIC_LOAD_SUB_I32:
6252      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
6253
6254   case ARM::ATOMIC_LOAD_MIN_I8:
6255      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
6256   case ARM::ATOMIC_LOAD_MIN_I16:
6257      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
6258   case ARM::ATOMIC_LOAD_MIN_I32:
6259      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
6260
6261   case ARM::ATOMIC_LOAD_MAX_I8:
6262      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
6263   case ARM::ATOMIC_LOAD_MAX_I16:
6264      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
6265   case ARM::ATOMIC_LOAD_MAX_I32:
6266      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
6267
6268   case ARM::ATOMIC_LOAD_UMIN_I8:
6269      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
6270   case ARM::ATOMIC_LOAD_UMIN_I16:
6271      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
6272   case ARM::ATOMIC_LOAD_UMIN_I32:
6273      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
6274
6275   case ARM::ATOMIC_LOAD_UMAX_I8:
6276      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
6277   case ARM::ATOMIC_LOAD_UMAX_I16:
6278      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
6279   case ARM::ATOMIC_LOAD_UMAX_I32:
6280      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
6281
6282   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
6283   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
6284   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
6285
6286   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
6287   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
6288   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
6289
6290
6291   case ARM::ATOMADD6432:
6292     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
6293                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
6294                               /*NeedsCarry*/ true);
6295   case ARM::ATOMSUB6432:
6296     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6297                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6298                               /*NeedsCarry*/ true);
6299   case ARM::ATOMOR6432:
6300     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
6301                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
6302   case ARM::ATOMXOR6432:
6303     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
6304                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
6305   case ARM::ATOMAND6432:
6306     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
6307                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
6308   case ARM::ATOMSWAP6432:
6309     return EmitAtomicBinary64(MI, BB, 0, 0, false);
6310   case ARM::ATOMCMPXCHG6432:
6311     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
6312                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
6313                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
6314
6315   case ARM::tMOVCCr_pseudo: {
6316     // To "insert" a SELECT_CC instruction, we actually have to insert the
6317     // diamond control-flow pattern.  The incoming instruction knows the
6318     // destination vreg to set, the condition code register to branch on, the
6319     // true/false values to select between, and a branch opcode to use.
6320     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6321     MachineFunction::iterator It = BB;
6322     ++It;
6323
6324     //  thisMBB:
6325     //  ...
6326     //   TrueVal = ...
6327     //   cmpTY ccX, r1, r2
6328     //   bCC copy1MBB
6329     //   fallthrough --> copy0MBB
6330     MachineBasicBlock *thisMBB  = BB;
6331     MachineFunction *F = BB->getParent();
6332     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6333     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
6334     F->insert(It, copy0MBB);
6335     F->insert(It, sinkMBB);
6336
6337     // Transfer the remainder of BB and its successor edges to sinkMBB.
6338     sinkMBB->splice(sinkMBB->begin(), BB,
6339                     llvm::next(MachineBasicBlock::iterator(MI)),
6340                     BB->end());
6341     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6342
6343     BB->addSuccessor(copy0MBB);
6344     BB->addSuccessor(sinkMBB);
6345
6346     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
6347       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
6348
6349     //  copy0MBB:
6350     //   %FalseValue = ...
6351     //   # fallthrough to sinkMBB
6352     BB = copy0MBB;
6353
6354     // Update machine-CFG edges
6355     BB->addSuccessor(sinkMBB);
6356
6357     //  sinkMBB:
6358     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6359     //  ...
6360     BB = sinkMBB;
6361     BuildMI(*BB, BB->begin(), dl,
6362             TII->get(ARM::PHI), MI->getOperand(0).getReg())
6363       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6364       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6365
6366     MI->eraseFromParent();   // The pseudo instruction is gone now.
6367     return BB;
6368   }
6369
6370   case ARM::BCCi64:
6371   case ARM::BCCZi64: {
6372     // If there is an unconditional branch to the other successor, remove it.
6373     BB->erase(llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
6374
6375     // Compare both parts that make up the double comparison separately for
6376     // equality.
6377     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
6378
6379     unsigned LHS1 = MI->getOperand(1).getReg();
6380     unsigned LHS2 = MI->getOperand(2).getReg();
6381     if (RHSisZero) {
6382       AddDefaultPred(BuildMI(BB, dl,
6383                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6384                      .addReg(LHS1).addImm(0));
6385       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6386         .addReg(LHS2).addImm(0)
6387         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6388     } else {
6389       unsigned RHS1 = MI->getOperand(3).getReg();
6390       unsigned RHS2 = MI->getOperand(4).getReg();
6391       AddDefaultPred(BuildMI(BB, dl,
6392                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6393                      .addReg(LHS1).addReg(RHS1));
6394       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6395         .addReg(LHS2).addReg(RHS2)
6396         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
6397     }
6398
6399     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
6400     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
6401     if (MI->getOperand(0).getImm() == ARMCC::NE)
6402       std::swap(destMBB, exitMBB);
6403
6404     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6405       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
6406     if (isThumb2)
6407       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
6408     else
6409       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
6410
6411     MI->eraseFromParent();   // The pseudo instruction is gone now.
6412     return BB;
6413   }
6414
6415   case ARM::Int_eh_sjlj_setjmp:
6416   case ARM::Int_eh_sjlj_setjmp_nofp:
6417   case ARM::tInt_eh_sjlj_setjmp:
6418   case ARM::t2Int_eh_sjlj_setjmp:
6419   case ARM::t2Int_eh_sjlj_setjmp_nofp:
6420     EmitSjLjDispatchBlock(MI, BB);
6421     return BB;
6422
6423   case ARM::ABS:
6424   case ARM::t2ABS: {
6425     // To insert an ABS instruction, we have to insert the
6426     // diamond control-flow pattern.  The incoming instruction knows the
6427     // source vreg to test against 0, the destination vreg to set,
6428     // the condition code register to branch on, the
6429     // true/false values to select between, and a branch opcode to use.
6430     // It transforms
6431     //     V1 = ABS V0
6432     // into
6433     //     V2 = MOVS V0
6434     //     BCC                      (branch to SinkBB if V0 >= 0)
6435     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
6436     //     SinkBB: V1 = PHI(V2, V3)
6437     const BasicBlock *LLVM_BB = BB->getBasicBlock();
6438     MachineFunction::iterator BBI = BB;
6439     ++BBI;
6440     MachineFunction *Fn = BB->getParent();
6441     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
6442     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
6443     Fn->insert(BBI, RSBBB);
6444     Fn->insert(BBI, SinkBB);
6445
6446     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
6447     unsigned int ABSDstReg = MI->getOperand(0).getReg();
6448     bool isThumb2 = Subtarget->isThumb2();
6449     MachineRegisterInfo &MRI = Fn->getRegInfo();
6450     // In Thumb mode S must not be specified if source register is the SP or
6451     // PC and if destination register is the SP, so restrict register class
6452     unsigned NewMovDstReg = MRI.createVirtualRegister(
6453       isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6454     unsigned NewRsbDstReg = MRI.createVirtualRegister(
6455       isThumb2 ? ARM::rGPRRegisterClass : ARM::GPRRegisterClass);
6456
6457     // Transfer the remainder of BB and its successor edges to sinkMBB.
6458     SinkBB->splice(SinkBB->begin(), BB,
6459       llvm::next(MachineBasicBlock::iterator(MI)),
6460       BB->end());
6461     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
6462
6463     BB->addSuccessor(RSBBB);
6464     BB->addSuccessor(SinkBB);
6465
6466     // fall through to SinkMBB
6467     RSBBB->addSuccessor(SinkBB);
6468
6469     // insert a movs at the end of BB
6470     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVr : ARM::MOVr),
6471       NewMovDstReg)
6472       .addReg(ABSSrcReg, RegState::Kill)
6473       .addImm((unsigned)ARMCC::AL).addReg(0)
6474       .addReg(ARM::CPSR, RegState::Define);
6475
6476     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
6477     BuildMI(BB, dl,
6478       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
6479       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
6480
6481     // insert rsbri in RSBBB
6482     // Note: BCC and rsbri will be converted into predicated rsbmi
6483     // by if-conversion pass
6484     BuildMI(*RSBBB, RSBBB->begin(), dl,
6485       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
6486       .addReg(NewMovDstReg, RegState::Kill)
6487       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
6488
6489     // insert PHI in SinkBB,
6490     // reuse ABSDstReg to not change uses of ABS instruction
6491     BuildMI(*SinkBB, SinkBB->begin(), dl,
6492       TII->get(ARM::PHI), ABSDstReg)
6493       .addReg(NewRsbDstReg).addMBB(RSBBB)
6494       .addReg(NewMovDstReg).addMBB(BB);
6495
6496     // remove ABS instruction
6497     MI->eraseFromParent();
6498
6499     // return last added BB
6500     return SinkBB;
6501   }
6502   }
6503 }
6504
6505 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
6506                                                       SDNode *Node) const {
6507   if (!MI->hasPostISelHook()) {
6508     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
6509            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
6510     return;
6511   }
6512
6513   const MCInstrDesc *MCID = &MI->getDesc();
6514   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
6515   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
6516   // operand is still set to noreg. If needed, set the optional operand's
6517   // register to CPSR, and remove the redundant implicit def.
6518   //
6519   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
6520
6521   // Rename pseudo opcodes.
6522   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
6523   if (NewOpc) {
6524     const ARMBaseInstrInfo *TII =
6525       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
6526     MCID = &TII->get(NewOpc);
6527
6528     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
6529            "converted opcode should be the same except for cc_out");
6530
6531     MI->setDesc(*MCID);
6532
6533     // Add the optional cc_out operand
6534     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
6535   }
6536   unsigned ccOutIdx = MCID->getNumOperands() - 1;
6537
6538   // Any ARM instruction that sets the 's' bit should specify an optional
6539   // "cc_out" operand in the last operand position.
6540   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
6541     assert(!NewOpc && "Optional cc_out operand required");
6542     return;
6543   }
6544   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
6545   // since we already have an optional CPSR def.
6546   bool definesCPSR = false;
6547   bool deadCPSR = false;
6548   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
6549        i != e; ++i) {
6550     const MachineOperand &MO = MI->getOperand(i);
6551     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
6552       definesCPSR = true;
6553       if (MO.isDead())
6554         deadCPSR = true;
6555       MI->RemoveOperand(i);
6556       break;
6557     }
6558   }
6559   if (!definesCPSR) {
6560     assert(!NewOpc && "Optional cc_out operand required");
6561     return;
6562   }
6563   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
6564   if (deadCPSR) {
6565     assert(!MI->getOperand(ccOutIdx).getReg() &&
6566            "expect uninitialized optional cc_out operand");
6567     return;
6568   }
6569
6570   // If this instruction was defined with an optional CPSR def and its dag node
6571   // had a live implicit CPSR def, then activate the optional CPSR def.
6572   MachineOperand &MO = MI->getOperand(ccOutIdx);
6573   MO.setReg(ARM::CPSR);
6574   MO.setIsDef(true);
6575 }
6576
6577 //===----------------------------------------------------------------------===//
6578 //                           ARM Optimization Hooks
6579 //===----------------------------------------------------------------------===//
6580
6581 static
6582 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
6583                             TargetLowering::DAGCombinerInfo &DCI) {
6584   SelectionDAG &DAG = DCI.DAG;
6585   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6586   EVT VT = N->getValueType(0);
6587   unsigned Opc = N->getOpcode();
6588   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
6589   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
6590   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
6591   ISD::CondCode CC = ISD::SETCC_INVALID;
6592
6593   if (isSlctCC) {
6594     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
6595   } else {
6596     SDValue CCOp = Slct.getOperand(0);
6597     if (CCOp.getOpcode() == ISD::SETCC)
6598       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
6599   }
6600
6601   bool DoXform = false;
6602   bool InvCC = false;
6603   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
6604           "Bad input!");
6605
6606   if (LHS.getOpcode() == ISD::Constant &&
6607       cast<ConstantSDNode>(LHS)->isNullValue()) {
6608     DoXform = true;
6609   } else if (CC != ISD::SETCC_INVALID &&
6610              RHS.getOpcode() == ISD::Constant &&
6611              cast<ConstantSDNode>(RHS)->isNullValue()) {
6612     std::swap(LHS, RHS);
6613     SDValue Op0 = Slct.getOperand(0);
6614     EVT OpVT = isSlctCC ? Op0.getValueType() :
6615                           Op0.getOperand(0).getValueType();
6616     bool isInt = OpVT.isInteger();
6617     CC = ISD::getSetCCInverse(CC, isInt);
6618
6619     if (!TLI.isCondCodeLegal(CC, OpVT))
6620       return SDValue();         // Inverse operator isn't legal.
6621
6622     DoXform = true;
6623     InvCC = true;
6624   }
6625
6626   if (DoXform) {
6627     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
6628     if (isSlctCC)
6629       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
6630                              Slct.getOperand(0), Slct.getOperand(1), CC);
6631     SDValue CCOp = Slct.getOperand(0);
6632     if (InvCC)
6633       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
6634                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
6635     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
6636                        CCOp, OtherOp, Result);
6637   }
6638   return SDValue();
6639 }
6640
6641 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
6642 // (only after legalization).
6643 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
6644                                  TargetLowering::DAGCombinerInfo &DCI,
6645                                  const ARMSubtarget *Subtarget) {
6646
6647   // Only perform optimization if after legalize, and if NEON is available. We
6648   // also expected both operands to be BUILD_VECTORs.
6649   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
6650       || N0.getOpcode() != ISD::BUILD_VECTOR
6651       || N1.getOpcode() != ISD::BUILD_VECTOR)
6652     return SDValue();
6653
6654   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
6655   EVT VT = N->getValueType(0);
6656   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
6657     return SDValue();
6658
6659   // Check that the vector operands are of the right form.
6660   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
6661   // operands, where N is the size of the formed vector.
6662   // Each EXTRACT_VECTOR should have the same input vector and odd or even
6663   // index such that we have a pair wise add pattern.
6664
6665   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
6666   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
6667     return SDValue();
6668   SDValue Vec = N0->getOperand(0)->getOperand(0);
6669   SDNode *V = Vec.getNode();
6670   unsigned nextIndex = 0;
6671
6672   // For each operands to the ADD which are BUILD_VECTORs,
6673   // check to see if each of their operands are an EXTRACT_VECTOR with
6674   // the same vector and appropriate index.
6675   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
6676     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
6677         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6678
6679       SDValue ExtVec0 = N0->getOperand(i);
6680       SDValue ExtVec1 = N1->getOperand(i);
6681
6682       // First operand is the vector, verify its the same.
6683       if (V != ExtVec0->getOperand(0).getNode() ||
6684           V != ExtVec1->getOperand(0).getNode())
6685         return SDValue();
6686
6687       // Second is the constant, verify its correct.
6688       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
6689       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
6690
6691       // For the constant, we want to see all the even or all the odd.
6692       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
6693           || C1->getZExtValue() != nextIndex+1)
6694         return SDValue();
6695
6696       // Increment index.
6697       nextIndex+=2;
6698     } else
6699       return SDValue();
6700   }
6701
6702   // Create VPADDL node.
6703   SelectionDAG &DAG = DCI.DAG;
6704   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6705
6706   // Build operand list.
6707   SmallVector<SDValue, 8> Ops;
6708   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
6709                                 TLI.getPointerTy()));
6710
6711   // Input is the vector.
6712   Ops.push_back(Vec);
6713
6714   // Get widened type and narrowed type.
6715   MVT widenType;
6716   unsigned numElem = VT.getVectorNumElements();
6717   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
6718     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
6719     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
6720     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
6721     default:
6722       llvm_unreachable("Invalid vector element type for padd optimization.");
6723   }
6724
6725   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
6726                             widenType, &Ops[0], Ops.size());
6727   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, tmp);
6728 }
6729
6730 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
6731 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
6732 /// called with the default operands, and if that fails, with commuted
6733 /// operands.
6734 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
6735                                           TargetLowering::DAGCombinerInfo &DCI,
6736                                           const ARMSubtarget *Subtarget){
6737
6738   // Attempt to create vpaddl for this add.
6739   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
6740   if (Result.getNode())
6741     return Result;
6742
6743   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
6744   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
6745     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
6746     if (Result.getNode()) return Result;
6747   }
6748   return SDValue();
6749 }
6750
6751 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
6752 ///
6753 static SDValue PerformADDCombine(SDNode *N,
6754                                  TargetLowering::DAGCombinerInfo &DCI,
6755                                  const ARMSubtarget *Subtarget) {
6756   SDValue N0 = N->getOperand(0);
6757   SDValue N1 = N->getOperand(1);
6758
6759   // First try with the default operand order.
6760   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
6761   if (Result.getNode())
6762     return Result;
6763
6764   // If that didn't work, try again with the operands commuted.
6765   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
6766 }
6767
6768 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
6769 ///
6770 static SDValue PerformSUBCombine(SDNode *N,
6771                                  TargetLowering::DAGCombinerInfo &DCI) {
6772   SDValue N0 = N->getOperand(0);
6773   SDValue N1 = N->getOperand(1);
6774
6775   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
6776   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
6777     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
6778     if (Result.getNode()) return Result;
6779   }
6780
6781   return SDValue();
6782 }
6783
6784 /// PerformVMULCombine
6785 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
6786 /// special multiplier accumulator forwarding.
6787 ///   vmul d3, d0, d2
6788 ///   vmla d3, d1, d2
6789 /// is faster than
6790 ///   vadd d3, d0, d1
6791 ///   vmul d3, d3, d2
6792 static SDValue PerformVMULCombine(SDNode *N,
6793                                   TargetLowering::DAGCombinerInfo &DCI,
6794                                   const ARMSubtarget *Subtarget) {
6795   if (!Subtarget->hasVMLxForwarding())
6796     return SDValue();
6797
6798   SelectionDAG &DAG = DCI.DAG;
6799   SDValue N0 = N->getOperand(0);
6800   SDValue N1 = N->getOperand(1);
6801   unsigned Opcode = N0.getOpcode();
6802   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6803       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
6804     Opcode = N1.getOpcode();
6805     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
6806         Opcode != ISD::FADD && Opcode != ISD::FSUB)
6807       return SDValue();
6808     std::swap(N0, N1);
6809   }
6810
6811   EVT VT = N->getValueType(0);
6812   DebugLoc DL = N->getDebugLoc();
6813   SDValue N00 = N0->getOperand(0);
6814   SDValue N01 = N0->getOperand(1);
6815   return DAG.getNode(Opcode, DL, VT,
6816                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
6817                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
6818 }
6819
6820 static SDValue PerformMULCombine(SDNode *N,
6821                                  TargetLowering::DAGCombinerInfo &DCI,
6822                                  const ARMSubtarget *Subtarget) {
6823   SelectionDAG &DAG = DCI.DAG;
6824
6825   if (Subtarget->isThumb1Only())
6826     return SDValue();
6827
6828   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
6829     return SDValue();
6830
6831   EVT VT = N->getValueType(0);
6832   if (VT.is64BitVector() || VT.is128BitVector())
6833     return PerformVMULCombine(N, DCI, Subtarget);
6834   if (VT != MVT::i32)
6835     return SDValue();
6836
6837   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
6838   if (!C)
6839     return SDValue();
6840
6841   uint64_t MulAmt = C->getZExtValue();
6842   unsigned ShiftAmt = CountTrailingZeros_64(MulAmt);
6843   ShiftAmt = ShiftAmt & (32 - 1);
6844   SDValue V = N->getOperand(0);
6845   DebugLoc DL = N->getDebugLoc();
6846
6847   SDValue Res;
6848   MulAmt >>= ShiftAmt;
6849   if (isPowerOf2_32(MulAmt - 1)) {
6850     // (mul x, 2^N + 1) => (add (shl x, N), x)
6851     Res = DAG.getNode(ISD::ADD, DL, VT,
6852                       V, DAG.getNode(ISD::SHL, DL, VT,
6853                                      V, DAG.getConstant(Log2_32(MulAmt-1),
6854                                                         MVT::i32)));
6855   } else if (isPowerOf2_32(MulAmt + 1)) {
6856     // (mul x, 2^N - 1) => (sub (shl x, N), x)
6857     Res = DAG.getNode(ISD::SUB, DL, VT,
6858                       DAG.getNode(ISD::SHL, DL, VT,
6859                                   V, DAG.getConstant(Log2_32(MulAmt+1),
6860                                                      MVT::i32)),
6861                                                      V);
6862   } else
6863     return SDValue();
6864
6865   if (ShiftAmt != 0)
6866     Res = DAG.getNode(ISD::SHL, DL, VT, Res,
6867                       DAG.getConstant(ShiftAmt, MVT::i32));
6868
6869   // Do not add new nodes to DAG combiner worklist.
6870   DCI.CombineTo(N, Res, false);
6871   return SDValue();
6872 }
6873
6874 static bool isCMOVWithZeroOrAllOnesLHS(SDValue N, bool AllOnes) {
6875   if (N.getOpcode() != ARMISD::CMOV || !N.getNode()->hasOneUse())
6876     return false;
6877
6878   SDValue FalseVal = N.getOperand(0);
6879   ConstantSDNode *C = dyn_cast<ConstantSDNode>(FalseVal);
6880   if (!C)
6881     return false;
6882   if (AllOnes)
6883     return C->isAllOnesValue();
6884   return C->isNullValue();
6885 }
6886
6887 /// formConditionalOp - Combine an operation with a conditional move operand
6888 /// to form a conditional op. e.g. (or x, (cmov 0, y, cond)) => (or.cond x, y)
6889 /// (and x, (cmov -1, y, cond)) => (and.cond, x, y)
6890 static SDValue formConditionalOp(SDNode *N, SelectionDAG &DAG,
6891                                  bool Commutable) {
6892   SDValue N0 = N->getOperand(0);
6893   SDValue N1 = N->getOperand(1);
6894
6895   bool isAND = N->getOpcode() == ISD::AND;
6896   bool isCand = isCMOVWithZeroOrAllOnesLHS(N1, isAND);
6897   if (!isCand && Commutable) {
6898     isCand = isCMOVWithZeroOrAllOnesLHS(N0, isAND);
6899     if (isCand)
6900       std::swap(N0, N1);
6901   }
6902   if (!isCand)
6903     return SDValue();
6904
6905   unsigned Opc = 0;
6906   switch (N->getOpcode()) {
6907   default: llvm_unreachable("Unexpected node");
6908   case ISD::AND: Opc = ARMISD::CAND; break;
6909   case ISD::OR:  Opc = ARMISD::COR; break;
6910   case ISD::XOR: Opc = ARMISD::CXOR; break;
6911   }
6912   return DAG.getNode(Opc, N->getDebugLoc(), N->getValueType(0), N0,
6913                      N1.getOperand(1), N1.getOperand(2), N1.getOperand(3),
6914                      N1.getOperand(4));
6915 }
6916
6917 static SDValue PerformANDCombine(SDNode *N,
6918                                  TargetLowering::DAGCombinerInfo &DCI,
6919                                  const ARMSubtarget *Subtarget) {
6920
6921   // Attempt to use immediate-form VBIC
6922   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6923   DebugLoc dl = N->getDebugLoc();
6924   EVT VT = N->getValueType(0);
6925   SelectionDAG &DAG = DCI.DAG;
6926
6927   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6928     return SDValue();
6929
6930   APInt SplatBits, SplatUndef;
6931   unsigned SplatBitSize;
6932   bool HasAnyUndefs;
6933   if (BVN &&
6934       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6935     if (SplatBitSize <= 64) {
6936       EVT VbicVT;
6937       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
6938                                       SplatUndef.getZExtValue(), SplatBitSize,
6939                                       DAG, VbicVT, VT.is128BitVector(),
6940                                       OtherModImm);
6941       if (Val.getNode()) {
6942         SDValue Input =
6943           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
6944         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
6945         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
6946       }
6947     }
6948   }
6949
6950   if (!Subtarget->isThumb1Only()) {
6951     // (and x, (cmov -1, y, cond)) => (and.cond x, y)
6952     SDValue CAND = formConditionalOp(N, DAG, true);
6953     if (CAND.getNode())
6954       return CAND;
6955   }
6956
6957   return SDValue();
6958 }
6959
6960 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
6961 static SDValue PerformORCombine(SDNode *N,
6962                                 TargetLowering::DAGCombinerInfo &DCI,
6963                                 const ARMSubtarget *Subtarget) {
6964   // Attempt to use immediate-form VORR
6965   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
6966   DebugLoc dl = N->getDebugLoc();
6967   EVT VT = N->getValueType(0);
6968   SelectionDAG &DAG = DCI.DAG;
6969
6970   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6971     return SDValue();
6972
6973   APInt SplatBits, SplatUndef;
6974   unsigned SplatBitSize;
6975   bool HasAnyUndefs;
6976   if (BVN && Subtarget->hasNEON() &&
6977       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6978     if (SplatBitSize <= 64) {
6979       EVT VorrVT;
6980       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6981                                       SplatUndef.getZExtValue(), SplatBitSize,
6982                                       DAG, VorrVT, VT.is128BitVector(),
6983                                       OtherModImm);
6984       if (Val.getNode()) {
6985         SDValue Input =
6986           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
6987         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
6988         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
6989       }
6990     }
6991   }
6992
6993   if (!Subtarget->isThumb1Only()) {
6994     // (or x, (cmov 0, y, cond)) => (or.cond x, y)
6995     SDValue COR = formConditionalOp(N, DAG, true);
6996     if (COR.getNode())
6997       return COR;
6998   }
6999
7000   SDValue N0 = N->getOperand(0);
7001   if (N0.getOpcode() != ISD::AND)
7002     return SDValue();
7003   SDValue N1 = N->getOperand(1);
7004
7005   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7006   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7007       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7008     APInt SplatUndef;
7009     unsigned SplatBitSize;
7010     bool HasAnyUndefs;
7011
7012     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7013     APInt SplatBits0;
7014     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7015                                   HasAnyUndefs) && !HasAnyUndefs) {
7016       BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7017       APInt SplatBits1;
7018       if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7019                                     HasAnyUndefs) && !HasAnyUndefs &&
7020           SplatBits0 == ~SplatBits1) {
7021         // Canonicalize the vector type to make instruction selection simpler.
7022         EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
7023         SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
7024                                      N0->getOperand(1), N0->getOperand(0),
7025                                      N1->getOperand(0));
7026         return DAG.getNode(ISD::BITCAST, dl, VT, Result);
7027       }
7028     }
7029   }
7030
7031   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
7032   // reasonable.
7033
7034   // BFI is only available on V6T2+
7035   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
7036     return SDValue();
7037
7038   DebugLoc DL = N->getDebugLoc();
7039   // 1) or (and A, mask), val => ARMbfi A, val, mask
7040   //      iff (val & mask) == val
7041   //
7042   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7043   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
7044   //          && mask == ~mask2
7045   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
7046   //          && ~mask == mask2
7047   //  (i.e., copy a bitfield value into another bitfield of the same width)
7048
7049   if (VT != MVT::i32)
7050     return SDValue();
7051
7052   SDValue N00 = N0.getOperand(0);
7053
7054   // The value and the mask need to be constants so we can verify this is
7055   // actually a bitfield set. If the mask is 0xffff, we can do better
7056   // via a movt instruction, so don't use BFI in that case.
7057   SDValue MaskOp = N0.getOperand(1);
7058   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
7059   if (!MaskC)
7060     return SDValue();
7061   unsigned Mask = MaskC->getZExtValue();
7062   if (Mask == 0xffff)
7063     return SDValue();
7064   SDValue Res;
7065   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
7066   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
7067   if (N1C) {
7068     unsigned Val = N1C->getZExtValue();
7069     if ((Val & ~Mask) != Val)
7070       return SDValue();
7071
7072     if (ARM::isBitFieldInvertedMask(Mask)) {
7073       Val >>= CountTrailingZeros_32(~Mask);
7074
7075       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
7076                         DAG.getConstant(Val, MVT::i32),
7077                         DAG.getConstant(Mask, MVT::i32));
7078
7079       // Do not add new nodes to DAG combiner worklist.
7080       DCI.CombineTo(N, Res, false);
7081       return SDValue();
7082     }
7083   } else if (N1.getOpcode() == ISD::AND) {
7084     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
7085     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7086     if (!N11C)
7087       return SDValue();
7088     unsigned Mask2 = N11C->getZExtValue();
7089
7090     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
7091     // as is to match.
7092     if (ARM::isBitFieldInvertedMask(Mask) &&
7093         (Mask == ~Mask2)) {
7094       // The pack halfword instruction works better for masks that fit it,
7095       // so use that when it's available.
7096       if (Subtarget->hasT2ExtractPack() &&
7097           (Mask == 0xffff || Mask == 0xffff0000))
7098         return SDValue();
7099       // 2a
7100       unsigned amt = CountTrailingZeros_32(Mask2);
7101       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
7102                         DAG.getConstant(amt, MVT::i32));
7103       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
7104                         DAG.getConstant(Mask, MVT::i32));
7105       // Do not add new nodes to DAG combiner worklist.
7106       DCI.CombineTo(N, Res, false);
7107       return SDValue();
7108     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
7109                (~Mask == Mask2)) {
7110       // The pack halfword instruction works better for masks that fit it,
7111       // so use that when it's available.
7112       if (Subtarget->hasT2ExtractPack() &&
7113           (Mask2 == 0xffff || Mask2 == 0xffff0000))
7114         return SDValue();
7115       // 2b
7116       unsigned lsb = CountTrailingZeros_32(Mask);
7117       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
7118                         DAG.getConstant(lsb, MVT::i32));
7119       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
7120                         DAG.getConstant(Mask2, MVT::i32));
7121       // Do not add new nodes to DAG combiner worklist.
7122       DCI.CombineTo(N, Res, false);
7123       return SDValue();
7124     }
7125   }
7126
7127   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
7128       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
7129       ARM::isBitFieldInvertedMask(~Mask)) {
7130     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
7131     // where lsb(mask) == #shamt and masked bits of B are known zero.
7132     SDValue ShAmt = N00.getOperand(1);
7133     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
7134     unsigned LSB = CountTrailingZeros_32(Mask);
7135     if (ShAmtC != LSB)
7136       return SDValue();
7137
7138     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
7139                       DAG.getConstant(~Mask, MVT::i32));
7140
7141     // Do not add new nodes to DAG combiner worklist.
7142     DCI.CombineTo(N, Res, false);
7143   }
7144
7145   return SDValue();
7146 }
7147
7148 static SDValue PerformXORCombine(SDNode *N,
7149                                  TargetLowering::DAGCombinerInfo &DCI,
7150                                  const ARMSubtarget *Subtarget) {
7151   EVT VT = N->getValueType(0);
7152   SelectionDAG &DAG = DCI.DAG;
7153
7154   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7155     return SDValue();
7156
7157   if (!Subtarget->isThumb1Only()) {
7158     // (xor x, (cmov 0, y, cond)) => (xor.cond x, y)
7159     SDValue CXOR = formConditionalOp(N, DAG, true);
7160     if (CXOR.getNode())
7161       return CXOR;
7162   }
7163
7164   return SDValue();
7165 }
7166
7167 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
7168 /// the bits being cleared by the AND are not demanded by the BFI.
7169 static SDValue PerformBFICombine(SDNode *N,
7170                                  TargetLowering::DAGCombinerInfo &DCI) {
7171   SDValue N1 = N->getOperand(1);
7172   if (N1.getOpcode() == ISD::AND) {
7173     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
7174     if (!N11C)
7175       return SDValue();
7176     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
7177     unsigned LSB = CountTrailingZeros_32(~InvMask);
7178     unsigned Width = (32 - CountLeadingZeros_32(~InvMask)) - LSB;
7179     unsigned Mask = (1 << Width)-1;
7180     unsigned Mask2 = N11C->getZExtValue();
7181     if ((Mask & (~Mask2)) == 0)
7182       return DCI.DAG.getNode(ARMISD::BFI, N->getDebugLoc(), N->getValueType(0),
7183                              N->getOperand(0), N1.getOperand(0),
7184                              N->getOperand(2));
7185   }
7186   return SDValue();
7187 }
7188
7189 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
7190 /// ARMISD::VMOVRRD.
7191 static SDValue PerformVMOVRRDCombine(SDNode *N,
7192                                      TargetLowering::DAGCombinerInfo &DCI) {
7193   // vmovrrd(vmovdrr x, y) -> x,y
7194   SDValue InDouble = N->getOperand(0);
7195   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
7196     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
7197
7198   // vmovrrd(load f64) -> (load i32), (load i32)
7199   SDNode *InNode = InDouble.getNode();
7200   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
7201       InNode->getValueType(0) == MVT::f64 &&
7202       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
7203       !cast<LoadSDNode>(InNode)->isVolatile()) {
7204     // TODO: Should this be done for non-FrameIndex operands?
7205     LoadSDNode *LD = cast<LoadSDNode>(InNode);
7206
7207     SelectionDAG &DAG = DCI.DAG;
7208     DebugLoc DL = LD->getDebugLoc();
7209     SDValue BasePtr = LD->getBasePtr();
7210     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
7211                                  LD->getPointerInfo(), LD->isVolatile(),
7212                                  LD->isNonTemporal(), LD->isInvariant(),
7213                                  LD->getAlignment());
7214
7215     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7216                                     DAG.getConstant(4, MVT::i32));
7217     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
7218                                  LD->getPointerInfo(), LD->isVolatile(),
7219                                  LD->isNonTemporal(), LD->isInvariant(),
7220                                  std::min(4U, LD->getAlignment() / 2));
7221
7222     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
7223     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
7224     DCI.RemoveFromWorklist(LD);
7225     DAG.DeleteNode(LD);
7226     return Result;
7227   }
7228
7229   return SDValue();
7230 }
7231
7232 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
7233 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
7234 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
7235   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
7236   SDValue Op0 = N->getOperand(0);
7237   SDValue Op1 = N->getOperand(1);
7238   if (Op0.getOpcode() == ISD::BITCAST)
7239     Op0 = Op0.getOperand(0);
7240   if (Op1.getOpcode() == ISD::BITCAST)
7241     Op1 = Op1.getOperand(0);
7242   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
7243       Op0.getNode() == Op1.getNode() &&
7244       Op0.getResNo() == 0 && Op1.getResNo() == 1)
7245     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
7246                        N->getValueType(0), Op0.getOperand(0));
7247   return SDValue();
7248 }
7249
7250 /// PerformSTORECombine - Target-specific dag combine xforms for
7251 /// ISD::STORE.
7252 static SDValue PerformSTORECombine(SDNode *N,
7253                                    TargetLowering::DAGCombinerInfo &DCI) {
7254   // Bitcast an i64 store extracted from a vector to f64.
7255   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7256   StoreSDNode *St = cast<StoreSDNode>(N);
7257   SDValue StVal = St->getValue();
7258   if (!ISD::isNormalStore(St) || St->isVolatile())
7259     return SDValue();
7260
7261   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
7262       StVal.getNode()->hasOneUse() && !St->isVolatile()) {
7263     SelectionDAG  &DAG = DCI.DAG;
7264     DebugLoc DL = St->getDebugLoc();
7265     SDValue BasePtr = St->getBasePtr();
7266     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
7267                                   StVal.getNode()->getOperand(0), BasePtr,
7268                                   St->getPointerInfo(), St->isVolatile(),
7269                                   St->isNonTemporal(), St->getAlignment());
7270
7271     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
7272                                     DAG.getConstant(4, MVT::i32));
7273     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
7274                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
7275                         St->isNonTemporal(),
7276                         std::min(4U, St->getAlignment() / 2));
7277   }
7278
7279   if (StVal.getValueType() != MVT::i64 ||
7280       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7281     return SDValue();
7282
7283   SelectionDAG &DAG = DCI.DAG;
7284   DebugLoc dl = StVal.getDebugLoc();
7285   SDValue IntVec = StVal.getOperand(0);
7286   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7287                                  IntVec.getValueType().getVectorNumElements());
7288   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
7289   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
7290                                Vec, StVal.getOperand(1));
7291   dl = N->getDebugLoc();
7292   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
7293   // Make the DAGCombiner fold the bitcasts.
7294   DCI.AddToWorklist(Vec.getNode());
7295   DCI.AddToWorklist(ExtElt.getNode());
7296   DCI.AddToWorklist(V.getNode());
7297   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
7298                       St->getPointerInfo(), St->isVolatile(),
7299                       St->isNonTemporal(), St->getAlignment(),
7300                       St->getTBAAInfo());
7301 }
7302
7303 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
7304 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
7305 /// i64 vector to have f64 elements, since the value can then be loaded
7306 /// directly into a VFP register.
7307 static bool hasNormalLoadOperand(SDNode *N) {
7308   unsigned NumElts = N->getValueType(0).getVectorNumElements();
7309   for (unsigned i = 0; i < NumElts; ++i) {
7310     SDNode *Elt = N->getOperand(i).getNode();
7311     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
7312       return true;
7313   }
7314   return false;
7315 }
7316
7317 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
7318 /// ISD::BUILD_VECTOR.
7319 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
7320                                           TargetLowering::DAGCombinerInfo &DCI){
7321   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
7322   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
7323   // into a pair of GPRs, which is fine when the value is used as a scalar,
7324   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
7325   SelectionDAG &DAG = DCI.DAG;
7326   if (N->getNumOperands() == 2) {
7327     SDValue RV = PerformVMOVDRRCombine(N, DAG);
7328     if (RV.getNode())
7329       return RV;
7330   }
7331
7332   // Load i64 elements as f64 values so that type legalization does not split
7333   // them up into i32 values.
7334   EVT VT = N->getValueType(0);
7335   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
7336     return SDValue();
7337   DebugLoc dl = N->getDebugLoc();
7338   SmallVector<SDValue, 8> Ops;
7339   unsigned NumElts = VT.getVectorNumElements();
7340   for (unsigned i = 0; i < NumElts; ++i) {
7341     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
7342     Ops.push_back(V);
7343     // Make the DAGCombiner fold the bitcast.
7344     DCI.AddToWorklist(V.getNode());
7345   }
7346   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
7347   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
7348   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
7349 }
7350
7351 /// PerformInsertEltCombine - Target-specific dag combine xforms for
7352 /// ISD::INSERT_VECTOR_ELT.
7353 static SDValue PerformInsertEltCombine(SDNode *N,
7354                                        TargetLowering::DAGCombinerInfo &DCI) {
7355   // Bitcast an i64 load inserted into a vector to f64.
7356   // Otherwise, the i64 value will be legalized to a pair of i32 values.
7357   EVT VT = N->getValueType(0);
7358   SDNode *Elt = N->getOperand(1).getNode();
7359   if (VT.getVectorElementType() != MVT::i64 ||
7360       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
7361     return SDValue();
7362
7363   SelectionDAG &DAG = DCI.DAG;
7364   DebugLoc dl = N->getDebugLoc();
7365   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
7366                                  VT.getVectorNumElements());
7367   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
7368   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
7369   // Make the DAGCombiner fold the bitcasts.
7370   DCI.AddToWorklist(Vec.getNode());
7371   DCI.AddToWorklist(V.getNode());
7372   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
7373                                Vec, V, N->getOperand(2));
7374   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
7375 }
7376
7377 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
7378 /// ISD::VECTOR_SHUFFLE.
7379 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
7380   // The LLVM shufflevector instruction does not require the shuffle mask
7381   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
7382   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
7383   // operands do not match the mask length, they are extended by concatenating
7384   // them with undef vectors.  That is probably the right thing for other
7385   // targets, but for NEON it is better to concatenate two double-register
7386   // size vector operands into a single quad-register size vector.  Do that
7387   // transformation here:
7388   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
7389   //   shuffle(concat(v1, v2), undef)
7390   SDValue Op0 = N->getOperand(0);
7391   SDValue Op1 = N->getOperand(1);
7392   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
7393       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
7394       Op0.getNumOperands() != 2 ||
7395       Op1.getNumOperands() != 2)
7396     return SDValue();
7397   SDValue Concat0Op1 = Op0.getOperand(1);
7398   SDValue Concat1Op1 = Op1.getOperand(1);
7399   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
7400       Concat1Op1.getOpcode() != ISD::UNDEF)
7401     return SDValue();
7402   // Skip the transformation if any of the types are illegal.
7403   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7404   EVT VT = N->getValueType(0);
7405   if (!TLI.isTypeLegal(VT) ||
7406       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
7407       !TLI.isTypeLegal(Concat1Op1.getValueType()))
7408     return SDValue();
7409
7410   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
7411                                   Op0.getOperand(0), Op1.getOperand(0));
7412   // Translate the shuffle mask.
7413   SmallVector<int, 16> NewMask;
7414   unsigned NumElts = VT.getVectorNumElements();
7415   unsigned HalfElts = NumElts/2;
7416   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7417   for (unsigned n = 0; n < NumElts; ++n) {
7418     int MaskElt = SVN->getMaskElt(n);
7419     int NewElt = -1;
7420     if (MaskElt < (int)HalfElts)
7421       NewElt = MaskElt;
7422     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
7423       NewElt = HalfElts + MaskElt - NumElts;
7424     NewMask.push_back(NewElt);
7425   }
7426   return DAG.getVectorShuffle(VT, N->getDebugLoc(), NewConcat,
7427                               DAG.getUNDEF(VT), NewMask.data());
7428 }
7429
7430 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
7431 /// NEON load/store intrinsics to merge base address updates.
7432 static SDValue CombineBaseUpdate(SDNode *N,
7433                                  TargetLowering::DAGCombinerInfo &DCI) {
7434   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7435     return SDValue();
7436
7437   SelectionDAG &DAG = DCI.DAG;
7438   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
7439                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
7440   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
7441   SDValue Addr = N->getOperand(AddrOpIdx);
7442
7443   // Search for a use of the address operand that is an increment.
7444   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7445          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7446     SDNode *User = *UI;
7447     if (User->getOpcode() != ISD::ADD ||
7448         UI.getUse().getResNo() != Addr.getResNo())
7449       continue;
7450
7451     // Check that the add is independent of the load/store.  Otherwise, folding
7452     // it would create a cycle.
7453     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7454       continue;
7455
7456     // Find the new opcode for the updating load/store.
7457     bool isLoad = true;
7458     bool isLaneOp = false;
7459     unsigned NewOpc = 0;
7460     unsigned NumVecs = 0;
7461     if (isIntrinsic) {
7462       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7463       switch (IntNo) {
7464       default: llvm_unreachable("unexpected intrinsic for Neon base update");
7465       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
7466         NumVecs = 1; break;
7467       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
7468         NumVecs = 2; break;
7469       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
7470         NumVecs = 3; break;
7471       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
7472         NumVecs = 4; break;
7473       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
7474         NumVecs = 2; isLaneOp = true; break;
7475       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
7476         NumVecs = 3; isLaneOp = true; break;
7477       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
7478         NumVecs = 4; isLaneOp = true; break;
7479       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
7480         NumVecs = 1; isLoad = false; break;
7481       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
7482         NumVecs = 2; isLoad = false; break;
7483       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
7484         NumVecs = 3; isLoad = false; break;
7485       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
7486         NumVecs = 4; isLoad = false; break;
7487       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
7488         NumVecs = 2; isLoad = false; isLaneOp = true; break;
7489       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
7490         NumVecs = 3; isLoad = false; isLaneOp = true; break;
7491       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
7492         NumVecs = 4; isLoad = false; isLaneOp = true; break;
7493       }
7494     } else {
7495       isLaneOp = true;
7496       switch (N->getOpcode()) {
7497       default: llvm_unreachable("unexpected opcode for Neon base update");
7498       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
7499       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
7500       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
7501       }
7502     }
7503
7504     // Find the size of memory referenced by the load/store.
7505     EVT VecTy;
7506     if (isLoad)
7507       VecTy = N->getValueType(0);
7508     else
7509       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
7510     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
7511     if (isLaneOp)
7512       NumBytes /= VecTy.getVectorNumElements();
7513
7514     // If the increment is a constant, it must match the memory ref size.
7515     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7516     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7517       uint64_t IncVal = CInc->getZExtValue();
7518       if (IncVal != NumBytes)
7519         continue;
7520     } else if (NumBytes >= 3 * 16) {
7521       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
7522       // separate instructions that make it harder to use a non-constant update.
7523       continue;
7524     }
7525
7526     // Create the new updating load/store node.
7527     EVT Tys[6];
7528     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
7529     unsigned n;
7530     for (n = 0; n < NumResultVecs; ++n)
7531       Tys[n] = VecTy;
7532     Tys[n++] = MVT::i32;
7533     Tys[n] = MVT::Other;
7534     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
7535     SmallVector<SDValue, 8> Ops;
7536     Ops.push_back(N->getOperand(0)); // incoming chain
7537     Ops.push_back(N->getOperand(AddrOpIdx));
7538     Ops.push_back(Inc);
7539     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
7540       Ops.push_back(N->getOperand(i));
7541     }
7542     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
7543     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, N->getDebugLoc(), SDTys,
7544                                            Ops.data(), Ops.size(),
7545                                            MemInt->getMemoryVT(),
7546                                            MemInt->getMemOperand());
7547
7548     // Update the uses.
7549     std::vector<SDValue> NewResults;
7550     for (unsigned i = 0; i < NumResultVecs; ++i) {
7551       NewResults.push_back(SDValue(UpdN.getNode(), i));
7552     }
7553     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
7554     DCI.CombineTo(N, NewResults);
7555     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
7556
7557     break;
7558   }
7559   return SDValue();
7560 }
7561
7562 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
7563 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
7564 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
7565 /// return true.
7566 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
7567   SelectionDAG &DAG = DCI.DAG;
7568   EVT VT = N->getValueType(0);
7569   // vldN-dup instructions only support 64-bit vectors for N > 1.
7570   if (!VT.is64BitVector())
7571     return false;
7572
7573   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
7574   SDNode *VLD = N->getOperand(0).getNode();
7575   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
7576     return false;
7577   unsigned NumVecs = 0;
7578   unsigned NewOpc = 0;
7579   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
7580   if (IntNo == Intrinsic::arm_neon_vld2lane) {
7581     NumVecs = 2;
7582     NewOpc = ARMISD::VLD2DUP;
7583   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
7584     NumVecs = 3;
7585     NewOpc = ARMISD::VLD3DUP;
7586   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
7587     NumVecs = 4;
7588     NewOpc = ARMISD::VLD4DUP;
7589   } else {
7590     return false;
7591   }
7592
7593   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
7594   // numbers match the load.
7595   unsigned VLDLaneNo =
7596     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
7597   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7598        UI != UE; ++UI) {
7599     // Ignore uses of the chain result.
7600     if (UI.getUse().getResNo() == NumVecs)
7601       continue;
7602     SDNode *User = *UI;
7603     if (User->getOpcode() != ARMISD::VDUPLANE ||
7604         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
7605       return false;
7606   }
7607
7608   // Create the vldN-dup node.
7609   EVT Tys[5];
7610   unsigned n;
7611   for (n = 0; n < NumVecs; ++n)
7612     Tys[n] = VT;
7613   Tys[n] = MVT::Other;
7614   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
7615   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
7616   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
7617   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, VLD->getDebugLoc(), SDTys,
7618                                            Ops, 2, VLDMemInt->getMemoryVT(),
7619                                            VLDMemInt->getMemOperand());
7620
7621   // Update the uses.
7622   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
7623        UI != UE; ++UI) {
7624     unsigned ResNo = UI.getUse().getResNo();
7625     // Ignore uses of the chain result.
7626     if (ResNo == NumVecs)
7627       continue;
7628     SDNode *User = *UI;
7629     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
7630   }
7631
7632   // Now the vldN-lane intrinsic is dead except for its chain result.
7633   // Update uses of the chain.
7634   std::vector<SDValue> VLDDupResults;
7635   for (unsigned n = 0; n < NumVecs; ++n)
7636     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
7637   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
7638   DCI.CombineTo(VLD, VLDDupResults);
7639
7640   return true;
7641 }
7642
7643 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
7644 /// ARMISD::VDUPLANE.
7645 static SDValue PerformVDUPLANECombine(SDNode *N,
7646                                       TargetLowering::DAGCombinerInfo &DCI) {
7647   SDValue Op = N->getOperand(0);
7648
7649   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
7650   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
7651   if (CombineVLDDUP(N, DCI))
7652     return SDValue(N, 0);
7653
7654   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
7655   // redundant.  Ignore bit_converts for now; element sizes are checked below.
7656   while (Op.getOpcode() == ISD::BITCAST)
7657     Op = Op.getOperand(0);
7658   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
7659     return SDValue();
7660
7661   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
7662   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
7663   // The canonical VMOV for a zero vector uses a 32-bit element size.
7664   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7665   unsigned EltBits;
7666   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
7667     EltSize = 8;
7668   EVT VT = N->getValueType(0);
7669   if (EltSize > VT.getVectorElementType().getSizeInBits())
7670     return SDValue();
7671
7672   return DCI.DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
7673 }
7674
7675 // isConstVecPow2 - Return true if each vector element is a power of 2, all
7676 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
7677 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
7678 {
7679   integerPart cN;
7680   integerPart c0 = 0;
7681   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
7682        I != E; I++) {
7683     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
7684     if (!C)
7685       return false;
7686
7687     bool isExact;
7688     APFloat APF = C->getValueAPF();
7689     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
7690         != APFloat::opOK || !isExact)
7691       return false;
7692
7693     c0 = (I == 0) ? cN : c0;
7694     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
7695       return false;
7696   }
7697   C = c0;
7698   return true;
7699 }
7700
7701 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
7702 /// can replace combinations of VMUL and VCVT (floating-point to integer)
7703 /// when the VMUL has a constant operand that is a power of 2.
7704 ///
7705 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7706 ///  vmul.f32        d16, d17, d16
7707 ///  vcvt.s32.f32    d16, d16
7708 /// becomes:
7709 ///  vcvt.s32.f32    d16, d16, #3
7710 static SDValue PerformVCVTCombine(SDNode *N,
7711                                   TargetLowering::DAGCombinerInfo &DCI,
7712                                   const ARMSubtarget *Subtarget) {
7713   SelectionDAG &DAG = DCI.DAG;
7714   SDValue Op = N->getOperand(0);
7715
7716   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
7717       Op.getOpcode() != ISD::FMUL)
7718     return SDValue();
7719
7720   uint64_t C;
7721   SDValue N0 = Op->getOperand(0);
7722   SDValue ConstVec = Op->getOperand(1);
7723   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
7724
7725   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7726       !isConstVecPow2(ConstVec, isSigned, C))
7727     return SDValue();
7728
7729   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
7730     Intrinsic::arm_neon_vcvtfp2fxu;
7731   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7732                      N->getValueType(0),
7733                      DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
7734                      DAG.getConstant(Log2_64(C), MVT::i32));
7735 }
7736
7737 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
7738 /// can replace combinations of VCVT (integer to floating-point) and VDIV
7739 /// when the VDIV has a constant operand that is a power of 2.
7740 ///
7741 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
7742 ///  vcvt.f32.s32    d16, d16
7743 ///  vdiv.f32        d16, d17, d16
7744 /// becomes:
7745 ///  vcvt.f32.s32    d16, d16, #3
7746 static SDValue PerformVDIVCombine(SDNode *N,
7747                                   TargetLowering::DAGCombinerInfo &DCI,
7748                                   const ARMSubtarget *Subtarget) {
7749   SelectionDAG &DAG = DCI.DAG;
7750   SDValue Op = N->getOperand(0);
7751   unsigned OpOpcode = Op.getNode()->getOpcode();
7752
7753   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
7754       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
7755     return SDValue();
7756
7757   uint64_t C;
7758   SDValue ConstVec = N->getOperand(1);
7759   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
7760
7761   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
7762       !isConstVecPow2(ConstVec, isSigned, C))
7763     return SDValue();
7764
7765   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
7766     Intrinsic::arm_neon_vcvtfxu2fp;
7767   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, N->getDebugLoc(),
7768                      Op.getValueType(),
7769                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
7770                      Op.getOperand(0), DAG.getConstant(Log2_64(C), MVT::i32));
7771 }
7772
7773 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
7774 /// operand of a vector shift operation, where all the elements of the
7775 /// build_vector must have the same constant integer value.
7776 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7777   // Ignore bit_converts.
7778   while (Op.getOpcode() == ISD::BITCAST)
7779     Op = Op.getOperand(0);
7780   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7781   APInt SplatBits, SplatUndef;
7782   unsigned SplatBitSize;
7783   bool HasAnyUndefs;
7784   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7785                                       HasAnyUndefs, ElementBits) ||
7786       SplatBitSize > ElementBits)
7787     return false;
7788   Cnt = SplatBits.getSExtValue();
7789   return true;
7790 }
7791
7792 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7793 /// operand of a vector shift left operation.  That value must be in the range:
7794 ///   0 <= Value < ElementBits for a left shift; or
7795 ///   0 <= Value <= ElementBits for a long left shift.
7796 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7797   assert(VT.isVector() && "vector shift count is not a vector type");
7798   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7799   if (! getVShiftImm(Op, ElementBits, Cnt))
7800     return false;
7801   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
7802 }
7803
7804 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7805 /// operand of a vector shift right operation.  For a shift opcode, the value
7806 /// is positive, but for an intrinsic the value count must be negative. The
7807 /// absolute value must be in the range:
7808 ///   1 <= |Value| <= ElementBits for a right shift; or
7809 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
7810 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
7811                          int64_t &Cnt) {
7812   assert(VT.isVector() && "vector shift count is not a vector type");
7813   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
7814   if (! getVShiftImm(Op, ElementBits, Cnt))
7815     return false;
7816   if (isIntrinsic)
7817     Cnt = -Cnt;
7818   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
7819 }
7820
7821 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
7822 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
7823   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7824   switch (IntNo) {
7825   default:
7826     // Don't do anything for most intrinsics.
7827     break;
7828
7829   // Vector shifts: check for immediate versions and lower them.
7830   // Note: This is done during DAG combining instead of DAG legalizing because
7831   // the build_vectors for 64-bit vector element shift counts are generally
7832   // not legal, and it is hard to see their values after they get legalized to
7833   // loads from a constant pool.
7834   case Intrinsic::arm_neon_vshifts:
7835   case Intrinsic::arm_neon_vshiftu:
7836   case Intrinsic::arm_neon_vshiftls:
7837   case Intrinsic::arm_neon_vshiftlu:
7838   case Intrinsic::arm_neon_vshiftn:
7839   case Intrinsic::arm_neon_vrshifts:
7840   case Intrinsic::arm_neon_vrshiftu:
7841   case Intrinsic::arm_neon_vrshiftn:
7842   case Intrinsic::arm_neon_vqshifts:
7843   case Intrinsic::arm_neon_vqshiftu:
7844   case Intrinsic::arm_neon_vqshiftsu:
7845   case Intrinsic::arm_neon_vqshiftns:
7846   case Intrinsic::arm_neon_vqshiftnu:
7847   case Intrinsic::arm_neon_vqshiftnsu:
7848   case Intrinsic::arm_neon_vqrshiftns:
7849   case Intrinsic::arm_neon_vqrshiftnu:
7850   case Intrinsic::arm_neon_vqrshiftnsu: {
7851     EVT VT = N->getOperand(1).getValueType();
7852     int64_t Cnt;
7853     unsigned VShiftOpc = 0;
7854
7855     switch (IntNo) {
7856     case Intrinsic::arm_neon_vshifts:
7857     case Intrinsic::arm_neon_vshiftu:
7858       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
7859         VShiftOpc = ARMISD::VSHL;
7860         break;
7861       }
7862       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
7863         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
7864                      ARMISD::VSHRs : ARMISD::VSHRu);
7865         break;
7866       }
7867       return SDValue();
7868
7869     case Intrinsic::arm_neon_vshiftls:
7870     case Intrinsic::arm_neon_vshiftlu:
7871       if (isVShiftLImm(N->getOperand(2), VT, true, Cnt))
7872         break;
7873       llvm_unreachable("invalid shift count for vshll intrinsic");
7874
7875     case Intrinsic::arm_neon_vrshifts:
7876     case Intrinsic::arm_neon_vrshiftu:
7877       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
7878         break;
7879       return SDValue();
7880
7881     case Intrinsic::arm_neon_vqshifts:
7882     case Intrinsic::arm_neon_vqshiftu:
7883       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7884         break;
7885       return SDValue();
7886
7887     case Intrinsic::arm_neon_vqshiftsu:
7888       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
7889         break;
7890       llvm_unreachable("invalid shift count for vqshlu intrinsic");
7891
7892     case Intrinsic::arm_neon_vshiftn:
7893     case Intrinsic::arm_neon_vrshiftn:
7894     case Intrinsic::arm_neon_vqshiftns:
7895     case Intrinsic::arm_neon_vqshiftnu:
7896     case Intrinsic::arm_neon_vqshiftnsu:
7897     case Intrinsic::arm_neon_vqrshiftns:
7898     case Intrinsic::arm_neon_vqrshiftnu:
7899     case Intrinsic::arm_neon_vqrshiftnsu:
7900       // Narrowing shifts require an immediate right shift.
7901       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
7902         break;
7903       llvm_unreachable("invalid shift count for narrowing vector shift "
7904                        "intrinsic");
7905
7906     default:
7907       llvm_unreachable("unhandled vector shift");
7908     }
7909
7910     switch (IntNo) {
7911     case Intrinsic::arm_neon_vshifts:
7912     case Intrinsic::arm_neon_vshiftu:
7913       // Opcode already set above.
7914       break;
7915     case Intrinsic::arm_neon_vshiftls:
7916     case Intrinsic::arm_neon_vshiftlu:
7917       if (Cnt == VT.getVectorElementType().getSizeInBits())
7918         VShiftOpc = ARMISD::VSHLLi;
7919       else
7920         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshiftls ?
7921                      ARMISD::VSHLLs : ARMISD::VSHLLu);
7922       break;
7923     case Intrinsic::arm_neon_vshiftn:
7924       VShiftOpc = ARMISD::VSHRN; break;
7925     case Intrinsic::arm_neon_vrshifts:
7926       VShiftOpc = ARMISD::VRSHRs; break;
7927     case Intrinsic::arm_neon_vrshiftu:
7928       VShiftOpc = ARMISD::VRSHRu; break;
7929     case Intrinsic::arm_neon_vrshiftn:
7930       VShiftOpc = ARMISD::VRSHRN; break;
7931     case Intrinsic::arm_neon_vqshifts:
7932       VShiftOpc = ARMISD::VQSHLs; break;
7933     case Intrinsic::arm_neon_vqshiftu:
7934       VShiftOpc = ARMISD::VQSHLu; break;
7935     case Intrinsic::arm_neon_vqshiftsu:
7936       VShiftOpc = ARMISD::VQSHLsu; break;
7937     case Intrinsic::arm_neon_vqshiftns:
7938       VShiftOpc = ARMISD::VQSHRNs; break;
7939     case Intrinsic::arm_neon_vqshiftnu:
7940       VShiftOpc = ARMISD::VQSHRNu; break;
7941     case Intrinsic::arm_neon_vqshiftnsu:
7942       VShiftOpc = ARMISD::VQSHRNsu; break;
7943     case Intrinsic::arm_neon_vqrshiftns:
7944       VShiftOpc = ARMISD::VQRSHRNs; break;
7945     case Intrinsic::arm_neon_vqrshiftnu:
7946       VShiftOpc = ARMISD::VQRSHRNu; break;
7947     case Intrinsic::arm_neon_vqrshiftnsu:
7948       VShiftOpc = ARMISD::VQRSHRNsu; break;
7949     }
7950
7951     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7952                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
7953   }
7954
7955   case Intrinsic::arm_neon_vshiftins: {
7956     EVT VT = N->getOperand(1).getValueType();
7957     int64_t Cnt;
7958     unsigned VShiftOpc = 0;
7959
7960     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
7961       VShiftOpc = ARMISD::VSLI;
7962     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
7963       VShiftOpc = ARMISD::VSRI;
7964     else {
7965       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
7966     }
7967
7968     return DAG.getNode(VShiftOpc, N->getDebugLoc(), N->getValueType(0),
7969                        N->getOperand(1), N->getOperand(2),
7970                        DAG.getConstant(Cnt, MVT::i32));
7971   }
7972
7973   case Intrinsic::arm_neon_vqrshifts:
7974   case Intrinsic::arm_neon_vqrshiftu:
7975     // No immediate versions of these to check for.
7976     break;
7977   }
7978
7979   return SDValue();
7980 }
7981
7982 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
7983 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
7984 /// combining instead of DAG legalizing because the build_vectors for 64-bit
7985 /// vector element shift counts are generally not legal, and it is hard to see
7986 /// their values after they get legalized to loads from a constant pool.
7987 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
7988                                    const ARMSubtarget *ST) {
7989   EVT VT = N->getValueType(0);
7990   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
7991     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
7992     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
7993     SDValue N1 = N->getOperand(1);
7994     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7995       SDValue N0 = N->getOperand(0);
7996       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
7997           DAG.MaskedValueIsZero(N0.getOperand(0),
7998                                 APInt::getHighBitsSet(32, 16)))
7999         return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, N0, N1);
8000     }
8001   }
8002
8003   // Nothing to be done for scalar shifts.
8004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8005   if (!VT.isVector() || !TLI.isTypeLegal(VT))
8006     return SDValue();
8007
8008   assert(ST->hasNEON() && "unexpected vector shift");
8009   int64_t Cnt;
8010
8011   switch (N->getOpcode()) {
8012   default: llvm_unreachable("unexpected shift opcode");
8013
8014   case ISD::SHL:
8015     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
8016       return DAG.getNode(ARMISD::VSHL, N->getDebugLoc(), VT, N->getOperand(0),
8017                          DAG.getConstant(Cnt, MVT::i32));
8018     break;
8019
8020   case ISD::SRA:
8021   case ISD::SRL:
8022     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
8023       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
8024                             ARMISD::VSHRs : ARMISD::VSHRu);
8025       return DAG.getNode(VShiftOpc, N->getDebugLoc(), VT, N->getOperand(0),
8026                          DAG.getConstant(Cnt, MVT::i32));
8027     }
8028   }
8029   return SDValue();
8030 }
8031
8032 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
8033 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
8034 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
8035                                     const ARMSubtarget *ST) {
8036   SDValue N0 = N->getOperand(0);
8037
8038   // Check for sign- and zero-extensions of vector extract operations of 8-
8039   // and 16-bit vector elements.  NEON supports these directly.  They are
8040   // handled during DAG combining because type legalization will promote them
8041   // to 32-bit types and it is messy to recognize the operations after that.
8042   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8043     SDValue Vec = N0.getOperand(0);
8044     SDValue Lane = N0.getOperand(1);
8045     EVT VT = N->getValueType(0);
8046     EVT EltVT = N0.getValueType();
8047     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8048
8049     if (VT == MVT::i32 &&
8050         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
8051         TLI.isTypeLegal(Vec.getValueType()) &&
8052         isa<ConstantSDNode>(Lane)) {
8053
8054       unsigned Opc = 0;
8055       switch (N->getOpcode()) {
8056       default: llvm_unreachable("unexpected opcode");
8057       case ISD::SIGN_EXTEND:
8058         Opc = ARMISD::VGETLANEs;
8059         break;
8060       case ISD::ZERO_EXTEND:
8061       case ISD::ANY_EXTEND:
8062         Opc = ARMISD::VGETLANEu;
8063         break;
8064       }
8065       return DAG.getNode(Opc, N->getDebugLoc(), VT, Vec, Lane);
8066     }
8067   }
8068
8069   return SDValue();
8070 }
8071
8072 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
8073 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
8074 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
8075                                        const ARMSubtarget *ST) {
8076   // If the target supports NEON, try to use vmax/vmin instructions for f32
8077   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
8078   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
8079   // a NaN; only do the transformation when it matches that behavior.
8080
8081   // For now only do this when using NEON for FP operations; if using VFP, it
8082   // is not obvious that the benefit outweighs the cost of switching to the
8083   // NEON pipeline.
8084   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
8085       N->getValueType(0) != MVT::f32)
8086     return SDValue();
8087
8088   SDValue CondLHS = N->getOperand(0);
8089   SDValue CondRHS = N->getOperand(1);
8090   SDValue LHS = N->getOperand(2);
8091   SDValue RHS = N->getOperand(3);
8092   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
8093
8094   unsigned Opcode = 0;
8095   bool IsReversed;
8096   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
8097     IsReversed = false; // x CC y ? x : y
8098   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
8099     IsReversed = true ; // x CC y ? y : x
8100   } else {
8101     return SDValue();
8102   }
8103
8104   bool IsUnordered;
8105   switch (CC) {
8106   default: break;
8107   case ISD::SETOLT:
8108   case ISD::SETOLE:
8109   case ISD::SETLT:
8110   case ISD::SETLE:
8111   case ISD::SETULT:
8112   case ISD::SETULE:
8113     // If LHS is NaN, an ordered comparison will be false and the result will
8114     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
8115     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8116     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
8117     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8118       break;
8119     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
8120     // will return -0, so vmin can only be used for unsafe math or if one of
8121     // the operands is known to be nonzero.
8122     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
8123         !DAG.getTarget().Options.UnsafeFPMath &&
8124         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8125       break;
8126     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
8127     break;
8128
8129   case ISD::SETOGT:
8130   case ISD::SETOGE:
8131   case ISD::SETGT:
8132   case ISD::SETGE:
8133   case ISD::SETUGT:
8134   case ISD::SETUGE:
8135     // If LHS is NaN, an ordered comparison will be false and the result will
8136     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
8137     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
8138     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
8139     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
8140       break;
8141     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
8142     // will return +0, so vmax can only be used for unsafe math or if one of
8143     // the operands is known to be nonzero.
8144     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
8145         !DAG.getTarget().Options.UnsafeFPMath &&
8146         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8147       break;
8148     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
8149     break;
8150   }
8151
8152   if (!Opcode)
8153     return SDValue();
8154   return DAG.getNode(Opcode, N->getDebugLoc(), N->getValueType(0), LHS, RHS);
8155 }
8156
8157 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
8158 SDValue
8159 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
8160   SDValue Cmp = N->getOperand(4);
8161   if (Cmp.getOpcode() != ARMISD::CMPZ)
8162     // Only looking at EQ and NE cases.
8163     return SDValue();
8164
8165   EVT VT = N->getValueType(0);
8166   DebugLoc dl = N->getDebugLoc();
8167   SDValue LHS = Cmp.getOperand(0);
8168   SDValue RHS = Cmp.getOperand(1);
8169   SDValue FalseVal = N->getOperand(0);
8170   SDValue TrueVal = N->getOperand(1);
8171   SDValue ARMcc = N->getOperand(2);
8172   ARMCC::CondCodes CC =
8173     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
8174
8175   // Simplify
8176   //   mov     r1, r0
8177   //   cmp     r1, x
8178   //   mov     r0, y
8179   //   moveq   r0, x
8180   // to
8181   //   cmp     r0, x
8182   //   movne   r0, y
8183   //
8184   //   mov     r1, r0
8185   //   cmp     r1, x
8186   //   mov     r0, x
8187   //   movne   r0, y
8188   // to
8189   //   cmp     r0, x
8190   //   movne   r0, y
8191   /// FIXME: Turn this into a target neutral optimization?
8192   SDValue Res;
8193   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
8194     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
8195                       N->getOperand(3), Cmp);
8196   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
8197     SDValue ARMcc;
8198     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
8199     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
8200                       N->getOperand(3), NewCmp);
8201   }
8202
8203   if (Res.getNode()) {
8204     APInt KnownZero, KnownOne;
8205     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
8206     DAG.ComputeMaskedBits(SDValue(N,0), Mask, KnownZero, KnownOne);
8207     // Capture demanded bits information that would be otherwise lost.
8208     if (KnownZero == 0xfffffffe)
8209       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8210                         DAG.getValueType(MVT::i1));
8211     else if (KnownZero == 0xffffff00)
8212       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8213                         DAG.getValueType(MVT::i8));
8214     else if (KnownZero == 0xffff0000)
8215       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
8216                         DAG.getValueType(MVT::i16));
8217   }
8218
8219   return Res;
8220 }
8221
8222 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
8223                                              DAGCombinerInfo &DCI) const {
8224   switch (N->getOpcode()) {
8225   default: break;
8226   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
8227   case ISD::SUB:        return PerformSUBCombine(N, DCI);
8228   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
8229   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
8230   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
8231   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
8232   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
8233   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
8234   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
8235   case ISD::STORE:      return PerformSTORECombine(N, DCI);
8236   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
8237   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
8238   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
8239   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
8240   case ISD::FP_TO_SINT:
8241   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
8242   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
8243   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
8244   case ISD::SHL:
8245   case ISD::SRA:
8246   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
8247   case ISD::SIGN_EXTEND:
8248   case ISD::ZERO_EXTEND:
8249   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
8250   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
8251   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
8252   case ARMISD::VLD2DUP:
8253   case ARMISD::VLD3DUP:
8254   case ARMISD::VLD4DUP:
8255     return CombineBaseUpdate(N, DCI);
8256   case ISD::INTRINSIC_VOID:
8257   case ISD::INTRINSIC_W_CHAIN:
8258     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8259     case Intrinsic::arm_neon_vld1:
8260     case Intrinsic::arm_neon_vld2:
8261     case Intrinsic::arm_neon_vld3:
8262     case Intrinsic::arm_neon_vld4:
8263     case Intrinsic::arm_neon_vld2lane:
8264     case Intrinsic::arm_neon_vld3lane:
8265     case Intrinsic::arm_neon_vld4lane:
8266     case Intrinsic::arm_neon_vst1:
8267     case Intrinsic::arm_neon_vst2:
8268     case Intrinsic::arm_neon_vst3:
8269     case Intrinsic::arm_neon_vst4:
8270     case Intrinsic::arm_neon_vst2lane:
8271     case Intrinsic::arm_neon_vst3lane:
8272     case Intrinsic::arm_neon_vst4lane:
8273       return CombineBaseUpdate(N, DCI);
8274     default: break;
8275     }
8276     break;
8277   }
8278   return SDValue();
8279 }
8280
8281 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
8282                                                           EVT VT) const {
8283   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
8284 }
8285
8286 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
8287   if (!Subtarget->allowsUnalignedMem())
8288     return false;
8289
8290   switch (VT.getSimpleVT().SimpleTy) {
8291   default:
8292     return false;
8293   case MVT::i8:
8294   case MVT::i16:
8295   case MVT::i32:
8296     return true;
8297   // FIXME: VLD1 etc with standard alignment is legal.
8298   }
8299 }
8300
8301 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
8302                        unsigned AlignCheck) {
8303   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
8304           (DstAlign == 0 || DstAlign % AlignCheck == 0));
8305 }
8306
8307 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
8308                                            unsigned DstAlign, unsigned SrcAlign,
8309                                            bool IsZeroVal,
8310                                            bool MemcpyStrSrc,
8311                                            MachineFunction &MF) const {
8312   const Function *F = MF.getFunction();
8313
8314   // See if we can use NEON instructions for this...
8315   if (IsZeroVal &&
8316       !F->hasFnAttr(Attribute::NoImplicitFloat) &&
8317       Subtarget->hasNEON()) {
8318     if (memOpAlign(SrcAlign, DstAlign, 16) && Size >= 16) {
8319       return MVT::v4i32;
8320     } else if (memOpAlign(SrcAlign, DstAlign, 8) && Size >= 8) {
8321       return MVT::v2i32;
8322     }
8323   }
8324
8325   // Lowering to i32/i16 if the size permits.
8326   if (Size >= 4) {
8327     return MVT::i32;
8328   } else if (Size >= 2) {
8329     return MVT::i16;
8330   }
8331
8332   // Let the target-independent logic figure it out.
8333   return MVT::Other;
8334 }
8335
8336 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
8337   if (V < 0)
8338     return false;
8339
8340   unsigned Scale = 1;
8341   switch (VT.getSimpleVT().SimpleTy) {
8342   default: return false;
8343   case MVT::i1:
8344   case MVT::i8:
8345     // Scale == 1;
8346     break;
8347   case MVT::i16:
8348     // Scale == 2;
8349     Scale = 2;
8350     break;
8351   case MVT::i32:
8352     // Scale == 4;
8353     Scale = 4;
8354     break;
8355   }
8356
8357   if ((V & (Scale - 1)) != 0)
8358     return false;
8359   V /= Scale;
8360   return V == (V & ((1LL << 5) - 1));
8361 }
8362
8363 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
8364                                       const ARMSubtarget *Subtarget) {
8365   bool isNeg = false;
8366   if (V < 0) {
8367     isNeg = true;
8368     V = - V;
8369   }
8370
8371   switch (VT.getSimpleVT().SimpleTy) {
8372   default: return false;
8373   case MVT::i1:
8374   case MVT::i8:
8375   case MVT::i16:
8376   case MVT::i32:
8377     // + imm12 or - imm8
8378     if (isNeg)
8379       return V == (V & ((1LL << 8) - 1));
8380     return V == (V & ((1LL << 12) - 1));
8381   case MVT::f32:
8382   case MVT::f64:
8383     // Same as ARM mode. FIXME: NEON?
8384     if (!Subtarget->hasVFP2())
8385       return false;
8386     if ((V & 3) != 0)
8387       return false;
8388     V >>= 2;
8389     return V == (V & ((1LL << 8) - 1));
8390   }
8391 }
8392
8393 /// isLegalAddressImmediate - Return true if the integer value can be used
8394 /// as the offset of the target addressing mode for load / store of the
8395 /// given type.
8396 static bool isLegalAddressImmediate(int64_t V, EVT VT,
8397                                     const ARMSubtarget *Subtarget) {
8398   if (V == 0)
8399     return true;
8400
8401   if (!VT.isSimple())
8402     return false;
8403
8404   if (Subtarget->isThumb1Only())
8405     return isLegalT1AddressImmediate(V, VT);
8406   else if (Subtarget->isThumb2())
8407     return isLegalT2AddressImmediate(V, VT, Subtarget);
8408
8409   // ARM mode.
8410   if (V < 0)
8411     V = - V;
8412   switch (VT.getSimpleVT().SimpleTy) {
8413   default: return false;
8414   case MVT::i1:
8415   case MVT::i8:
8416   case MVT::i32:
8417     // +- imm12
8418     return V == (V & ((1LL << 12) - 1));
8419   case MVT::i16:
8420     // +- imm8
8421     return V == (V & ((1LL << 8) - 1));
8422   case MVT::f32:
8423   case MVT::f64:
8424     if (!Subtarget->hasVFP2()) // FIXME: NEON?
8425       return false;
8426     if ((V & 3) != 0)
8427       return false;
8428     V >>= 2;
8429     return V == (V & ((1LL << 8) - 1));
8430   }
8431 }
8432
8433 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
8434                                                       EVT VT) const {
8435   int Scale = AM.Scale;
8436   if (Scale < 0)
8437     return false;
8438
8439   switch (VT.getSimpleVT().SimpleTy) {
8440   default: return false;
8441   case MVT::i1:
8442   case MVT::i8:
8443   case MVT::i16:
8444   case MVT::i32:
8445     if (Scale == 1)
8446       return true;
8447     // r + r << imm
8448     Scale = Scale & ~1;
8449     return Scale == 2 || Scale == 4 || Scale == 8;
8450   case MVT::i64:
8451     // r + r
8452     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8453       return true;
8454     return false;
8455   case MVT::isVoid:
8456     // Note, we allow "void" uses (basically, uses that aren't loads or
8457     // stores), because arm allows folding a scale into many arithmetic
8458     // operations.  This should be made more precise and revisited later.
8459
8460     // Allow r << imm, but the imm has to be a multiple of two.
8461     if (Scale & 1) return false;
8462     return isPowerOf2_32(Scale);
8463   }
8464 }
8465
8466 /// isLegalAddressingMode - Return true if the addressing mode represented
8467 /// by AM is legal for this target, for a load/store of the specified type.
8468 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8469                                               Type *Ty) const {
8470   EVT VT = getValueType(Ty, true);
8471   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
8472     return false;
8473
8474   // Can never fold addr of global into load/store.
8475   if (AM.BaseGV)
8476     return false;
8477
8478   switch (AM.Scale) {
8479   case 0:  // no scale reg, must be "r+i" or "r", or "i".
8480     break;
8481   case 1:
8482     if (Subtarget->isThumb1Only())
8483       return false;
8484     // FALL THROUGH.
8485   default:
8486     // ARM doesn't support any R+R*scale+imm addr modes.
8487     if (AM.BaseOffs)
8488       return false;
8489
8490     if (!VT.isSimple())
8491       return false;
8492
8493     if (Subtarget->isThumb2())
8494       return isLegalT2ScaledAddressingMode(AM, VT);
8495
8496     int Scale = AM.Scale;
8497     switch (VT.getSimpleVT().SimpleTy) {
8498     default: return false;
8499     case MVT::i1:
8500     case MVT::i8:
8501     case MVT::i32:
8502       if (Scale < 0) Scale = -Scale;
8503       if (Scale == 1)
8504         return true;
8505       // r + r << imm
8506       return isPowerOf2_32(Scale & ~1);
8507     case MVT::i16:
8508     case MVT::i64:
8509       // r + r
8510       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
8511         return true;
8512       return false;
8513
8514     case MVT::isVoid:
8515       // Note, we allow "void" uses (basically, uses that aren't loads or
8516       // stores), because arm allows folding a scale into many arithmetic
8517       // operations.  This should be made more precise and revisited later.
8518
8519       // Allow r << imm, but the imm has to be a multiple of two.
8520       if (Scale & 1) return false;
8521       return isPowerOf2_32(Scale);
8522     }
8523   }
8524   return true;
8525 }
8526
8527 /// isLegalICmpImmediate - Return true if the specified immediate is legal
8528 /// icmp immediate, that is the target has icmp instructions which can compare
8529 /// a register against the immediate without having to materialize the
8530 /// immediate into a register.
8531 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
8532   if (!Subtarget->isThumb())
8533     return ARM_AM::getSOImmVal(Imm) != -1;
8534   if (Subtarget->isThumb2())
8535     return ARM_AM::getT2SOImmVal(Imm) != -1;
8536   return Imm >= 0 && Imm <= 255;
8537 }
8538
8539 /// isLegalAddImmediate - Return true if the specified immediate is legal
8540 /// add immediate, that is the target has add instructions which can add
8541 /// a register with the immediate without having to materialize the
8542 /// immediate into a register.
8543 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
8544   return ARM_AM::getSOImmVal(Imm) != -1;
8545 }
8546
8547 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
8548                                       bool isSEXTLoad, SDValue &Base,
8549                                       SDValue &Offset, bool &isInc,
8550                                       SelectionDAG &DAG) {
8551   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8552     return false;
8553
8554   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
8555     // AddressingMode 3
8556     Base = Ptr->getOperand(0);
8557     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8558       int RHSC = (int)RHS->getZExtValue();
8559       if (RHSC < 0 && RHSC > -256) {
8560         assert(Ptr->getOpcode() == ISD::ADD);
8561         isInc = false;
8562         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8563         return true;
8564       }
8565     }
8566     isInc = (Ptr->getOpcode() == ISD::ADD);
8567     Offset = Ptr->getOperand(1);
8568     return true;
8569   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
8570     // AddressingMode 2
8571     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8572       int RHSC = (int)RHS->getZExtValue();
8573       if (RHSC < 0 && RHSC > -0x1000) {
8574         assert(Ptr->getOpcode() == ISD::ADD);
8575         isInc = false;
8576         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8577         Base = Ptr->getOperand(0);
8578         return true;
8579       }
8580     }
8581
8582     if (Ptr->getOpcode() == ISD::ADD) {
8583       isInc = true;
8584       ARM_AM::ShiftOpc ShOpcVal=
8585         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
8586       if (ShOpcVal != ARM_AM::no_shift) {
8587         Base = Ptr->getOperand(1);
8588         Offset = Ptr->getOperand(0);
8589       } else {
8590         Base = Ptr->getOperand(0);
8591         Offset = Ptr->getOperand(1);
8592       }
8593       return true;
8594     }
8595
8596     isInc = (Ptr->getOpcode() == ISD::ADD);
8597     Base = Ptr->getOperand(0);
8598     Offset = Ptr->getOperand(1);
8599     return true;
8600   }
8601
8602   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
8603   return false;
8604 }
8605
8606 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
8607                                      bool isSEXTLoad, SDValue &Base,
8608                                      SDValue &Offset, bool &isInc,
8609                                      SelectionDAG &DAG) {
8610   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
8611     return false;
8612
8613   Base = Ptr->getOperand(0);
8614   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
8615     int RHSC = (int)RHS->getZExtValue();
8616     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
8617       assert(Ptr->getOpcode() == ISD::ADD);
8618       isInc = false;
8619       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
8620       return true;
8621     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
8622       isInc = Ptr->getOpcode() == ISD::ADD;
8623       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
8624       return true;
8625     }
8626   }
8627
8628   return false;
8629 }
8630
8631 /// getPreIndexedAddressParts - returns true by value, base pointer and
8632 /// offset pointer and addressing mode by reference if the node's address
8633 /// can be legally represented as pre-indexed load / store address.
8634 bool
8635 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8636                                              SDValue &Offset,
8637                                              ISD::MemIndexedMode &AM,
8638                                              SelectionDAG &DAG) const {
8639   if (Subtarget->isThumb1Only())
8640     return false;
8641
8642   EVT VT;
8643   SDValue Ptr;
8644   bool isSEXTLoad = false;
8645   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8646     Ptr = LD->getBasePtr();
8647     VT  = LD->getMemoryVT();
8648     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8649   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8650     Ptr = ST->getBasePtr();
8651     VT  = ST->getMemoryVT();
8652   } else
8653     return false;
8654
8655   bool isInc;
8656   bool isLegal = false;
8657   if (Subtarget->isThumb2())
8658     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8659                                        Offset, isInc, DAG);
8660   else
8661     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
8662                                         Offset, isInc, DAG);
8663   if (!isLegal)
8664     return false;
8665
8666   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
8667   return true;
8668 }
8669
8670 /// getPostIndexedAddressParts - returns true by value, base pointer and
8671 /// offset pointer and addressing mode by reference if this node can be
8672 /// combined with a load / store to form a post-indexed load / store.
8673 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
8674                                                    SDValue &Base,
8675                                                    SDValue &Offset,
8676                                                    ISD::MemIndexedMode &AM,
8677                                                    SelectionDAG &DAG) const {
8678   if (Subtarget->isThumb1Only())
8679     return false;
8680
8681   EVT VT;
8682   SDValue Ptr;
8683   bool isSEXTLoad = false;
8684   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8685     VT  = LD->getMemoryVT();
8686     Ptr = LD->getBasePtr();
8687     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
8688   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8689     VT  = ST->getMemoryVT();
8690     Ptr = ST->getBasePtr();
8691   } else
8692     return false;
8693
8694   bool isInc;
8695   bool isLegal = false;
8696   if (Subtarget->isThumb2())
8697     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8698                                        isInc, DAG);
8699   else
8700     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
8701                                         isInc, DAG);
8702   if (!isLegal)
8703     return false;
8704
8705   if (Ptr != Base) {
8706     // Swap base ptr and offset to catch more post-index load / store when
8707     // it's legal. In Thumb2 mode, offset must be an immediate.
8708     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
8709         !Subtarget->isThumb2())
8710       std::swap(Base, Offset);
8711
8712     // Post-indexed load / store update the base pointer.
8713     if (Ptr != Base)
8714       return false;
8715   }
8716
8717   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
8718   return true;
8719 }
8720
8721 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8722                                                        const APInt &Mask,
8723                                                        APInt &KnownZero,
8724                                                        APInt &KnownOne,
8725                                                        const SelectionDAG &DAG,
8726                                                        unsigned Depth) const {
8727   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);
8728   switch (Op.getOpcode()) {
8729   default: break;
8730   case ARMISD::CMOV: {
8731     // Bits are known zero/one if known on the LHS and RHS.
8732     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
8733     if (KnownZero == 0 && KnownOne == 0) return;
8734
8735     APInt KnownZeroRHS, KnownOneRHS;
8736     DAG.ComputeMaskedBits(Op.getOperand(1), Mask,
8737                           KnownZeroRHS, KnownOneRHS, Depth+1);
8738     KnownZero &= KnownZeroRHS;
8739     KnownOne  &= KnownOneRHS;
8740     return;
8741   }
8742   }
8743 }
8744
8745 //===----------------------------------------------------------------------===//
8746 //                           ARM Inline Assembly Support
8747 //===----------------------------------------------------------------------===//
8748
8749 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
8750   // Looking for "rev" which is V6+.
8751   if (!Subtarget->hasV6Ops())
8752     return false;
8753
8754   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
8755   std::string AsmStr = IA->getAsmString();
8756   SmallVector<StringRef, 4> AsmPieces;
8757   SplitString(AsmStr, AsmPieces, ";\n");
8758
8759   switch (AsmPieces.size()) {
8760   default: return false;
8761   case 1:
8762     AsmStr = AsmPieces[0];
8763     AsmPieces.clear();
8764     SplitString(AsmStr, AsmPieces, " \t,");
8765
8766     // rev $0, $1
8767     if (AsmPieces.size() == 3 &&
8768         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
8769         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
8770       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
8771       if (Ty && Ty->getBitWidth() == 32)
8772         return IntrinsicLowering::LowerToByteSwap(CI);
8773     }
8774     break;
8775   }
8776
8777   return false;
8778 }
8779
8780 /// getConstraintType - Given a constraint letter, return the type of
8781 /// constraint it is for this target.
8782 ARMTargetLowering::ConstraintType
8783 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
8784   if (Constraint.size() == 1) {
8785     switch (Constraint[0]) {
8786     default:  break;
8787     case 'l': return C_RegisterClass;
8788     case 'w': return C_RegisterClass;
8789     case 'h': return C_RegisterClass;
8790     case 'x': return C_RegisterClass;
8791     case 't': return C_RegisterClass;
8792     case 'j': return C_Other; // Constant for movw.
8793       // An address with a single base register. Due to the way we
8794       // currently handle addresses it is the same as an 'r' memory constraint.
8795     case 'Q': return C_Memory;
8796     }
8797   } else if (Constraint.size() == 2) {
8798     switch (Constraint[0]) {
8799     default: break;
8800     // All 'U+' constraints are addresses.
8801     case 'U': return C_Memory;
8802     }
8803   }
8804   return TargetLowering::getConstraintType(Constraint);
8805 }
8806
8807 /// Examine constraint type and operand type and determine a weight value.
8808 /// This object must already have been set up with the operand type
8809 /// and the current alternative constraint selected.
8810 TargetLowering::ConstraintWeight
8811 ARMTargetLowering::getSingleConstraintMatchWeight(
8812     AsmOperandInfo &info, const char *constraint) const {
8813   ConstraintWeight weight = CW_Invalid;
8814   Value *CallOperandVal = info.CallOperandVal;
8815     // If we don't have a value, we can't do a match,
8816     // but allow it at the lowest weight.
8817   if (CallOperandVal == NULL)
8818     return CW_Default;
8819   Type *type = CallOperandVal->getType();
8820   // Look at the constraint type.
8821   switch (*constraint) {
8822   default:
8823     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8824     break;
8825   case 'l':
8826     if (type->isIntegerTy()) {
8827       if (Subtarget->isThumb())
8828         weight = CW_SpecificReg;
8829       else
8830         weight = CW_Register;
8831     }
8832     break;
8833   case 'w':
8834     if (type->isFloatingPointTy())
8835       weight = CW_Register;
8836     break;
8837   }
8838   return weight;
8839 }
8840
8841 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
8842 RCPair
8843 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8844                                                 EVT VT) const {
8845   if (Constraint.size() == 1) {
8846     // GCC ARM Constraint Letters
8847     switch (Constraint[0]) {
8848     case 'l': // Low regs or general regs.
8849       if (Subtarget->isThumb())
8850         return RCPair(0U, ARM::tGPRRegisterClass);
8851       else
8852         return RCPair(0U, ARM::GPRRegisterClass);
8853     case 'h': // High regs or no regs.
8854       if (Subtarget->isThumb())
8855         return RCPair(0U, ARM::hGPRRegisterClass);
8856       break;
8857     case 'r':
8858       return RCPair(0U, ARM::GPRRegisterClass);
8859     case 'w':
8860       if (VT == MVT::f32)
8861         return RCPair(0U, ARM::SPRRegisterClass);
8862       if (VT.getSizeInBits() == 64)
8863         return RCPair(0U, ARM::DPRRegisterClass);
8864       if (VT.getSizeInBits() == 128)
8865         return RCPair(0U, ARM::QPRRegisterClass);
8866       break;
8867     case 'x':
8868       if (VT == MVT::f32)
8869         return RCPair(0U, ARM::SPR_8RegisterClass);
8870       if (VT.getSizeInBits() == 64)
8871         return RCPair(0U, ARM::DPR_8RegisterClass);
8872       if (VT.getSizeInBits() == 128)
8873         return RCPair(0U, ARM::QPR_8RegisterClass);
8874       break;
8875     case 't':
8876       if (VT == MVT::f32)
8877         return RCPair(0U, ARM::SPRRegisterClass);
8878       break;
8879     }
8880   }
8881   if (StringRef("{cc}").equals_lower(Constraint))
8882     return std::make_pair(unsigned(ARM::CPSR), ARM::CCRRegisterClass);
8883
8884   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8885 }
8886
8887 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8888 /// vector.  If it is invalid, don't add anything to Ops.
8889 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8890                                                      std::string &Constraint,
8891                                                      std::vector<SDValue>&Ops,
8892                                                      SelectionDAG &DAG) const {
8893   SDValue Result(0, 0);
8894
8895   // Currently only support length 1 constraints.
8896   if (Constraint.length() != 1) return;
8897
8898   char ConstraintLetter = Constraint[0];
8899   switch (ConstraintLetter) {
8900   default: break;
8901   case 'j':
8902   case 'I': case 'J': case 'K': case 'L':
8903   case 'M': case 'N': case 'O':
8904     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
8905     if (!C)
8906       return;
8907
8908     int64_t CVal64 = C->getSExtValue();
8909     int CVal = (int) CVal64;
8910     // None of these constraints allow values larger than 32 bits.  Check
8911     // that the value fits in an int.
8912     if (CVal != CVal64)
8913       return;
8914
8915     switch (ConstraintLetter) {
8916       case 'j':
8917         // Constant suitable for movw, must be between 0 and
8918         // 65535.
8919         if (Subtarget->hasV6T2Ops())
8920           if (CVal >= 0 && CVal <= 65535)
8921             break;
8922         return;
8923       case 'I':
8924         if (Subtarget->isThumb1Only()) {
8925           // This must be a constant between 0 and 255, for ADD
8926           // immediates.
8927           if (CVal >= 0 && CVal <= 255)
8928             break;
8929         } else if (Subtarget->isThumb2()) {
8930           // A constant that can be used as an immediate value in a
8931           // data-processing instruction.
8932           if (ARM_AM::getT2SOImmVal(CVal) != -1)
8933             break;
8934         } else {
8935           // A constant that can be used as an immediate value in a
8936           // data-processing instruction.
8937           if (ARM_AM::getSOImmVal(CVal) != -1)
8938             break;
8939         }
8940         return;
8941
8942       case 'J':
8943         if (Subtarget->isThumb()) {  // FIXME thumb2
8944           // This must be a constant between -255 and -1, for negated ADD
8945           // immediates. This can be used in GCC with an "n" modifier that
8946           // prints the negated value, for use with SUB instructions. It is
8947           // not useful otherwise but is implemented for compatibility.
8948           if (CVal >= -255 && CVal <= -1)
8949             break;
8950         } else {
8951           // This must be a constant between -4095 and 4095. It is not clear
8952           // what this constraint is intended for. Implemented for
8953           // compatibility with GCC.
8954           if (CVal >= -4095 && CVal <= 4095)
8955             break;
8956         }
8957         return;
8958
8959       case 'K':
8960         if (Subtarget->isThumb1Only()) {
8961           // A 32-bit value where only one byte has a nonzero value. Exclude
8962           // zero to match GCC. This constraint is used by GCC internally for
8963           // constants that can be loaded with a move/shift combination.
8964           // It is not useful otherwise but is implemented for compatibility.
8965           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
8966             break;
8967         } else if (Subtarget->isThumb2()) {
8968           // A constant whose bitwise inverse can be used as an immediate
8969           // value in a data-processing instruction. This can be used in GCC
8970           // with a "B" modifier that prints the inverted value, for use with
8971           // BIC and MVN instructions. It is not useful otherwise but is
8972           // implemented for compatibility.
8973           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
8974             break;
8975         } else {
8976           // A constant whose bitwise inverse can be used as an immediate
8977           // value in a data-processing instruction. This can be used in GCC
8978           // with a "B" modifier that prints the inverted value, for use with
8979           // BIC and MVN instructions. It is not useful otherwise but is
8980           // implemented for compatibility.
8981           if (ARM_AM::getSOImmVal(~CVal) != -1)
8982             break;
8983         }
8984         return;
8985
8986       case 'L':
8987         if (Subtarget->isThumb1Only()) {
8988           // This must be a constant between -7 and 7,
8989           // for 3-operand ADD/SUB immediate instructions.
8990           if (CVal >= -7 && CVal < 7)
8991             break;
8992         } else if (Subtarget->isThumb2()) {
8993           // A constant whose negation can be used as an immediate value in a
8994           // data-processing instruction. This can be used in GCC with an "n"
8995           // modifier that prints the negated value, for use with SUB
8996           // instructions. It is not useful otherwise but is implemented for
8997           // compatibility.
8998           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
8999             break;
9000         } else {
9001           // A constant whose negation can be used as an immediate value in a
9002           // data-processing instruction. This can be used in GCC with an "n"
9003           // modifier that prints the negated value, for use with SUB
9004           // instructions. It is not useful otherwise but is implemented for
9005           // compatibility.
9006           if (ARM_AM::getSOImmVal(-CVal) != -1)
9007             break;
9008         }
9009         return;
9010
9011       case 'M':
9012         if (Subtarget->isThumb()) { // FIXME thumb2
9013           // This must be a multiple of 4 between 0 and 1020, for
9014           // ADD sp + immediate.
9015           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
9016             break;
9017         } else {
9018           // A power of two or a constant between 0 and 32.  This is used in
9019           // GCC for the shift amount on shifted register operands, but it is
9020           // useful in general for any shift amounts.
9021           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
9022             break;
9023         }
9024         return;
9025
9026       case 'N':
9027         if (Subtarget->isThumb()) {  // FIXME thumb2
9028           // This must be a constant between 0 and 31, for shift amounts.
9029           if (CVal >= 0 && CVal <= 31)
9030             break;
9031         }
9032         return;
9033
9034       case 'O':
9035         if (Subtarget->isThumb()) {  // FIXME thumb2
9036           // This must be a multiple of 4 between -508 and 508, for
9037           // ADD/SUB sp = sp + immediate.
9038           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
9039             break;
9040         }
9041         return;
9042     }
9043     Result = DAG.getTargetConstant(CVal, Op.getValueType());
9044     break;
9045   }
9046
9047   if (Result.getNode()) {
9048     Ops.push_back(Result);
9049     return;
9050   }
9051   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9052 }
9053
9054 bool
9055 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9056   // The ARM target isn't yet aware of offsets.
9057   return false;
9058 }
9059
9060 bool ARM::isBitFieldInvertedMask(unsigned v) {
9061   if (v == 0xffffffff)
9062     return 0;
9063   // there can be 1's on either or both "outsides", all the "inside"
9064   // bits must be 0's
9065   unsigned int lsb = 0, msb = 31;
9066   while (v & (1 << msb)) --msb;
9067   while (v & (1 << lsb)) ++lsb;
9068   for (unsigned int i = lsb; i <= msb; ++i) {
9069     if (v & (1 << i))
9070       return 0;
9071   }
9072   return 1;
9073 }
9074
9075 /// isFPImmLegal - Returns true if the target can instruction select the
9076 /// specified FP immediate natively. If false, the legalizer will
9077 /// materialize the FP immediate as a load from a constant pool.
9078 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
9079   if (!Subtarget->hasVFP3())
9080     return false;
9081   if (VT == MVT::f32)
9082     return ARM_AM::getFP32Imm(Imm) != -1;
9083   if (VT == MVT::f64)
9084     return ARM_AM::getFP64Imm(Imm) != -1;
9085   return false;
9086 }
9087
9088 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
9089 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
9090 /// specified in the intrinsic calls.
9091 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9092                                            const CallInst &I,
9093                                            unsigned Intrinsic) const {
9094   switch (Intrinsic) {
9095   case Intrinsic::arm_neon_vld1:
9096   case Intrinsic::arm_neon_vld2:
9097   case Intrinsic::arm_neon_vld3:
9098   case Intrinsic::arm_neon_vld4:
9099   case Intrinsic::arm_neon_vld2lane:
9100   case Intrinsic::arm_neon_vld3lane:
9101   case Intrinsic::arm_neon_vld4lane: {
9102     Info.opc = ISD::INTRINSIC_W_CHAIN;
9103     // Conservatively set memVT to the entire set of vectors loaded.
9104     uint64_t NumElts = getTargetData()->getTypeAllocSize(I.getType()) / 8;
9105     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9106     Info.ptrVal = I.getArgOperand(0);
9107     Info.offset = 0;
9108     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9109     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9110     Info.vol = false; // volatile loads with NEON intrinsics not supported
9111     Info.readMem = true;
9112     Info.writeMem = false;
9113     return true;
9114   }
9115   case Intrinsic::arm_neon_vst1:
9116   case Intrinsic::arm_neon_vst2:
9117   case Intrinsic::arm_neon_vst3:
9118   case Intrinsic::arm_neon_vst4:
9119   case Intrinsic::arm_neon_vst2lane:
9120   case Intrinsic::arm_neon_vst3lane:
9121   case Intrinsic::arm_neon_vst4lane: {
9122     Info.opc = ISD::INTRINSIC_VOID;
9123     // Conservatively set memVT to the entire set of vectors stored.
9124     unsigned NumElts = 0;
9125     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
9126       Type *ArgTy = I.getArgOperand(ArgI)->getType();
9127       if (!ArgTy->isVectorTy())
9128         break;
9129       NumElts += getTargetData()->getTypeAllocSize(ArgTy) / 8;
9130     }
9131     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
9132     Info.ptrVal = I.getArgOperand(0);
9133     Info.offset = 0;
9134     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
9135     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
9136     Info.vol = false; // volatile stores with NEON intrinsics not supported
9137     Info.readMem = false;
9138     Info.writeMem = true;
9139     return true;
9140   }
9141   case Intrinsic::arm_strexd: {
9142     Info.opc = ISD::INTRINSIC_W_CHAIN;
9143     Info.memVT = MVT::i64;
9144     Info.ptrVal = I.getArgOperand(2);
9145     Info.offset = 0;
9146     Info.align = 8;
9147     Info.vol = true;
9148     Info.readMem = false;
9149     Info.writeMem = true;
9150     return true;
9151   }
9152   case Intrinsic::arm_ldrexd: {
9153     Info.opc = ISD::INTRINSIC_W_CHAIN;
9154     Info.memVT = MVT::i64;
9155     Info.ptrVal = I.getArgOperand(0);
9156     Info.offset = 0;
9157     Info.align = 8;
9158     Info.vol = true;
9159     Info.readMem = true;
9160     Info.writeMem = false;
9161     return true;
9162   }
9163   default:
9164     break;
9165   }
9166
9167   return false;
9168 }