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