ARM: update subtarget information for Windows on ARM
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-isel"
16 #include "ARMISelLowering.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "ARMTargetObjectFile.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <utility>
50 using namespace llvm;
51
52 STATISTIC(NumTailCalls, "Number of tail calls");
53 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
54 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
55
56 cl::opt<bool>
57 EnableARMLongCalls("arm-long-calls", cl::Hidden,
58   cl::desc("Generate calls via indirect call instructions"),
59   cl::init(false));
60
61 static cl::opt<bool>
62 ARMInterworking("arm-interworking", cl::Hidden,
63   cl::desc("Enable / disable ARM interworking (for debugging only)"),
64   cl::init(true));
65
66 namespace {
67   class ARMCCState : public CCState {
68   public:
69     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
70                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
71                LLVMContext &C, ParmContext PC)
72         : CCState(CC, isVarArg, MF, TM, locs, C) {
73       assert(((PC == Call) || (PC == Prologue)) &&
74              "ARMCCState users must specify whether their context is call"
75              "or prologue generation.");
76       CallOrPrologue = PC;
77     }
78   };
79 }
80
81 // The APCS parameter registers.
82 static const uint16_t GPRArgRegs[] = {
83   ARM::R0, ARM::R1, ARM::R2, ARM::R3
84 };
85
86 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
87                                        MVT PromotedBitwiseVT) {
88   if (VT != PromotedLdStVT) {
89     setOperationAction(ISD::LOAD, VT, Promote);
90     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
91
92     setOperationAction(ISD::STORE, VT, Promote);
93     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
94   }
95
96   MVT ElemTy = VT.getVectorElementType();
97   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
98     setOperationAction(ISD::SETCC, VT, Custom);
99   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
100   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
101   if (ElemTy == MVT::i32) {
102     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
103     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
104     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
105     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
106   } else {
107     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
108     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
109     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
110     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
111   }
112   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
113   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
114   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
115   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
116   setOperationAction(ISD::SELECT,            VT, Expand);
117   setOperationAction(ISD::SELECT_CC,         VT, Expand);
118   setOperationAction(ISD::VSELECT,           VT, Expand);
119   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
120   if (VT.isInteger()) {
121     setOperationAction(ISD::SHL, VT, Custom);
122     setOperationAction(ISD::SRA, VT, Custom);
123     setOperationAction(ISD::SRL, VT, Custom);
124   }
125
126   // Promote all bit-wise operations.
127   if (VT.isInteger() && VT != PromotedBitwiseVT) {
128     setOperationAction(ISD::AND, VT, Promote);
129     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
130     setOperationAction(ISD::OR,  VT, Promote);
131     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
132     setOperationAction(ISD::XOR, VT, Promote);
133     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
134   }
135
136   // Neon does not support vector divide/remainder operations.
137   setOperationAction(ISD::SDIV, VT, Expand);
138   setOperationAction(ISD::UDIV, VT, Expand);
139   setOperationAction(ISD::FDIV, VT, Expand);
140   setOperationAction(ISD::SREM, VT, Expand);
141   setOperationAction(ISD::UREM, VT, Expand);
142   setOperationAction(ISD::FREM, VT, Expand);
143 }
144
145 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
146   addRegisterClass(VT, &ARM::DPRRegClass);
147   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
148 }
149
150 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
151   addRegisterClass(VT, &ARM::DPairRegClass);
152   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
153 }
154
155 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
156   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
157     return new TargetLoweringObjectFileMachO();
158
159   return new ARMElfTargetObjectFile();
160 }
161
162 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
163     : TargetLowering(TM, createTLOF(TM)) {
164   Subtarget = &TM.getSubtarget<ARMSubtarget>();
165   RegInfo = TM.getRegisterInfo();
166   Itins = TM.getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps()) {
174       // Single-precision floating-point arithmetic.
175       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
176       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
177       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
178       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
179
180       // Double-precision floating-point arithmetic.
181       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
182       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
183       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
184       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
185
186       // Single-precision comparisons.
187       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
188       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
189       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
190       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
191       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
192       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
193       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
194       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
195
196       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
197       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
198       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
203       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
204
205       // Double-precision comparisons.
206       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
207       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
208       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
209       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
210       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
211       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
212       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
213       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
214
215       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
216       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
217       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
222       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
223
224       // Floating-point to integer conversions.
225       // i64 conversions are done via library routines even when generating VFP
226       // instructions, so use the same ones.
227       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
228       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
229       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
231
232       // Conversions between floating types.
233       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
234       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
235
236       // Integer to floating-point conversions.
237       // i64 conversions are done via library routines even when generating VFP
238       // instructions, so use the same ones.
239       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
240       // e.g., __floatunsidf vs. __floatunssidfvfp.
241       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
242       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
243       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
245     }
246   }
247
248   // These libcalls are not available in 32-bit.
249   setLibcallName(RTLIB::SHL_I128, 0);
250   setLibcallName(RTLIB::SRL_I128, 0);
251   setLibcallName(RTLIB::SRA_I128, 0);
252
253   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
254       !Subtarget->isTargetWindows()) {
255     // Double-precision floating-point arithmetic helper functions
256     // RTABI chapter 4.1.2, Table 2
257     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
258     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
259     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
260     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
261     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
262     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
263     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
264     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
265
266     // Double-precision floating-point comparison helper functions
267     // RTABI chapter 4.1.2, Table 3
268     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
269     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
270     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
271     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
272     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
273     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
274     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
275     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
276     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
277     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
279     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
280     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
281     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
282     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
283     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
284     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
285     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
286     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
287     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
292
293     // Single-precision floating-point arithmetic helper functions
294     // RTABI chapter 4.1.2, Table 4
295     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
296     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
297     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
298     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
299     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
300     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
301     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
302     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
303
304     // Single-precision floating-point comparison helper functions
305     // RTABI chapter 4.1.2, Table 5
306     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
307     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
308     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
309     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
310     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
311     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
312     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
313     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
314     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
315     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
317     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
318     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
319     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
320     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
321     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
322     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
323     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
324     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
325     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
330
331     // Floating-point to integer conversions.
332     // RTABI chapter 4.1.2, Table 6
333     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
334     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
335     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
336     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
337     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
338     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
339     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
340     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
341     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
342     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
343     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
349
350     // Conversions between floating types.
351     // RTABI chapter 4.1.2, Table 7
352     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
353     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
354     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
355     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
356
357     // Integer to floating-point conversions.
358     // RTABI chapter 4.1.2, Table 8
359     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
360     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
361     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
362     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
363     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
364     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
365     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
366     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
367     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
368     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
369     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
370     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
375
376     // Long long helper functions
377     // RTABI chapter 4.2, Table 9
378     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
379     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
380     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
381     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
382     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
383     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
384     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
388
389     // Integer division functions
390     // RTABI chapter 4.3.1
391     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
392     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
393     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
394     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
395     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
396     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
397     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
398     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
399     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
400     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
401     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
402     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
407
408     // Memory operations
409     // RTABI chapter 4.3.4
410     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
411     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
412     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
413     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
414     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
415     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
416   }
417
418   // Use divmod compiler-rt calls for iOS 5.0 and later.
419   if (Subtarget->getTargetTriple().isiOS() &&
420       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
421     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
422     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
423   }
424
425   if (Subtarget->isThumb1Only())
426     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
427   else
428     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
429   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
430       !Subtarget->isThumb1Only()) {
431     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
432     if (!Subtarget->isFPOnlySP())
433       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
434
435     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
436   }
437
438   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
439        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
440     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
442       setTruncStoreAction((MVT::SimpleValueType)VT,
443                           (MVT::SimpleValueType)InnerVT, Expand);
444     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
445     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
446     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
447   }
448
449   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
450   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
451
452   if (Subtarget->hasNEON()) {
453     addDRTypeForNEON(MVT::v2f32);
454     addDRTypeForNEON(MVT::v8i8);
455     addDRTypeForNEON(MVT::v4i16);
456     addDRTypeForNEON(MVT::v2i32);
457     addDRTypeForNEON(MVT::v1i64);
458
459     addQRTypeForNEON(MVT::v4f32);
460     addQRTypeForNEON(MVT::v2f64);
461     addQRTypeForNEON(MVT::v16i8);
462     addQRTypeForNEON(MVT::v8i16);
463     addQRTypeForNEON(MVT::v4i32);
464     addQRTypeForNEON(MVT::v2i64);
465
466     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
467     // neither Neon nor VFP support any arithmetic operations on it.
468     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
469     // supported for v4f32.
470     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
472     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
473     // FIXME: Code duplication: FDIV and FREM are expanded always, see
474     // ARMTargetLowering::addTypeForNEON method for details.
475     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
476     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
477     // FIXME: Create unittest.
478     // In another words, find a way when "copysign" appears in DAG with vector
479     // operands.
480     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
481     // FIXME: Code duplication: SETCC has custom operation action, see
482     // ARMTargetLowering::addTypeForNEON method for details.
483     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
484     // FIXME: Create unittest for FNEG and for FABS.
485     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
486     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
487     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
488     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
489     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
490     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
491     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
492     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
494     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
495     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
496     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
497     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
498     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
499     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
500     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
501     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
502     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
503     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
504
505     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
506     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
507     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
508     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
509     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
510     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
511     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
512     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
513     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
514     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
515     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
516     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
517     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
518     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
519     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
520
521     // Mark v2f32 intrinsics.
522     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
523     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
524     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
525     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
526     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
527     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
528     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
529     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
530     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
531     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
532     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
533     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
534     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
535     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
536     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
537
538     // Neon does not support some operations on v1i64 and v2i64 types.
539     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
540     // Custom handling for some quad-vector types to detect VMULL.
541     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
542     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
543     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
544     // Custom handling for some vector types to avoid expensive expansions
545     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
546     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
547     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
548     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
549     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
550     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
551     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
552     // a destination type that is wider than the source, and nor does
553     // it have a FP_TO_[SU]INT instruction with a narrower destination than
554     // source.
555     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
556     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
557     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
558     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
559
560     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
561     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
562
563     // NEON does not have single instruction CTPOP for vectors with element
564     // types wider than 8-bits.  However, custom lowering can leverage the
565     // v8i8/v16i8 vcnt instruction.
566     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
567     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
568     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
569     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
570
571     // NEON only has FMA instructions as of VFP4.
572     if (!Subtarget->hasVFP4()) {
573       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
575     }
576
577     setTargetDAGCombine(ISD::INTRINSIC_VOID);
578     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580     setTargetDAGCombine(ISD::SHL);
581     setTargetDAGCombine(ISD::SRL);
582     setTargetDAGCombine(ISD::SRA);
583     setTargetDAGCombine(ISD::SIGN_EXTEND);
584     setTargetDAGCombine(ISD::ZERO_EXTEND);
585     setTargetDAGCombine(ISD::ANY_EXTEND);
586     setTargetDAGCombine(ISD::SELECT_CC);
587     setTargetDAGCombine(ISD::BUILD_VECTOR);
588     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
589     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
590     setTargetDAGCombine(ISD::STORE);
591     setTargetDAGCombine(ISD::FP_TO_SINT);
592     setTargetDAGCombine(ISD::FP_TO_UINT);
593     setTargetDAGCombine(ISD::FDIV);
594
595     // It is legal to extload from v4i8 to v4i16 or v4i32.
596     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
597                   MVT::v4i16, MVT::v2i16,
598                   MVT::v2i32};
599     for (unsigned i = 0; i < 6; ++i) {
600       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
601       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
602       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
603     }
604   }
605
606   // ARM and Thumb2 support UMLAL/SMLAL.
607   if (!Subtarget->isThumb1Only())
608     setTargetDAGCombine(ISD::ADDC);
609
610
611   computeRegisterProperties();
612
613   // ARM does not have f32 extending load.
614   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
615
616   // ARM does not have i1 sign extending load.
617   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
618
619   // ARM supports all 4 flavors of integer indexed load / store.
620   if (!Subtarget->isThumb1Only()) {
621     for (unsigned im = (unsigned)ISD::PRE_INC;
622          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
623       setIndexedLoadAction(im,  MVT::i1,  Legal);
624       setIndexedLoadAction(im,  MVT::i8,  Legal);
625       setIndexedLoadAction(im,  MVT::i16, Legal);
626       setIndexedLoadAction(im,  MVT::i32, Legal);
627       setIndexedStoreAction(im, MVT::i1,  Legal);
628       setIndexedStoreAction(im, MVT::i8,  Legal);
629       setIndexedStoreAction(im, MVT::i16, Legal);
630       setIndexedStoreAction(im, MVT::i32, Legal);
631     }
632   }
633
634   // i64 operation support.
635   setOperationAction(ISD::MUL,     MVT::i64, Expand);
636   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
637   if (Subtarget->isThumb1Only()) {
638     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
639     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
640   }
641   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
642       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
643     setOperationAction(ISD::MULHS, MVT::i32, Expand);
644
645   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
646   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
647   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
648   setOperationAction(ISD::SRL,       MVT::i64, Custom);
649   setOperationAction(ISD::SRA,       MVT::i64, Custom);
650
651   if (!Subtarget->isThumb1Only()) {
652     // FIXME: We should do this for Thumb1 as well.
653     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
654     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
655     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
656     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
657   }
658
659   // ARM does not have ROTL.
660   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
661   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
662   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
663   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
664     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
665
666   // These just redirect to CTTZ and CTLZ on ARM.
667   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
668   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
669
670   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
671
672   // Only ARMv6 has BSWAP.
673   if (!Subtarget->hasV6Ops())
674     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
675
676   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
677       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
678     // These are expanded into libcalls if the cpu doesn't have HW divider.
679     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
680     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
681   }
682
683   // FIXME: Also set divmod for SREM on EABI
684   setOperationAction(ISD::SREM,  MVT::i32, Expand);
685   setOperationAction(ISD::UREM,  MVT::i32, Expand);
686   // Register based DivRem for AEABI (RTABI 4.2)
687   if (Subtarget->isTargetAEABI()) {
688     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
689     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
690     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
691     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
692     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
693     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
694     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
695     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
696
697     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
698     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
699     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
700     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
701     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
702     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
703     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
704     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
705
706     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
707     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
708   } else {
709     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
710     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
711   }
712
713   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
714   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
715   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
716   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
717   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
718
719   setOperationAction(ISD::TRAP, MVT::Other, Legal);
720
721   // Use the default implementation.
722   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
723   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
724   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
725   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
726   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
727   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
728
729   if (!Subtarget->isTargetMachO()) {
730     // Non-MachO platforms may return values in these registers via the
731     // personality function.
732     setExceptionPointerRegister(ARM::R0);
733     setExceptionSelectorRegister(ARM::R1);
734   }
735
736   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
737   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
738   // the default expansion.
739   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
740     // ATOMIC_FENCE needs custom lowering; the other 32-bit ones are legal and
741     // handled normally.
742     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
743     // Custom lowering for 64-bit ops
744     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i64, Custom);
745     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i64, Custom);
746     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i64, Custom);
747     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i64, Custom);
748     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i64, Custom);
749     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i64, Custom);
750     setOperationAction(ISD::ATOMIC_LOAD_MIN,  MVT::i64, Custom);
751     setOperationAction(ISD::ATOMIC_LOAD_MAX,  MVT::i64, Custom);
752     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
753     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
754     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
755     // On v8, we have particularly efficient implementations of atomic fences
756     // if they can be combined with nearby atomic loads and stores.
757     if (!Subtarget->hasV8Ops()) {
758       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
759       setInsertFencesForAtomic(true);
760     }
761     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
762   } else {
763     // If there's anything we can use as a barrier, go through custom lowering
764     // for ATOMIC_FENCE.
765     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
766                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
767
768     // Set them all for expansion, which will force libcalls.
769     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
770     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
771     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
772     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
773     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
774     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
775     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
776     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
777     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
778     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
779     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
780     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
781     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
782     // Unordered/Monotonic case.
783     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
784     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
785   }
786
787   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
788
789   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
790   if (!Subtarget->hasV6Ops()) {
791     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
792     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
793   }
794   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
795
796   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
797       !Subtarget->isThumb1Only()) {
798     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
799     // iff target supports vfp2.
800     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
801     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
802   }
803
804   // We want to custom lower some of our intrinsics.
805   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
806   if (Subtarget->isTargetDarwin()) {
807     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
808     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
809     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
810   }
811
812   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
813   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
814   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
815   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
816   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
817   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
818   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
819   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
820   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
821
822   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
823   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
824   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
825   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
826   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
827
828   // We don't support sin/cos/fmod/copysign/pow
829   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
830   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
831   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
832   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
833   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
834   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
835   setOperationAction(ISD::FREM,      MVT::f64, Expand);
836   setOperationAction(ISD::FREM,      MVT::f32, Expand);
837   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
838       !Subtarget->isThumb1Only()) {
839     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
840     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
841   }
842   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
843   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
844
845   if (!Subtarget->hasVFP4()) {
846     setOperationAction(ISD::FMA, MVT::f64, Expand);
847     setOperationAction(ISD::FMA, MVT::f32, Expand);
848   }
849
850   // Various VFP goodness
851   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
852     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
853     if (Subtarget->hasVFP2()) {
854       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
855       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
856       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
857       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
858     }
859     // Special handling for half-precision FP.
860     if (!Subtarget->hasFP16()) {
861       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
862       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
863     }
864   }
865       
866   // Combine sin / cos into one node or libcall if possible.
867   if (Subtarget->hasSinCos()) {
868     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
869     setLibcallName(RTLIB::SINCOS_F64, "sincos");
870     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
871       // For iOS, we don't want to the normal expansion of a libcall to
872       // sincos. We want to issue a libcall to __sincos_stret.
873       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
874       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
875     }
876   }
877
878   // We have target-specific dag combine patterns for the following nodes:
879   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
880   setTargetDAGCombine(ISD::ADD);
881   setTargetDAGCombine(ISD::SUB);
882   setTargetDAGCombine(ISD::MUL);
883   setTargetDAGCombine(ISD::AND);
884   setTargetDAGCombine(ISD::OR);
885   setTargetDAGCombine(ISD::XOR);
886
887   if (Subtarget->hasV6Ops())
888     setTargetDAGCombine(ISD::SRL);
889
890   setStackPointerRegisterToSaveRestore(ARM::SP);
891
892   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
893       !Subtarget->hasVFP2())
894     setSchedulingPreference(Sched::RegPressure);
895   else
896     setSchedulingPreference(Sched::Hybrid);
897
898   //// temporary - rewrite interface to use type
899   MaxStoresPerMemset = 8;
900   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
901   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
902   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
903   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
904   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
905
906   // On ARM arguments smaller than 4 bytes are extended, so all arguments
907   // are at least 4 bytes aligned.
908   setMinStackArgumentAlignment(4);
909
910   // Prefer likely predicted branches to selects on out-of-order cores.
911   PredictableSelectIsExpensive = Subtarget->isLikeA9();
912
913   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
914 }
915
916 static void getExclusiveOperation(unsigned Size, AtomicOrdering Ord,
917                                   bool isThumb2, unsigned &LdrOpc,
918                                   unsigned &StrOpc) {
919   static const unsigned LoadBares[4][2] =  {{ARM::LDREXB, ARM::t2LDREXB},
920                                             {ARM::LDREXH, ARM::t2LDREXH},
921                                             {ARM::LDREX,  ARM::t2LDREX},
922                                             {ARM::LDREXD, ARM::t2LDREXD}};
923   static const unsigned LoadAcqs[4][2] =   {{ARM::LDAEXB, ARM::t2LDAEXB},
924                                             {ARM::LDAEXH, ARM::t2LDAEXH},
925                                             {ARM::LDAEX,  ARM::t2LDAEX},
926                                             {ARM::LDAEXD, ARM::t2LDAEXD}};
927   static const unsigned StoreBares[4][2] = {{ARM::STREXB, ARM::t2STREXB},
928                                             {ARM::STREXH, ARM::t2STREXH},
929                                             {ARM::STREX,  ARM::t2STREX},
930                                             {ARM::STREXD, ARM::t2STREXD}};
931   static const unsigned StoreRels[4][2] =  {{ARM::STLEXB, ARM::t2STLEXB},
932                                             {ARM::STLEXH, ARM::t2STLEXH},
933                                             {ARM::STLEX,  ARM::t2STLEX},
934                                             {ARM::STLEXD, ARM::t2STLEXD}};
935
936   const unsigned (*LoadOps)[2], (*StoreOps)[2];
937   if (Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent)
938     LoadOps = LoadAcqs;
939   else
940     LoadOps = LoadBares;
941
942   if (Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent)
943     StoreOps = StoreRels;
944   else
945     StoreOps = StoreBares;
946
947   assert(isPowerOf2_32(Size) && Size <= 8 &&
948          "unsupported size for atomic binary op!");
949
950   LdrOpc = LoadOps[Log2_32(Size)][isThumb2];
951   StrOpc = StoreOps[Log2_32(Size)][isThumb2];
952 }
953
954 // FIXME: It might make sense to define the representative register class as the
955 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
956 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
957 // SPR's representative would be DPR_VFP2. This should work well if register
958 // pressure tracking were modified such that a register use would increment the
959 // pressure of the register class's representative and all of it's super
960 // classes' representatives transitively. We have not implemented this because
961 // of the difficulty prior to coalescing of modeling operand register classes
962 // due to the common occurrence of cross class copies and subregister insertions
963 // and extractions.
964 std::pair<const TargetRegisterClass*, uint8_t>
965 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
966   const TargetRegisterClass *RRC = 0;
967   uint8_t Cost = 1;
968   switch (VT.SimpleTy) {
969   default:
970     return TargetLowering::findRepresentativeClass(VT);
971   // Use DPR as representative register class for all floating point
972   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
973   // the cost is 1 for both f32 and f64.
974   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
975   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
976     RRC = &ARM::DPRRegClass;
977     // When NEON is used for SP, only half of the register file is available
978     // because operations that define both SP and DP results will be constrained
979     // to the VFP2 class (D0-D15). We currently model this constraint prior to
980     // coalescing by double-counting the SP regs. See the FIXME above.
981     if (Subtarget->useNEONForSinglePrecisionFP())
982       Cost = 2;
983     break;
984   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
985   case MVT::v4f32: case MVT::v2f64:
986     RRC = &ARM::DPRRegClass;
987     Cost = 2;
988     break;
989   case MVT::v4i64:
990     RRC = &ARM::DPRRegClass;
991     Cost = 4;
992     break;
993   case MVT::v8i64:
994     RRC = &ARM::DPRRegClass;
995     Cost = 8;
996     break;
997   }
998   return std::make_pair(RRC, Cost);
999 }
1000
1001 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1002   switch (Opcode) {
1003   default: return 0;
1004   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1005   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1006   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1007   case ARMISD::CALL:          return "ARMISD::CALL";
1008   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1009   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1010   case ARMISD::tCALL:         return "ARMISD::tCALL";
1011   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1012   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1013   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1014   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1015   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1016   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1017   case ARMISD::CMP:           return "ARMISD::CMP";
1018   case ARMISD::CMN:           return "ARMISD::CMN";
1019   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1020   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1021   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1022   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1023   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1024
1025   case ARMISD::CMOV:          return "ARMISD::CMOV";
1026
1027   case ARMISD::RBIT:          return "ARMISD::RBIT";
1028
1029   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1030   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1031   case ARMISD::SITOF:         return "ARMISD::SITOF";
1032   case ARMISD::UITOF:         return "ARMISD::UITOF";
1033
1034   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1035   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1036   case ARMISD::RRX:           return "ARMISD::RRX";
1037
1038   case ARMISD::ADDC:          return "ARMISD::ADDC";
1039   case ARMISD::ADDE:          return "ARMISD::ADDE";
1040   case ARMISD::SUBC:          return "ARMISD::SUBC";
1041   case ARMISD::SUBE:          return "ARMISD::SUBE";
1042
1043   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1044   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1045
1046   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1047   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1048
1049   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1050
1051   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1052
1053   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1054
1055   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1056
1057   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1058
1059   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1060   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1061   case ARMISD::VCGE:          return "ARMISD::VCGE";
1062   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1063   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1064   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1065   case ARMISD::VCGT:          return "ARMISD::VCGT";
1066   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1067   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1068   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1069   case ARMISD::VTST:          return "ARMISD::VTST";
1070
1071   case ARMISD::VSHL:          return "ARMISD::VSHL";
1072   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1073   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1074   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1075   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1076   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1077   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1078   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1079   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1080   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1081   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1082   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1083   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1084   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1085   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1086   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1087   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1088   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1089   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1090   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1091   case ARMISD::VDUP:          return "ARMISD::VDUP";
1092   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1093   case ARMISD::VEXT:          return "ARMISD::VEXT";
1094   case ARMISD::VREV64:        return "ARMISD::VREV64";
1095   case ARMISD::VREV32:        return "ARMISD::VREV32";
1096   case ARMISD::VREV16:        return "ARMISD::VREV16";
1097   case ARMISD::VZIP:          return "ARMISD::VZIP";
1098   case ARMISD::VUZP:          return "ARMISD::VUZP";
1099   case ARMISD::VTRN:          return "ARMISD::VTRN";
1100   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1101   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1102   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1103   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1104   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1105   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1106   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1107   case ARMISD::FMAX:          return "ARMISD::FMAX";
1108   case ARMISD::FMIN:          return "ARMISD::FMIN";
1109   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1110   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1111   case ARMISD::BFI:           return "ARMISD::BFI";
1112   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1113   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1114   case ARMISD::VBSL:          return "ARMISD::VBSL";
1115   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1116   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1117   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1118   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1119   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1120   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1121   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1122   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1123   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1124   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1125   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1126   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1127   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1128   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1129   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1130   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1131   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1132   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1133   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1134   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1135   }
1136 }
1137
1138 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1139   if (!VT.isVector()) return getPointerTy();
1140   return VT.changeVectorElementTypeToInteger();
1141 }
1142
1143 /// getRegClassFor - Return the register class that should be used for the
1144 /// specified value type.
1145 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1146   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1147   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1148   // load / store 4 to 8 consecutive D registers.
1149   if (Subtarget->hasNEON()) {
1150     if (VT == MVT::v4i64)
1151       return &ARM::QQPRRegClass;
1152     if (VT == MVT::v8i64)
1153       return &ARM::QQQQPRRegClass;
1154   }
1155   return TargetLowering::getRegClassFor(VT);
1156 }
1157
1158 // Create a fast isel object.
1159 FastISel *
1160 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1161                                   const TargetLibraryInfo *libInfo) const {
1162   return ARM::createFastISel(funcInfo, libInfo);
1163 }
1164
1165 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1166 /// be used for loads / stores from the global.
1167 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1168   return (Subtarget->isThumb1Only() ? 127 : 4095);
1169 }
1170
1171 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1172   unsigned NumVals = N->getNumValues();
1173   if (!NumVals)
1174     return Sched::RegPressure;
1175
1176   for (unsigned i = 0; i != NumVals; ++i) {
1177     EVT VT = N->getValueType(i);
1178     if (VT == MVT::Glue || VT == MVT::Other)
1179       continue;
1180     if (VT.isFloatingPoint() || VT.isVector())
1181       return Sched::ILP;
1182   }
1183
1184   if (!N->isMachineOpcode())
1185     return Sched::RegPressure;
1186
1187   // Load are scheduled for latency even if there instruction itinerary
1188   // is not available.
1189   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1190   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1191
1192   if (MCID.getNumDefs() == 0)
1193     return Sched::RegPressure;
1194   if (!Itins->isEmpty() &&
1195       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1196     return Sched::ILP;
1197
1198   return Sched::RegPressure;
1199 }
1200
1201 //===----------------------------------------------------------------------===//
1202 // Lowering Code
1203 //===----------------------------------------------------------------------===//
1204
1205 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1206 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1207   switch (CC) {
1208   default: llvm_unreachable("Unknown condition code!");
1209   case ISD::SETNE:  return ARMCC::NE;
1210   case ISD::SETEQ:  return ARMCC::EQ;
1211   case ISD::SETGT:  return ARMCC::GT;
1212   case ISD::SETGE:  return ARMCC::GE;
1213   case ISD::SETLT:  return ARMCC::LT;
1214   case ISD::SETLE:  return ARMCC::LE;
1215   case ISD::SETUGT: return ARMCC::HI;
1216   case ISD::SETUGE: return ARMCC::HS;
1217   case ISD::SETULT: return ARMCC::LO;
1218   case ISD::SETULE: return ARMCC::LS;
1219   }
1220 }
1221
1222 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1223 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1224                         ARMCC::CondCodes &CondCode2) {
1225   CondCode2 = ARMCC::AL;
1226   switch (CC) {
1227   default: llvm_unreachable("Unknown FP condition!");
1228   case ISD::SETEQ:
1229   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1230   case ISD::SETGT:
1231   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1232   case ISD::SETGE:
1233   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1234   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1235   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1236   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1237   case ISD::SETO:   CondCode = ARMCC::VC; break;
1238   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1239   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1240   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1241   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1242   case ISD::SETLT:
1243   case ISD::SETULT: CondCode = ARMCC::LT; break;
1244   case ISD::SETLE:
1245   case ISD::SETULE: CondCode = ARMCC::LE; break;
1246   case ISD::SETNE:
1247   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1248   }
1249 }
1250
1251 //===----------------------------------------------------------------------===//
1252 //                      Calling Convention Implementation
1253 //===----------------------------------------------------------------------===//
1254
1255 #include "ARMGenCallingConv.inc"
1256
1257 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1258 /// given CallingConvention value.
1259 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1260                                                  bool Return,
1261                                                  bool isVarArg) const {
1262   switch (CC) {
1263   default:
1264     llvm_unreachable("Unsupported calling convention");
1265   case CallingConv::Fast:
1266     if (Subtarget->hasVFP2() && !isVarArg) {
1267       if (!Subtarget->isAAPCS_ABI())
1268         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1269       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1270       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1271     }
1272     // Fallthrough
1273   case CallingConv::C: {
1274     // Use target triple & subtarget features to do actual dispatch.
1275     if (!Subtarget->isAAPCS_ABI())
1276       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1277     else if (Subtarget->hasVFP2() &&
1278              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1279              !isVarArg)
1280       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1281     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1282   }
1283   case CallingConv::ARM_AAPCS_VFP:
1284     if (!isVarArg)
1285       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1286     // Fallthrough
1287   case CallingConv::ARM_AAPCS:
1288     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1289   case CallingConv::ARM_APCS:
1290     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1291   case CallingConv::GHC:
1292     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1293   }
1294 }
1295
1296 /// LowerCallResult - Lower the result values of a call into the
1297 /// appropriate copies out of appropriate physical registers.
1298 SDValue
1299 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1300                                    CallingConv::ID CallConv, bool isVarArg,
1301                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1302                                    SDLoc dl, SelectionDAG &DAG,
1303                                    SmallVectorImpl<SDValue> &InVals,
1304                                    bool isThisReturn, SDValue ThisVal) const {
1305
1306   // Assign locations to each value returned by this call.
1307   SmallVector<CCValAssign, 16> RVLocs;
1308   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1309                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1310   CCInfo.AnalyzeCallResult(Ins,
1311                            CCAssignFnForNode(CallConv, /* Return*/ true,
1312                                              isVarArg));
1313
1314   // Copy all of the result registers out of their specified physreg.
1315   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1316     CCValAssign VA = RVLocs[i];
1317
1318     // Pass 'this' value directly from the argument to return value, to avoid
1319     // reg unit interference
1320     if (i == 0 && isThisReturn) {
1321       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1322              "unexpected return calling convention register assignment");
1323       InVals.push_back(ThisVal);
1324       continue;
1325     }
1326
1327     SDValue Val;
1328     if (VA.needsCustom()) {
1329       // Handle f64 or half of a v2f64.
1330       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1331                                       InFlag);
1332       Chain = Lo.getValue(1);
1333       InFlag = Lo.getValue(2);
1334       VA = RVLocs[++i]; // skip ahead to next loc
1335       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1336                                       InFlag);
1337       Chain = Hi.getValue(1);
1338       InFlag = Hi.getValue(2);
1339       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1340
1341       if (VA.getLocVT() == MVT::v2f64) {
1342         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1343         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1344                           DAG.getConstant(0, MVT::i32));
1345
1346         VA = RVLocs[++i]; // skip ahead to next loc
1347         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1348         Chain = Lo.getValue(1);
1349         InFlag = Lo.getValue(2);
1350         VA = RVLocs[++i]; // skip ahead to next loc
1351         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1352         Chain = Hi.getValue(1);
1353         InFlag = Hi.getValue(2);
1354         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1355         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1356                           DAG.getConstant(1, MVT::i32));
1357       }
1358     } else {
1359       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1360                                InFlag);
1361       Chain = Val.getValue(1);
1362       InFlag = Val.getValue(2);
1363     }
1364
1365     switch (VA.getLocInfo()) {
1366     default: llvm_unreachable("Unknown loc info!");
1367     case CCValAssign::Full: break;
1368     case CCValAssign::BCvt:
1369       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1370       break;
1371     }
1372
1373     InVals.push_back(Val);
1374   }
1375
1376   return Chain;
1377 }
1378
1379 /// LowerMemOpCallTo - Store the argument to the stack.
1380 SDValue
1381 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1382                                     SDValue StackPtr, SDValue Arg,
1383                                     SDLoc dl, SelectionDAG &DAG,
1384                                     const CCValAssign &VA,
1385                                     ISD::ArgFlagsTy Flags) const {
1386   unsigned LocMemOffset = VA.getLocMemOffset();
1387   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1388   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1389   return DAG.getStore(Chain, dl, Arg, PtrOff,
1390                       MachinePointerInfo::getStack(LocMemOffset),
1391                       false, false, 0);
1392 }
1393
1394 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1395                                          SDValue Chain, SDValue &Arg,
1396                                          RegsToPassVector &RegsToPass,
1397                                          CCValAssign &VA, CCValAssign &NextVA,
1398                                          SDValue &StackPtr,
1399                                          SmallVectorImpl<SDValue> &MemOpChains,
1400                                          ISD::ArgFlagsTy Flags) const {
1401
1402   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1403                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1404   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd));
1405
1406   if (NextVA.isRegLoc())
1407     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1)));
1408   else {
1409     assert(NextVA.isMemLoc());
1410     if (StackPtr.getNode() == 0)
1411       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1412
1413     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1),
1414                                            dl, DAG, NextVA,
1415                                            Flags));
1416   }
1417 }
1418
1419 /// LowerCall - Lowering a call into a callseq_start <-
1420 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1421 /// nodes.
1422 SDValue
1423 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1424                              SmallVectorImpl<SDValue> &InVals) const {
1425   SelectionDAG &DAG                     = CLI.DAG;
1426   SDLoc &dl                          = CLI.DL;
1427   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1428   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1429   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1430   SDValue Chain                         = CLI.Chain;
1431   SDValue Callee                        = CLI.Callee;
1432   bool &isTailCall                      = CLI.IsTailCall;
1433   CallingConv::ID CallConv              = CLI.CallConv;
1434   bool doesNotRet                       = CLI.DoesNotReturn;
1435   bool isVarArg                         = CLI.IsVarArg;
1436
1437   MachineFunction &MF = DAG.getMachineFunction();
1438   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1439   bool isThisReturn   = false;
1440   bool isSibCall      = false;
1441
1442   // Disable tail calls if they're not supported.
1443   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1444     isTailCall = false;
1445
1446   if (isTailCall) {
1447     // Check if it's really possible to do a tail call.
1448     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1449                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1450                                                    Outs, OutVals, Ins, DAG);
1451     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1452     // detected sibcalls.
1453     if (isTailCall) {
1454       ++NumTailCalls;
1455       isSibCall = true;
1456     }
1457   }
1458
1459   // Analyze operands of the call, assigning locations to each operand.
1460   SmallVector<CCValAssign, 16> ArgLocs;
1461   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1462                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1463   CCInfo.AnalyzeCallOperands(Outs,
1464                              CCAssignFnForNode(CallConv, /* Return*/ false,
1465                                                isVarArg));
1466
1467   // Get a count of how many bytes are to be pushed on the stack.
1468   unsigned NumBytes = CCInfo.getNextStackOffset();
1469
1470   // For tail calls, memory operands are available in our caller's stack.
1471   if (isSibCall)
1472     NumBytes = 0;
1473
1474   // Adjust the stack pointer for the new arguments...
1475   // These operations are automatically eliminated by the prolog/epilog pass
1476   if (!isSibCall)
1477     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1478                                  dl);
1479
1480   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1481
1482   RegsToPassVector RegsToPass;
1483   SmallVector<SDValue, 8> MemOpChains;
1484
1485   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1486   // of tail call optimization, arguments are handled later.
1487   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1488        i != e;
1489        ++i, ++realArgIdx) {
1490     CCValAssign &VA = ArgLocs[i];
1491     SDValue Arg = OutVals[realArgIdx];
1492     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1493     bool isByVal = Flags.isByVal();
1494
1495     // Promote the value if needed.
1496     switch (VA.getLocInfo()) {
1497     default: llvm_unreachable("Unknown loc info!");
1498     case CCValAssign::Full: break;
1499     case CCValAssign::SExt:
1500       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1501       break;
1502     case CCValAssign::ZExt:
1503       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1504       break;
1505     case CCValAssign::AExt:
1506       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1507       break;
1508     case CCValAssign::BCvt:
1509       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1510       break;
1511     }
1512
1513     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1514     if (VA.needsCustom()) {
1515       if (VA.getLocVT() == MVT::v2f64) {
1516         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1517                                   DAG.getConstant(0, MVT::i32));
1518         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1519                                   DAG.getConstant(1, MVT::i32));
1520
1521         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1522                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1523
1524         VA = ArgLocs[++i]; // skip ahead to next loc
1525         if (VA.isRegLoc()) {
1526           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1527                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1528         } else {
1529           assert(VA.isMemLoc());
1530
1531           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1532                                                  dl, DAG, VA, Flags));
1533         }
1534       } else {
1535         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1536                          StackPtr, MemOpChains, Flags);
1537       }
1538     } else if (VA.isRegLoc()) {
1539       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1540         assert(VA.getLocVT() == MVT::i32 &&
1541                "unexpected calling convention register assignment");
1542         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1543                "unexpected use of 'returned'");
1544         isThisReturn = true;
1545       }
1546       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1547     } else if (isByVal) {
1548       assert(VA.isMemLoc());
1549       unsigned offset = 0;
1550
1551       // True if this byval aggregate will be split between registers
1552       // and memory.
1553       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1554       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1555
1556       if (CurByValIdx < ByValArgsCount) {
1557
1558         unsigned RegBegin, RegEnd;
1559         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1560
1561         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1562         unsigned int i, j;
1563         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1564           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1565           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1566           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1567                                      MachinePointerInfo(),
1568                                      false, false, false,
1569                                      DAG.InferPtrAlignment(AddArg));
1570           MemOpChains.push_back(Load.getValue(1));
1571           RegsToPass.push_back(std::make_pair(j, Load));
1572         }
1573
1574         // If parameter size outsides register area, "offset" value
1575         // helps us to calculate stack slot for remained part properly.
1576         offset = RegEnd - RegBegin;
1577
1578         CCInfo.nextInRegsParam();
1579       }
1580
1581       if (Flags.getByValSize() > 4*offset) {
1582         unsigned LocMemOffset = VA.getLocMemOffset();
1583         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1584         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1585                                   StkPtrOff);
1586         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1587         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1588         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1589                                            MVT::i32);
1590         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1591
1592         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1593         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1594         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1595                                           Ops, array_lengthof(Ops)));
1596       }
1597     } else if (!isSibCall) {
1598       assert(VA.isMemLoc());
1599
1600       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1601                                              dl, DAG, VA, Flags));
1602     }
1603   }
1604
1605   if (!MemOpChains.empty())
1606     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1607                         &MemOpChains[0], MemOpChains.size());
1608
1609   // Build a sequence of copy-to-reg nodes chained together with token chain
1610   // and flag operands which copy the outgoing args into the appropriate regs.
1611   SDValue InFlag;
1612   // Tail call byval lowering might overwrite argument registers so in case of
1613   // tail call optimization the copies to registers are lowered later.
1614   if (!isTailCall)
1615     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1616       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1617                                RegsToPass[i].second, InFlag);
1618       InFlag = Chain.getValue(1);
1619     }
1620
1621   // For tail calls lower the arguments to the 'real' stack slot.
1622   if (isTailCall) {
1623     // Force all the incoming stack arguments to be loaded from the stack
1624     // before any new outgoing arguments are stored to the stack, because the
1625     // outgoing stack slots may alias the incoming argument stack slots, and
1626     // the alias isn't otherwise explicit. This is slightly more conservative
1627     // than necessary, because it means that each store effectively depends
1628     // on every argument instead of just those arguments it would clobber.
1629
1630     // Do not flag preceding copytoreg stuff together with the following stuff.
1631     InFlag = SDValue();
1632     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1633       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1634                                RegsToPass[i].second, InFlag);
1635       InFlag = Chain.getValue(1);
1636     }
1637     InFlag = SDValue();
1638   }
1639
1640   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1641   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1642   // node so that legalize doesn't hack it.
1643   bool isDirect = false;
1644   bool isARMFunc = false;
1645   bool isLocalARMFunc = false;
1646   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1647
1648   if (EnableARMLongCalls) {
1649     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1650             && "long-calls with non-static relocation model!");
1651     // Handle a global address or an external symbol. If it's not one of
1652     // those, the target's already in a register, so we don't need to do
1653     // anything extra.
1654     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1655       const GlobalValue *GV = G->getGlobal();
1656       // Create a constant pool entry for the callee address
1657       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1658       ARMConstantPoolValue *CPV =
1659         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1660
1661       // Get the address of the callee into a register
1662       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1663       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1664       Callee = DAG.getLoad(getPointerTy(), dl,
1665                            DAG.getEntryNode(), CPAddr,
1666                            MachinePointerInfo::getConstantPool(),
1667                            false, false, false, 0);
1668     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1669       const char *Sym = S->getSymbol();
1670
1671       // Create a constant pool entry for the callee address
1672       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1673       ARMConstantPoolValue *CPV =
1674         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1675                                       ARMPCLabelIndex, 0);
1676       // Get the address of the callee into a register
1677       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1678       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1679       Callee = DAG.getLoad(getPointerTy(), dl,
1680                            DAG.getEntryNode(), CPAddr,
1681                            MachinePointerInfo::getConstantPool(),
1682                            false, false, false, 0);
1683     }
1684   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1685     const GlobalValue *GV = G->getGlobal();
1686     isDirect = true;
1687     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1688     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1689                    getTargetMachine().getRelocationModel() != Reloc::Static;
1690     isARMFunc = !Subtarget->isThumb() || isStub;
1691     // ARM call to a local ARM function is predicable.
1692     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1693     // tBX takes a register source operand.
1694     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1695       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1696       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1697                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1698     } else {
1699       // On ELF targets for PIC code, direct calls should go through the PLT
1700       unsigned OpFlags = 0;
1701       if (Subtarget->isTargetELF() &&
1702           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1703         OpFlags = ARMII::MO_PLT;
1704       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1705     }
1706   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1707     isDirect = true;
1708     bool isStub = Subtarget->isTargetMachO() &&
1709                   getTargetMachine().getRelocationModel() != Reloc::Static;
1710     isARMFunc = !Subtarget->isThumb() || isStub;
1711     // tBX takes a register source operand.
1712     const char *Sym = S->getSymbol();
1713     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1714       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1715       ARMConstantPoolValue *CPV =
1716         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1717                                       ARMPCLabelIndex, 4);
1718       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1719       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1720       Callee = DAG.getLoad(getPointerTy(), dl,
1721                            DAG.getEntryNode(), CPAddr,
1722                            MachinePointerInfo::getConstantPool(),
1723                            false, false, false, 0);
1724       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1725       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1726                            getPointerTy(), Callee, PICLabel);
1727     } else {
1728       unsigned OpFlags = 0;
1729       // On ELF targets for PIC code, direct calls should go through the PLT
1730       if (Subtarget->isTargetELF() &&
1731                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1732         OpFlags = ARMII::MO_PLT;
1733       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1734     }
1735   }
1736
1737   // FIXME: handle tail calls differently.
1738   unsigned CallOpc;
1739   bool HasMinSizeAttr = Subtarget->isMinSize();
1740   if (Subtarget->isThumb()) {
1741     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1742       CallOpc = ARMISD::CALL_NOLINK;
1743     else
1744       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1745   } else {
1746     if (!isDirect && !Subtarget->hasV5TOps())
1747       CallOpc = ARMISD::CALL_NOLINK;
1748     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1749                // Emit regular call when code size is the priority
1750                !HasMinSizeAttr)
1751       // "mov lr, pc; b _foo" to avoid confusing the RSP
1752       CallOpc = ARMISD::CALL_NOLINK;
1753     else
1754       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1755   }
1756
1757   std::vector<SDValue> Ops;
1758   Ops.push_back(Chain);
1759   Ops.push_back(Callee);
1760
1761   // Add argument registers to the end of the list so that they are known live
1762   // into the call.
1763   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1764     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1765                                   RegsToPass[i].second.getValueType()));
1766
1767   // Add a register mask operand representing the call-preserved registers.
1768   if (!isTailCall) {
1769     const uint32_t *Mask;
1770     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1771     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1772     if (isThisReturn) {
1773       // For 'this' returns, use the R0-preserving mask if applicable
1774       Mask = ARI->getThisReturnPreservedMask(CallConv);
1775       if (!Mask) {
1776         // Set isThisReturn to false if the calling convention is not one that
1777         // allows 'returned' to be modeled in this way, so LowerCallResult does
1778         // not try to pass 'this' straight through
1779         isThisReturn = false;
1780         Mask = ARI->getCallPreservedMask(CallConv);
1781       }
1782     } else
1783       Mask = ARI->getCallPreservedMask(CallConv);
1784
1785     assert(Mask && "Missing call preserved mask for calling convention");
1786     Ops.push_back(DAG.getRegisterMask(Mask));
1787   }
1788
1789   if (InFlag.getNode())
1790     Ops.push_back(InFlag);
1791
1792   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1793   if (isTailCall)
1794     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, &Ops[0], Ops.size());
1795
1796   // Returns a chain and a flag for retval copy to use.
1797   Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
1798   InFlag = Chain.getValue(1);
1799
1800   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1801                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1802   if (!Ins.empty())
1803     InFlag = Chain.getValue(1);
1804
1805   // Handle result values, copying them out of physregs into vregs that we
1806   // return.
1807   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1808                          InVals, isThisReturn,
1809                          isThisReturn ? OutVals[0] : SDValue());
1810 }
1811
1812 /// HandleByVal - Every parameter *after* a byval parameter is passed
1813 /// on the stack.  Remember the next parameter register to allocate,
1814 /// and then confiscate the rest of the parameter registers to insure
1815 /// this.
1816 void
1817 ARMTargetLowering::HandleByVal(
1818     CCState *State, unsigned &size, unsigned Align) const {
1819   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1820   assert((State->getCallOrPrologue() == Prologue ||
1821           State->getCallOrPrologue() == Call) &&
1822          "unhandled ParmContext");
1823
1824   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1825     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1826       unsigned AlignInRegs = Align / 4;
1827       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1828       for (unsigned i = 0; i < Waste; ++i)
1829         reg = State->AllocateReg(GPRArgRegs, 4);
1830     }
1831     if (reg != 0) {
1832       unsigned excess = 4 * (ARM::R4 - reg);
1833
1834       // Special case when NSAA != SP and parameter size greater than size of
1835       // all remained GPR regs. In that case we can't split parameter, we must
1836       // send it to stack. We also must set NCRN to R4, so waste all
1837       // remained registers.
1838       const unsigned NSAAOffset = State->getNextStackOffset();
1839       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1840         while (State->AllocateReg(GPRArgRegs, 4))
1841           ;
1842         return;
1843       }
1844
1845       // First register for byval parameter is the first register that wasn't
1846       // allocated before this method call, so it would be "reg".
1847       // If parameter is small enough to be saved in range [reg, r4), then
1848       // the end (first after last) register would be reg + param-size-in-regs,
1849       // else parameter would be splitted between registers and stack,
1850       // end register would be r4 in this case.
1851       unsigned ByValRegBegin = reg;
1852       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1853       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1854       // Note, first register is allocated in the beginning of function already,
1855       // allocate remained amount of registers we need.
1856       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1857         State->AllocateReg(GPRArgRegs, 4);
1858       // A byval parameter that is split between registers and memory needs its
1859       // size truncated here.
1860       // In the case where the entire structure fits in registers, we set the
1861       // size in memory to zero.
1862       if (size < excess)
1863         size = 0;
1864       else
1865         size -= excess;
1866     }
1867   }
1868 }
1869
1870 /// MatchingStackOffset - Return true if the given stack call argument is
1871 /// already available in the same position (relatively) of the caller's
1872 /// incoming argument stack.
1873 static
1874 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1875                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1876                          const TargetInstrInfo *TII) {
1877   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1878   int FI = INT_MAX;
1879   if (Arg.getOpcode() == ISD::CopyFromReg) {
1880     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1881     if (!TargetRegisterInfo::isVirtualRegister(VR))
1882       return false;
1883     MachineInstr *Def = MRI->getVRegDef(VR);
1884     if (!Def)
1885       return false;
1886     if (!Flags.isByVal()) {
1887       if (!TII->isLoadFromStackSlot(Def, FI))
1888         return false;
1889     } else {
1890       return false;
1891     }
1892   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1893     if (Flags.isByVal())
1894       // ByVal argument is passed in as a pointer but it's now being
1895       // dereferenced. e.g.
1896       // define @foo(%struct.X* %A) {
1897       //   tail call @bar(%struct.X* byval %A)
1898       // }
1899       return false;
1900     SDValue Ptr = Ld->getBasePtr();
1901     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1902     if (!FINode)
1903       return false;
1904     FI = FINode->getIndex();
1905   } else
1906     return false;
1907
1908   assert(FI != INT_MAX);
1909   if (!MFI->isFixedObjectIndex(FI))
1910     return false;
1911   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1912 }
1913
1914 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1915 /// for tail call optimization. Targets which want to do tail call
1916 /// optimization should implement this function.
1917 bool
1918 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1919                                                      CallingConv::ID CalleeCC,
1920                                                      bool isVarArg,
1921                                                      bool isCalleeStructRet,
1922                                                      bool isCallerStructRet,
1923                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1924                                     const SmallVectorImpl<SDValue> &OutVals,
1925                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1926                                                      SelectionDAG& DAG) const {
1927   const Function *CallerF = DAG.getMachineFunction().getFunction();
1928   CallingConv::ID CallerCC = CallerF->getCallingConv();
1929   bool CCMatch = CallerCC == CalleeCC;
1930
1931   // Look for obvious safe cases to perform tail call optimization that do not
1932   // require ABI changes. This is what gcc calls sibcall.
1933
1934   // Do not sibcall optimize vararg calls unless the call site is not passing
1935   // any arguments.
1936   if (isVarArg && !Outs.empty())
1937     return false;
1938
1939   // Exception-handling functions need a special set of instructions to indicate
1940   // a return to the hardware. Tail-calling another function would probably
1941   // break this.
1942   if (CallerF->hasFnAttribute("interrupt"))
1943     return false;
1944
1945   // Also avoid sibcall optimization if either caller or callee uses struct
1946   // return semantics.
1947   if (isCalleeStructRet || isCallerStructRet)
1948     return false;
1949
1950   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1951   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1952   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1953   // support in the assembler and linker to be used. This would need to be
1954   // fixed to fully support tail calls in Thumb1.
1955   //
1956   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1957   // LR.  This means if we need to reload LR, it takes an extra instructions,
1958   // which outweighs the value of the tail call; but here we don't know yet
1959   // whether LR is going to be used.  Probably the right approach is to
1960   // generate the tail call here and turn it back into CALL/RET in
1961   // emitEpilogue if LR is used.
1962
1963   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1964   // but we need to make sure there are enough registers; the only valid
1965   // registers are the 4 used for parameters.  We don't currently do this
1966   // case.
1967   if (Subtarget->isThumb1Only())
1968     return false;
1969
1970   // If the calling conventions do not match, then we'd better make sure the
1971   // results are returned in the same way as what the caller expects.
1972   if (!CCMatch) {
1973     SmallVector<CCValAssign, 16> RVLocs1;
1974     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1975                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1976     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1977
1978     SmallVector<CCValAssign, 16> RVLocs2;
1979     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1980                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1981     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1982
1983     if (RVLocs1.size() != RVLocs2.size())
1984       return false;
1985     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1986       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1987         return false;
1988       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1989         return false;
1990       if (RVLocs1[i].isRegLoc()) {
1991         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1992           return false;
1993       } else {
1994         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1995           return false;
1996       }
1997     }
1998   }
1999
2000   // If Caller's vararg or byval argument has been split between registers and
2001   // stack, do not perform tail call, since part of the argument is in caller's
2002   // local frame.
2003   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2004                                       getInfo<ARMFunctionInfo>();
2005   if (AFI_Caller->getArgRegsSaveSize())
2006     return false;
2007
2008   // If the callee takes no arguments then go on to check the results of the
2009   // call.
2010   if (!Outs.empty()) {
2011     // Check if stack adjustment is needed. For now, do not do this if any
2012     // argument is passed on the stack.
2013     SmallVector<CCValAssign, 16> ArgLocs;
2014     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2015                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2016     CCInfo.AnalyzeCallOperands(Outs,
2017                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2018     if (CCInfo.getNextStackOffset()) {
2019       MachineFunction &MF = DAG.getMachineFunction();
2020
2021       // Check if the arguments are already laid out in the right way as
2022       // the caller's fixed stack objects.
2023       MachineFrameInfo *MFI = MF.getFrameInfo();
2024       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2025       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2026       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2027            i != e;
2028            ++i, ++realArgIdx) {
2029         CCValAssign &VA = ArgLocs[i];
2030         EVT RegVT = VA.getLocVT();
2031         SDValue Arg = OutVals[realArgIdx];
2032         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2033         if (VA.getLocInfo() == CCValAssign::Indirect)
2034           return false;
2035         if (VA.needsCustom()) {
2036           // f64 and vector types are split into multiple registers or
2037           // register/stack-slot combinations.  The types will not match
2038           // the registers; give up on memory f64 refs until we figure
2039           // out what to do about this.
2040           if (!VA.isRegLoc())
2041             return false;
2042           if (!ArgLocs[++i].isRegLoc())
2043             return false;
2044           if (RegVT == MVT::v2f64) {
2045             if (!ArgLocs[++i].isRegLoc())
2046               return false;
2047             if (!ArgLocs[++i].isRegLoc())
2048               return false;
2049           }
2050         } else if (!VA.isRegLoc()) {
2051           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2052                                    MFI, MRI, TII))
2053             return false;
2054         }
2055       }
2056     }
2057   }
2058
2059   return true;
2060 }
2061
2062 bool
2063 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2064                                   MachineFunction &MF, bool isVarArg,
2065                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2066                                   LLVMContext &Context) const {
2067   SmallVector<CCValAssign, 16> RVLocs;
2068   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2069   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2070                                                     isVarArg));
2071 }
2072
2073 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2074                                     SDLoc DL, SelectionDAG &DAG) {
2075   const MachineFunction &MF = DAG.getMachineFunction();
2076   const Function *F = MF.getFunction();
2077
2078   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2079
2080   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2081   // version of the "preferred return address". These offsets affect the return
2082   // instruction if this is a return from PL1 without hypervisor extensions.
2083   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2084   //    SWI:     0      "subs pc, lr, #0"
2085   //    ABORT:   +4     "subs pc, lr, #4"
2086   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2087   // UNDEF varies depending on where the exception came from ARM or Thumb
2088   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2089
2090   int64_t LROffset;
2091   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2092       IntKind == "ABORT")
2093     LROffset = 4;
2094   else if (IntKind == "SWI" || IntKind == "UNDEF")
2095     LROffset = 0;
2096   else
2097     report_fatal_error("Unsupported interrupt attribute. If present, value "
2098                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2099
2100   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2101
2102   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other,
2103                      RetOps.data(), RetOps.size());
2104 }
2105
2106 SDValue
2107 ARMTargetLowering::LowerReturn(SDValue Chain,
2108                                CallingConv::ID CallConv, bool isVarArg,
2109                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2110                                const SmallVectorImpl<SDValue> &OutVals,
2111                                SDLoc dl, SelectionDAG &DAG) const {
2112
2113   // CCValAssign - represent the assignment of the return value to a location.
2114   SmallVector<CCValAssign, 16> RVLocs;
2115
2116   // CCState - Info about the registers and stack slots.
2117   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2118                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2119
2120   // Analyze outgoing return values.
2121   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2122                                                isVarArg));
2123
2124   SDValue Flag;
2125   SmallVector<SDValue, 4> RetOps;
2126   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2127
2128   // Copy the result values into the output registers.
2129   for (unsigned i = 0, realRVLocIdx = 0;
2130        i != RVLocs.size();
2131        ++i, ++realRVLocIdx) {
2132     CCValAssign &VA = RVLocs[i];
2133     assert(VA.isRegLoc() && "Can only return in registers!");
2134
2135     SDValue Arg = OutVals[realRVLocIdx];
2136
2137     switch (VA.getLocInfo()) {
2138     default: llvm_unreachable("Unknown loc info!");
2139     case CCValAssign::Full: break;
2140     case CCValAssign::BCvt:
2141       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2142       break;
2143     }
2144
2145     if (VA.needsCustom()) {
2146       if (VA.getLocVT() == MVT::v2f64) {
2147         // Extract the first half and return it in two registers.
2148         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2149                                    DAG.getConstant(0, MVT::i32));
2150         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2151                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2152
2153         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), HalfGPRs, Flag);
2154         Flag = Chain.getValue(1);
2155         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2156         VA = RVLocs[++i]; // skip ahead to next loc
2157         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2158                                  HalfGPRs.getValue(1), Flag);
2159         Flag = Chain.getValue(1);
2160         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2161         VA = RVLocs[++i]; // skip ahead to next loc
2162
2163         // Extract the 2nd half and fall through to handle it as an f64 value.
2164         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2165                           DAG.getConstant(1, MVT::i32));
2166       }
2167       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2168       // available.
2169       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2170                                   DAG.getVTList(MVT::i32, MVT::i32), &Arg, 1);
2171       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd, Flag);
2172       Flag = Chain.getValue(1);
2173       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2174       VA = RVLocs[++i]; // skip ahead to next loc
2175       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), fmrrd.getValue(1),
2176                                Flag);
2177     } else
2178       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2179
2180     // Guarantee that all emitted copies are
2181     // stuck together, avoiding something bad.
2182     Flag = Chain.getValue(1);
2183     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2184   }
2185
2186   // Update chain and glue.
2187   RetOps[0] = Chain;
2188   if (Flag.getNode())
2189     RetOps.push_back(Flag);
2190
2191   // CPUs which aren't M-class use a special sequence to return from
2192   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2193   // though we use "subs pc, lr, #N").
2194   //
2195   // M-class CPUs actually use a normal return sequence with a special
2196   // (hardware-provided) value in LR, so the normal code path works.
2197   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2198       !Subtarget->isMClass()) {
2199     if (Subtarget->isThumb1Only())
2200       report_fatal_error("interrupt attribute is not supported in Thumb1");
2201     return LowerInterruptReturn(RetOps, dl, DAG);
2202   }
2203
2204   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other,
2205                      RetOps.data(), RetOps.size());
2206 }
2207
2208 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2209   if (N->getNumValues() != 1)
2210     return false;
2211   if (!N->hasNUsesOfValue(1, 0))
2212     return false;
2213
2214   SDValue TCChain = Chain;
2215   SDNode *Copy = *N->use_begin();
2216   if (Copy->getOpcode() == ISD::CopyToReg) {
2217     // If the copy has a glue operand, we conservatively assume it isn't safe to
2218     // perform a tail call.
2219     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2220       return false;
2221     TCChain = Copy->getOperand(0);
2222   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2223     SDNode *VMov = Copy;
2224     // f64 returned in a pair of GPRs.
2225     SmallPtrSet<SDNode*, 2> Copies;
2226     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2227          UI != UE; ++UI) {
2228       if (UI->getOpcode() != ISD::CopyToReg)
2229         return false;
2230       Copies.insert(*UI);
2231     }
2232     if (Copies.size() > 2)
2233       return false;
2234
2235     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2236          UI != UE; ++UI) {
2237       SDValue UseChain = UI->getOperand(0);
2238       if (Copies.count(UseChain.getNode()))
2239         // Second CopyToReg
2240         Copy = *UI;
2241       else
2242         // First CopyToReg
2243         TCChain = UseChain;
2244     }
2245   } else if (Copy->getOpcode() == ISD::BITCAST) {
2246     // f32 returned in a single GPR.
2247     if (!Copy->hasOneUse())
2248       return false;
2249     Copy = *Copy->use_begin();
2250     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2251       return false;
2252     TCChain = Copy->getOperand(0);
2253   } else {
2254     return false;
2255   }
2256
2257   bool HasRet = false;
2258   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2259        UI != UE; ++UI) {
2260     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2261         UI->getOpcode() != ARMISD::INTRET_FLAG)
2262       return false;
2263     HasRet = true;
2264   }
2265
2266   if (!HasRet)
2267     return false;
2268
2269   Chain = TCChain;
2270   return true;
2271 }
2272
2273 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2274   if (!Subtarget->supportsTailCall())
2275     return false;
2276
2277   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2278     return false;
2279
2280   return !Subtarget->isThumb1Only();
2281 }
2282
2283 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2284 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2285 // one of the above mentioned nodes. It has to be wrapped because otherwise
2286 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2287 // be used to form addressing mode. These wrapped nodes will be selected
2288 // into MOVi.
2289 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2290   EVT PtrVT = Op.getValueType();
2291   // FIXME there is no actual debug info here
2292   SDLoc dl(Op);
2293   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2294   SDValue Res;
2295   if (CP->isMachineConstantPoolEntry())
2296     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2297                                     CP->getAlignment());
2298   else
2299     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2300                                     CP->getAlignment());
2301   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2302 }
2303
2304 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2305   return MachineJumpTableInfo::EK_Inline;
2306 }
2307
2308 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2309                                              SelectionDAG &DAG) const {
2310   MachineFunction &MF = DAG.getMachineFunction();
2311   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2312   unsigned ARMPCLabelIndex = 0;
2313   SDLoc DL(Op);
2314   EVT PtrVT = getPointerTy();
2315   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2316   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2317   SDValue CPAddr;
2318   if (RelocM == Reloc::Static) {
2319     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2320   } else {
2321     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2322     ARMPCLabelIndex = AFI->createPICLabelUId();
2323     ARMConstantPoolValue *CPV =
2324       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2325                                       ARMCP::CPBlockAddress, PCAdj);
2326     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2327   }
2328   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2329   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2330                                MachinePointerInfo::getConstantPool(),
2331                                false, false, false, 0);
2332   if (RelocM == Reloc::Static)
2333     return Result;
2334   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2335   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2336 }
2337
2338 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2339 SDValue
2340 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2341                                                  SelectionDAG &DAG) const {
2342   SDLoc dl(GA);
2343   EVT PtrVT = getPointerTy();
2344   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2345   MachineFunction &MF = DAG.getMachineFunction();
2346   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2347   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2348   ARMConstantPoolValue *CPV =
2349     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2350                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2351   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2352   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2353   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2354                          MachinePointerInfo::getConstantPool(),
2355                          false, false, false, 0);
2356   SDValue Chain = Argument.getValue(1);
2357
2358   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2359   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2360
2361   // call __tls_get_addr.
2362   ArgListTy Args;
2363   ArgListEntry Entry;
2364   Entry.Node = Argument;
2365   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2366   Args.push_back(Entry);
2367   // FIXME: is there useful debug info available here?
2368   TargetLowering::CallLoweringInfo CLI(Chain,
2369                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2370                 false, false, false, false,
2371                 0, CallingConv::C, /*isTailCall=*/false,
2372                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2373                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2374   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2375   return CallResult.first;
2376 }
2377
2378 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2379 // "local exec" model.
2380 SDValue
2381 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2382                                         SelectionDAG &DAG,
2383                                         TLSModel::Model model) const {
2384   const GlobalValue *GV = GA->getGlobal();
2385   SDLoc dl(GA);
2386   SDValue Offset;
2387   SDValue Chain = DAG.getEntryNode();
2388   EVT PtrVT = getPointerTy();
2389   // Get the Thread Pointer
2390   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2391
2392   if (model == TLSModel::InitialExec) {
2393     MachineFunction &MF = DAG.getMachineFunction();
2394     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2395     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2396     // Initial exec model.
2397     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2398     ARMConstantPoolValue *CPV =
2399       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2400                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2401                                       true);
2402     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2403     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2404     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2405                          MachinePointerInfo::getConstantPool(),
2406                          false, false, false, 0);
2407     Chain = Offset.getValue(1);
2408
2409     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2410     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2411
2412     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2413                          MachinePointerInfo::getConstantPool(),
2414                          false, false, false, 0);
2415   } else {
2416     // local exec model
2417     assert(model == TLSModel::LocalExec);
2418     ARMConstantPoolValue *CPV =
2419       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2420     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2421     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2422     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2423                          MachinePointerInfo::getConstantPool(),
2424                          false, false, false, 0);
2425   }
2426
2427   // The address of the thread local variable is the add of the thread
2428   // pointer with the offset of the variable.
2429   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2430 }
2431
2432 SDValue
2433 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2434   // TODO: implement the "local dynamic" model
2435   assert(Subtarget->isTargetELF() &&
2436          "TLS not implemented for non-ELF targets");
2437   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2438
2439   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2440
2441   switch (model) {
2442     case TLSModel::GeneralDynamic:
2443     case TLSModel::LocalDynamic:
2444       return LowerToTLSGeneralDynamicModel(GA, DAG);
2445     case TLSModel::InitialExec:
2446     case TLSModel::LocalExec:
2447       return LowerToTLSExecModels(GA, DAG, model);
2448   }
2449   llvm_unreachable("bogus TLS model");
2450 }
2451
2452 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2453                                                  SelectionDAG &DAG) const {
2454   EVT PtrVT = getPointerTy();
2455   SDLoc dl(Op);
2456   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2457   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2458     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2459     ARMConstantPoolValue *CPV =
2460       ARMConstantPoolConstant::Create(GV,
2461                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2462     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2463     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2464     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2465                                  CPAddr,
2466                                  MachinePointerInfo::getConstantPool(),
2467                                  false, false, false, 0);
2468     SDValue Chain = Result.getValue(1);
2469     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2470     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2471     if (!UseGOTOFF)
2472       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2473                            MachinePointerInfo::getGOT(),
2474                            false, false, false, 0);
2475     return Result;
2476   }
2477
2478   // If we have T2 ops, we can materialize the address directly via movt/movw
2479   // pair. This is always cheaper.
2480   if (Subtarget->useMovt()) {
2481     ++NumMovwMovt;
2482     // FIXME: Once remat is capable of dealing with instructions with register
2483     // operands, expand this into two nodes.
2484     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2485                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2486   } else {
2487     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2488     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2489     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2490                        MachinePointerInfo::getConstantPool(),
2491                        false, false, false, 0);
2492   }
2493 }
2494
2495 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2496                                                     SelectionDAG &DAG) const {
2497   EVT PtrVT = getPointerTy();
2498   SDLoc dl(Op);
2499   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2500   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2501
2502   if (Subtarget->useMovt())
2503     ++NumMovwMovt;
2504
2505   // FIXME: Once remat is capable of dealing with instructions with register
2506   // operands, expand this into multiple nodes
2507   unsigned Wrapper =
2508       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2509
2510   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2511   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2512
2513   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2514     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2515                          MachinePointerInfo::getGOT(), false, false, false, 0);
2516   return Result;
2517 }
2518
2519 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2520                                                     SelectionDAG &DAG) const {
2521   assert(Subtarget->isTargetELF() &&
2522          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2523   MachineFunction &MF = DAG.getMachineFunction();
2524   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2525   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2526   EVT PtrVT = getPointerTy();
2527   SDLoc dl(Op);
2528   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2529   ARMConstantPoolValue *CPV =
2530     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2531                                   ARMPCLabelIndex, PCAdj);
2532   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2533   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2534   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2535                                MachinePointerInfo::getConstantPool(),
2536                                false, false, false, 0);
2537   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2538   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2539 }
2540
2541 SDValue
2542 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2543   SDLoc dl(Op);
2544   SDValue Val = DAG.getConstant(0, MVT::i32);
2545   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2546                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2547                      Op.getOperand(1), Val);
2548 }
2549
2550 SDValue
2551 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2552   SDLoc dl(Op);
2553   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2554                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2555 }
2556
2557 SDValue
2558 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2559                                           const ARMSubtarget *Subtarget) const {
2560   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2561   SDLoc dl(Op);
2562   switch (IntNo) {
2563   default: return SDValue();    // Don't custom lower most intrinsics.
2564   case Intrinsic::arm_thread_pointer: {
2565     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2566     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2567   }
2568   case Intrinsic::eh_sjlj_lsda: {
2569     MachineFunction &MF = DAG.getMachineFunction();
2570     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2571     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2572     EVT PtrVT = getPointerTy();
2573     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2574     SDValue CPAddr;
2575     unsigned PCAdj = (RelocM != Reloc::PIC_)
2576       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2577     ARMConstantPoolValue *CPV =
2578       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2579                                       ARMCP::CPLSDA, PCAdj);
2580     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2581     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2582     SDValue Result =
2583       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2584                   MachinePointerInfo::getConstantPool(),
2585                   false, false, false, 0);
2586
2587     if (RelocM == Reloc::PIC_) {
2588       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2589       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2590     }
2591     return Result;
2592   }
2593   case Intrinsic::arm_neon_vmulls:
2594   case Intrinsic::arm_neon_vmullu: {
2595     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2596       ? ARMISD::VMULLs : ARMISD::VMULLu;
2597     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2598                        Op.getOperand(1), Op.getOperand(2));
2599   }
2600   }
2601 }
2602
2603 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2604                                  const ARMSubtarget *Subtarget) {
2605   // FIXME: handle "fence singlethread" more efficiently.
2606   SDLoc dl(Op);
2607   if (!Subtarget->hasDataBarrier()) {
2608     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2609     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2610     // here.
2611     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2612            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2613     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2614                        DAG.getConstant(0, MVT::i32));
2615   }
2616
2617   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2618   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2619   unsigned Domain = ARM_MB::ISH;
2620   if (Subtarget->isMClass()) {
2621     // Only a full system barrier exists in the M-class architectures.
2622     Domain = ARM_MB::SY;
2623   } else if (Subtarget->isSwift() && Ord == Release) {
2624     // Swift happens to implement ISHST barriers in a way that's compatible with
2625     // Release semantics but weaker than ISH so we'd be fools not to use
2626     // it. Beware: other processors probably don't!
2627     Domain = ARM_MB::ISHST;
2628   }
2629
2630   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2631                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2632                      DAG.getConstant(Domain, MVT::i32));
2633 }
2634
2635 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2636                              const ARMSubtarget *Subtarget) {
2637   // ARM pre v5TE and Thumb1 does not have preload instructions.
2638   if (!(Subtarget->isThumb2() ||
2639         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2640     // Just preserve the chain.
2641     return Op.getOperand(0);
2642
2643   SDLoc dl(Op);
2644   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2645   if (!isRead &&
2646       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2647     // ARMv7 with MP extension has PLDW.
2648     return Op.getOperand(0);
2649
2650   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2651   if (Subtarget->isThumb()) {
2652     // Invert the bits.
2653     isRead = ~isRead & 1;
2654     isData = ~isData & 1;
2655   }
2656
2657   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2658                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2659                      DAG.getConstant(isData, MVT::i32));
2660 }
2661
2662 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2663   MachineFunction &MF = DAG.getMachineFunction();
2664   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2665
2666   // vastart just stores the address of the VarArgsFrameIndex slot into the
2667   // memory location argument.
2668   SDLoc dl(Op);
2669   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2670   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2671   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2672   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2673                       MachinePointerInfo(SV), false, false, 0);
2674 }
2675
2676 SDValue
2677 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2678                                         SDValue &Root, SelectionDAG &DAG,
2679                                         SDLoc dl) const {
2680   MachineFunction &MF = DAG.getMachineFunction();
2681   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2682
2683   const TargetRegisterClass *RC;
2684   if (AFI->isThumb1OnlyFunction())
2685     RC = &ARM::tGPRRegClass;
2686   else
2687     RC = &ARM::GPRRegClass;
2688
2689   // Transform the arguments stored in physical registers into virtual ones.
2690   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2691   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2692
2693   SDValue ArgValue2;
2694   if (NextVA.isMemLoc()) {
2695     MachineFrameInfo *MFI = MF.getFrameInfo();
2696     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2697
2698     // Create load node to retrieve arguments from the stack.
2699     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2700     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2701                             MachinePointerInfo::getFixedStack(FI),
2702                             false, false, false, 0);
2703   } else {
2704     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2705     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2706   }
2707
2708   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2709 }
2710
2711 void
2712 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2713                                   unsigned InRegsParamRecordIdx,
2714                                   unsigned ArgSize,
2715                                   unsigned &ArgRegsSize,
2716                                   unsigned &ArgRegsSaveSize)
2717   const {
2718   unsigned NumGPRs;
2719   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2720     unsigned RBegin, REnd;
2721     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2722     NumGPRs = REnd - RBegin;
2723   } else {
2724     unsigned int firstUnalloced;
2725     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2726                                                 sizeof(GPRArgRegs) /
2727                                                 sizeof(GPRArgRegs[0]));
2728     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2729   }
2730
2731   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2732   ArgRegsSize = NumGPRs * 4;
2733
2734   // If parameter is split between stack and GPRs...
2735   if (NumGPRs && Align > 4 &&
2736       (ArgRegsSize < ArgSize ||
2737         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2738     // Add padding for part of param recovered from GPRs.  For example,
2739     // if Align == 8, its last byte must be at address K*8 - 1.
2740     // We need to do it, since remained (stack) part of parameter has
2741     // stack alignment, and we need to "attach" "GPRs head" without gaps
2742     // to it:
2743     // Stack:
2744     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2745     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2746     //
2747     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2748     unsigned Padding =
2749         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2750     ArgRegsSaveSize = ArgRegsSize + Padding;
2751   } else
2752     // We don't need to extend regs save size for byval parameters if they
2753     // are passed via GPRs only.
2754     ArgRegsSaveSize = ArgRegsSize;
2755 }
2756
2757 // The remaining GPRs hold either the beginning of variable-argument
2758 // data, or the beginning of an aggregate passed by value (usually
2759 // byval).  Either way, we allocate stack slots adjacent to the data
2760 // provided by our caller, and store the unallocated registers there.
2761 // If this is a variadic function, the va_list pointer will begin with
2762 // these values; otherwise, this reassembles a (byval) structure that
2763 // was split between registers and memory.
2764 // Return: The frame index registers were stored into.
2765 int
2766 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2767                                   SDLoc dl, SDValue &Chain,
2768                                   const Value *OrigArg,
2769                                   unsigned InRegsParamRecordIdx,
2770                                   unsigned OffsetFromOrigArg,
2771                                   unsigned ArgOffset,
2772                                   unsigned ArgSize,
2773                                   bool ForceMutable,
2774                                   unsigned ByValStoreOffset,
2775                                   unsigned TotalArgRegsSaveSize) const {
2776
2777   // Currently, two use-cases possible:
2778   // Case #1. Non-var-args function, and we meet first byval parameter.
2779   //          Setup first unallocated register as first byval register;
2780   //          eat all remained registers
2781   //          (these two actions are performed by HandleByVal method).
2782   //          Then, here, we initialize stack frame with
2783   //          "store-reg" instructions.
2784   // Case #2. Var-args function, that doesn't contain byval parameters.
2785   //          The same: eat all remained unallocated registers,
2786   //          initialize stack frame.
2787
2788   MachineFunction &MF = DAG.getMachineFunction();
2789   MachineFrameInfo *MFI = MF.getFrameInfo();
2790   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2791   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2792   unsigned RBegin, REnd;
2793   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2794     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2795     firstRegToSaveIndex = RBegin - ARM::R0;
2796     lastRegToSaveIndex = REnd - ARM::R0;
2797   } else {
2798     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2799       (GPRArgRegs, array_lengthof(GPRArgRegs));
2800     lastRegToSaveIndex = 4;
2801   }
2802
2803   unsigned ArgRegsSize, ArgRegsSaveSize;
2804   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2805                  ArgRegsSize, ArgRegsSaveSize);
2806
2807   // Store any by-val regs to their spots on the stack so that they may be
2808   // loaded by deferencing the result of formal parameter pointer or va_next.
2809   // Note: once stack area for byval/varargs registers
2810   // was initialized, it can't be initialized again.
2811   if (ArgRegsSaveSize) {
2812     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2813
2814     if (Padding) {
2815       assert(AFI->getStoredByValParamsPadding() == 0 &&
2816              "The only parameter may be padded.");
2817       AFI->setStoredByValParamsPadding(Padding);
2818     }
2819
2820     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2821                                             Padding +
2822                                               ByValStoreOffset -
2823                                               (int64_t)TotalArgRegsSaveSize,
2824                                             false);
2825     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2826     if (Padding) {
2827        MFI->CreateFixedObject(Padding,
2828                               ArgOffset + ByValStoreOffset -
2829                                 (int64_t)ArgRegsSaveSize,
2830                               false);
2831     }
2832
2833     SmallVector<SDValue, 4> MemOps;
2834     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2835          ++firstRegToSaveIndex, ++i) {
2836       const TargetRegisterClass *RC;
2837       if (AFI->isThumb1OnlyFunction())
2838         RC = &ARM::tGPRRegClass;
2839       else
2840         RC = &ARM::GPRRegClass;
2841
2842       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2843       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2844       SDValue Store =
2845         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2846                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2847                      false, false, 0);
2848       MemOps.push_back(Store);
2849       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2850                         DAG.getConstant(4, getPointerTy()));
2851     }
2852
2853     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2854
2855     if (!MemOps.empty())
2856       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2857                           &MemOps[0], MemOps.size());
2858     return FrameIndex;
2859   } else {
2860     if (ArgSize == 0) {
2861       // We cannot allocate a zero-byte object for the first variadic argument,
2862       // so just make up a size.
2863       ArgSize = 4;
2864     }
2865     // This will point to the next argument passed via stack.
2866     return MFI->CreateFixedObject(
2867       ArgSize, ArgOffset, !ForceMutable);
2868   }
2869 }
2870
2871 // Setup stack frame, the va_list pointer will start from.
2872 void
2873 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2874                                         SDLoc dl, SDValue &Chain,
2875                                         unsigned ArgOffset,
2876                                         unsigned TotalArgRegsSaveSize,
2877                                         bool ForceMutable) const {
2878   MachineFunction &MF = DAG.getMachineFunction();
2879   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2880
2881   // Try to store any remaining integer argument regs
2882   // to their spots on the stack so that they may be loaded by deferencing
2883   // the result of va_next.
2884   // If there is no regs to be stored, just point address after last
2885   // argument passed via stack.
2886   int FrameIndex =
2887     StoreByValRegs(CCInfo, DAG, dl, Chain, 0, CCInfo.getInRegsParamsCount(),
2888                    0, ArgOffset, 0, ForceMutable, 0, TotalArgRegsSaveSize);
2889
2890   AFI->setVarArgsFrameIndex(FrameIndex);
2891 }
2892
2893 SDValue
2894 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2895                                         CallingConv::ID CallConv, bool isVarArg,
2896                                         const SmallVectorImpl<ISD::InputArg>
2897                                           &Ins,
2898                                         SDLoc dl, SelectionDAG &DAG,
2899                                         SmallVectorImpl<SDValue> &InVals)
2900                                           const {
2901   MachineFunction &MF = DAG.getMachineFunction();
2902   MachineFrameInfo *MFI = MF.getFrameInfo();
2903
2904   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2905
2906   // Assign locations to all of the incoming arguments.
2907   SmallVector<CCValAssign, 16> ArgLocs;
2908   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2909                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2910   CCInfo.AnalyzeFormalArguments(Ins,
2911                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2912                                                   isVarArg));
2913
2914   SmallVector<SDValue, 16> ArgValues;
2915   int lastInsIndex = -1;
2916   SDValue ArgValue;
2917   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2918   unsigned CurArgIdx = 0;
2919
2920   // Initially ArgRegsSaveSize is zero.
2921   // Then we increase this value each time we meet byval parameter.
2922   // We also increase this value in case of varargs function.
2923   AFI->setArgRegsSaveSize(0);
2924
2925   unsigned ByValStoreOffset = 0;
2926   unsigned TotalArgRegsSaveSize = 0;
2927   unsigned ArgRegsSaveSizeMaxAlign = 4;
2928
2929   // Calculate the amount of stack space that we need to allocate to store
2930   // byval and variadic arguments that are passed in registers.
2931   // We need to know this before we allocate the first byval or variadic
2932   // argument, as they will be allocated a stack slot below the CFA (Canonical
2933   // Frame Address, the stack pointer at entry to the function).
2934   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2935     CCValAssign &VA = ArgLocs[i];
2936     if (VA.isMemLoc()) {
2937       int index = VA.getValNo();
2938       if (index != lastInsIndex) {
2939         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2940         if (Flags.isByVal()) {
2941           unsigned ExtraArgRegsSize;
2942           unsigned ExtraArgRegsSaveSize;
2943           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2944                          Flags.getByValSize(),
2945                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2946
2947           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2948           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2949               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2950           CCInfo.nextInRegsParam();
2951         }
2952         lastInsIndex = index;
2953       }
2954     }
2955   }
2956   CCInfo.rewindByValRegsInfo();
2957   lastInsIndex = -1;
2958   if (isVarArg) {
2959     unsigned ExtraArgRegsSize;
2960     unsigned ExtraArgRegsSaveSize;
2961     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2962                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2963     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2964   }
2965   // If the arg regs save area contains N-byte aligned values, the
2966   // bottom of it must be at least N-byte aligned.
2967   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2968   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2969
2970   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2971     CCValAssign &VA = ArgLocs[i];
2972     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2973     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2974     // Arguments stored in registers.
2975     if (VA.isRegLoc()) {
2976       EVT RegVT = VA.getLocVT();
2977
2978       if (VA.needsCustom()) {
2979         // f64 and vector types are split up into multiple registers or
2980         // combinations of registers and stack slots.
2981         if (VA.getLocVT() == MVT::v2f64) {
2982           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2983                                                    Chain, DAG, dl);
2984           VA = ArgLocs[++i]; // skip ahead to next loc
2985           SDValue ArgValue2;
2986           if (VA.isMemLoc()) {
2987             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2988             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2989             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2990                                     MachinePointerInfo::getFixedStack(FI),
2991                                     false, false, false, 0);
2992           } else {
2993             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2994                                              Chain, DAG, dl);
2995           }
2996           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2997           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2998                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2999           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3000                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3001         } else
3002           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3003
3004       } else {
3005         const TargetRegisterClass *RC;
3006
3007         if (RegVT == MVT::f32)
3008           RC = &ARM::SPRRegClass;
3009         else if (RegVT == MVT::f64)
3010           RC = &ARM::DPRRegClass;
3011         else if (RegVT == MVT::v2f64)
3012           RC = &ARM::QPRRegClass;
3013         else if (RegVT == MVT::i32)
3014           RC = AFI->isThumb1OnlyFunction() ?
3015             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3016             (const TargetRegisterClass*)&ARM::GPRRegClass;
3017         else
3018           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3019
3020         // Transform the arguments in physical registers into virtual ones.
3021         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3022         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3023       }
3024
3025       // If this is an 8 or 16-bit value, it is really passed promoted
3026       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3027       // truncate to the right size.
3028       switch (VA.getLocInfo()) {
3029       default: llvm_unreachable("Unknown loc info!");
3030       case CCValAssign::Full: break;
3031       case CCValAssign::BCvt:
3032         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3033         break;
3034       case CCValAssign::SExt:
3035         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3036                                DAG.getValueType(VA.getValVT()));
3037         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3038         break;
3039       case CCValAssign::ZExt:
3040         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3041                                DAG.getValueType(VA.getValVT()));
3042         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3043         break;
3044       }
3045
3046       InVals.push_back(ArgValue);
3047
3048     } else { // VA.isRegLoc()
3049
3050       // sanity check
3051       assert(VA.isMemLoc());
3052       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3053
3054       int index = ArgLocs[i].getValNo();
3055
3056       // Some Ins[] entries become multiple ArgLoc[] entries.
3057       // Process them only once.
3058       if (index != lastInsIndex)
3059         {
3060           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3061           // FIXME: For now, all byval parameter objects are marked mutable.
3062           // This can be changed with more analysis.
3063           // In case of tail call optimization mark all arguments mutable.
3064           // Since they could be overwritten by lowering of arguments in case of
3065           // a tail call.
3066           if (Flags.isByVal()) {
3067             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3068
3069             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3070             int FrameIndex = StoreByValRegs(
3071                 CCInfo, DAG, dl, Chain, CurOrigArg,
3072                 CurByValIndex,
3073                 Ins[VA.getValNo()].PartOffset,
3074                 VA.getLocMemOffset(),
3075                 Flags.getByValSize(),
3076                 true /*force mutable frames*/,
3077                 ByValStoreOffset,
3078                 TotalArgRegsSaveSize);
3079             ByValStoreOffset += Flags.getByValSize();
3080             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3081             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3082             CCInfo.nextInRegsParam();
3083           } else {
3084             unsigned FIOffset = VA.getLocMemOffset();
3085             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3086                                             FIOffset, true);
3087
3088             // Create load nodes to retrieve arguments from the stack.
3089             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3090             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3091                                          MachinePointerInfo::getFixedStack(FI),
3092                                          false, false, false, 0));
3093           }
3094           lastInsIndex = index;
3095         }
3096     }
3097   }
3098
3099   // varargs
3100   if (isVarArg)
3101     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3102                          CCInfo.getNextStackOffset(),
3103                          TotalArgRegsSaveSize);
3104
3105   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3106
3107   return Chain;
3108 }
3109
3110 /// isFloatingPointZero - Return true if this is +0.0.
3111 static bool isFloatingPointZero(SDValue Op) {
3112   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3113     return CFP->getValueAPF().isPosZero();
3114   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3115     // Maybe this has already been legalized into the constant pool?
3116     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3117       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3118       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3119         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3120           return CFP->getValueAPF().isPosZero();
3121     }
3122   }
3123   return false;
3124 }
3125
3126 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3127 /// the given operands.
3128 SDValue
3129 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3130                              SDValue &ARMcc, SelectionDAG &DAG,
3131                              SDLoc dl) const {
3132   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3133     unsigned C = RHSC->getZExtValue();
3134     if (!isLegalICmpImmediate(C)) {
3135       // Constant does not fit, try adjusting it by one?
3136       switch (CC) {
3137       default: break;
3138       case ISD::SETLT:
3139       case ISD::SETGE:
3140         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3141           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3142           RHS = DAG.getConstant(C-1, MVT::i32);
3143         }
3144         break;
3145       case ISD::SETULT:
3146       case ISD::SETUGE:
3147         if (C != 0 && isLegalICmpImmediate(C-1)) {
3148           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3149           RHS = DAG.getConstant(C-1, MVT::i32);
3150         }
3151         break;
3152       case ISD::SETLE:
3153       case ISD::SETGT:
3154         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3155           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3156           RHS = DAG.getConstant(C+1, MVT::i32);
3157         }
3158         break;
3159       case ISD::SETULE:
3160       case ISD::SETUGT:
3161         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3162           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3163           RHS = DAG.getConstant(C+1, MVT::i32);
3164         }
3165         break;
3166       }
3167     }
3168   }
3169
3170   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3171   ARMISD::NodeType CompareType;
3172   switch (CondCode) {
3173   default:
3174     CompareType = ARMISD::CMP;
3175     break;
3176   case ARMCC::EQ:
3177   case ARMCC::NE:
3178     // Uses only Z Flag
3179     CompareType = ARMISD::CMPZ;
3180     break;
3181   }
3182   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3183   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3184 }
3185
3186 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3187 SDValue
3188 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3189                              SDLoc dl) const {
3190   SDValue Cmp;
3191   if (!isFloatingPointZero(RHS))
3192     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3193   else
3194     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3195   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3196 }
3197
3198 /// duplicateCmp - Glue values can have only one use, so this function
3199 /// duplicates a comparison node.
3200 SDValue
3201 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3202   unsigned Opc = Cmp.getOpcode();
3203   SDLoc DL(Cmp);
3204   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3205     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3206
3207   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3208   Cmp = Cmp.getOperand(0);
3209   Opc = Cmp.getOpcode();
3210   if (Opc == ARMISD::CMPFP)
3211     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3212   else {
3213     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3214     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3215   }
3216   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3217 }
3218
3219 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3220   SDValue Cond = Op.getOperand(0);
3221   SDValue SelectTrue = Op.getOperand(1);
3222   SDValue SelectFalse = Op.getOperand(2);
3223   SDLoc dl(Op);
3224
3225   // Convert:
3226   //
3227   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3228   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3229   //
3230   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3231     const ConstantSDNode *CMOVTrue =
3232       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3233     const ConstantSDNode *CMOVFalse =
3234       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3235
3236     if (CMOVTrue && CMOVFalse) {
3237       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3238       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3239
3240       SDValue True;
3241       SDValue False;
3242       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3243         True = SelectTrue;
3244         False = SelectFalse;
3245       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3246         True = SelectFalse;
3247         False = SelectTrue;
3248       }
3249
3250       if (True.getNode() && False.getNode()) {
3251         EVT VT = Op.getValueType();
3252         SDValue ARMcc = Cond.getOperand(2);
3253         SDValue CCR = Cond.getOperand(3);
3254         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3255         assert(True.getValueType() == VT);
3256         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3257       }
3258     }
3259   }
3260
3261   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3262   // undefined bits before doing a full-word comparison with zero.
3263   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3264                      DAG.getConstant(1, Cond.getValueType()));
3265
3266   return DAG.getSelectCC(dl, Cond,
3267                          DAG.getConstant(0, Cond.getValueType()),
3268                          SelectTrue, SelectFalse, ISD::SETNE);
3269 }
3270
3271 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3272   if (CC == ISD::SETNE)
3273     return ISD::SETEQ;
3274   return ISD::getSetCCInverse(CC, true);
3275 }
3276
3277 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3278                                  bool &swpCmpOps, bool &swpVselOps) {
3279   // Start by selecting the GE condition code for opcodes that return true for
3280   // 'equality'
3281   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3282       CC == ISD::SETULE)
3283     CondCode = ARMCC::GE;
3284
3285   // and GT for opcodes that return false for 'equality'.
3286   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3287            CC == ISD::SETULT)
3288     CondCode = ARMCC::GT;
3289
3290   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3291   // to swap the compare operands.
3292   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3293       CC == ISD::SETULT)
3294     swpCmpOps = true;
3295
3296   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3297   // If we have an unordered opcode, we need to swap the operands to the VSEL
3298   // instruction (effectively negating the condition).
3299   //
3300   // This also has the effect of swapping which one of 'less' or 'greater'
3301   // returns true, so we also swap the compare operands. It also switches
3302   // whether we return true for 'equality', so we compensate by picking the
3303   // opposite condition code to our original choice.
3304   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3305       CC == ISD::SETUGT) {
3306     swpCmpOps = !swpCmpOps;
3307     swpVselOps = !swpVselOps;
3308     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3309   }
3310
3311   // 'ordered' is 'anything but unordered', so use the VS condition code and
3312   // swap the VSEL operands.
3313   if (CC == ISD::SETO) {
3314     CondCode = ARMCC::VS;
3315     swpVselOps = true;
3316   }
3317
3318   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3319   // code and swap the VSEL operands.
3320   if (CC == ISD::SETUNE) {
3321     CondCode = ARMCC::EQ;
3322     swpVselOps = true;
3323   }
3324 }
3325
3326 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3327   EVT VT = Op.getValueType();
3328   SDValue LHS = Op.getOperand(0);
3329   SDValue RHS = Op.getOperand(1);
3330   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3331   SDValue TrueVal = Op.getOperand(2);
3332   SDValue FalseVal = Op.getOperand(3);
3333   SDLoc dl(Op);
3334
3335   if (LHS.getValueType() == MVT::i32) {
3336     // Try to generate VSEL on ARMv8.
3337     // The VSEL instruction can't use all the usual ARM condition
3338     // codes: it only has two bits to select the condition code, so it's
3339     // constrained to use only GE, GT, VS and EQ.
3340     //
3341     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3342     // swap the operands of the previous compare instruction (effectively
3343     // inverting the compare condition, swapping 'less' and 'greater') and
3344     // sometimes need to swap the operands to the VSEL (which inverts the
3345     // condition in the sense of firing whenever the previous condition didn't)
3346     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3347                                       TrueVal.getValueType() == MVT::f64)) {
3348       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3349       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3350           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3351         CC = getInverseCCForVSEL(CC);
3352         std::swap(TrueVal, FalseVal);
3353       }
3354     }
3355
3356     SDValue ARMcc;
3357     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3358     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3359     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3360                        Cmp);
3361   }
3362
3363   ARMCC::CondCodes CondCode, CondCode2;
3364   FPCCToARMCC(CC, CondCode, CondCode2);
3365
3366   // Try to generate VSEL on ARMv8.
3367   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3368                                     TrueVal.getValueType() == MVT::f64)) {
3369     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3370     // same operands, as follows:
3371     //   c = fcmp [ogt, olt, ugt, ult] a, b
3372     //   select c, a, b
3373     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3374     // handled differently than the original code sequence.
3375     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3376         RHS == FalseVal) {
3377       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3378         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3379       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3380         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3381     }
3382
3383     bool swpCmpOps = false;
3384     bool swpVselOps = false;
3385     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3386
3387     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3388         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3389       if (swpCmpOps)
3390         std::swap(LHS, RHS);
3391       if (swpVselOps)
3392         std::swap(TrueVal, FalseVal);
3393     }
3394   }
3395
3396   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3397   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3398   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3399   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3400                                ARMcc, CCR, Cmp);
3401   if (CondCode2 != ARMCC::AL) {
3402     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3403     // FIXME: Needs another CMP because flag can have but one use.
3404     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3405     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3406                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3407   }
3408   return Result;
3409 }
3410
3411 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3412 /// to morph to an integer compare sequence.
3413 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3414                            const ARMSubtarget *Subtarget) {
3415   SDNode *N = Op.getNode();
3416   if (!N->hasOneUse())
3417     // Otherwise it requires moving the value from fp to integer registers.
3418     return false;
3419   if (!N->getNumValues())
3420     return false;
3421   EVT VT = Op.getValueType();
3422   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3423     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3424     // vmrs are very slow, e.g. cortex-a8.
3425     return false;
3426
3427   if (isFloatingPointZero(Op)) {
3428     SeenZero = true;
3429     return true;
3430   }
3431   return ISD::isNormalLoad(N);
3432 }
3433
3434 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3435   if (isFloatingPointZero(Op))
3436     return DAG.getConstant(0, MVT::i32);
3437
3438   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3439     return DAG.getLoad(MVT::i32, SDLoc(Op),
3440                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3441                        Ld->isVolatile(), Ld->isNonTemporal(),
3442                        Ld->isInvariant(), Ld->getAlignment());
3443
3444   llvm_unreachable("Unknown VFP cmp argument!");
3445 }
3446
3447 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3448                            SDValue &RetVal1, SDValue &RetVal2) {
3449   if (isFloatingPointZero(Op)) {
3450     RetVal1 = DAG.getConstant(0, MVT::i32);
3451     RetVal2 = DAG.getConstant(0, MVT::i32);
3452     return;
3453   }
3454
3455   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3456     SDValue Ptr = Ld->getBasePtr();
3457     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3458                           Ld->getChain(), Ptr,
3459                           Ld->getPointerInfo(),
3460                           Ld->isVolatile(), Ld->isNonTemporal(),
3461                           Ld->isInvariant(), Ld->getAlignment());
3462
3463     EVT PtrType = Ptr.getValueType();
3464     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3465     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3466                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3467     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3468                           Ld->getChain(), NewPtr,
3469                           Ld->getPointerInfo().getWithOffset(4),
3470                           Ld->isVolatile(), Ld->isNonTemporal(),
3471                           Ld->isInvariant(), NewAlign);
3472     return;
3473   }
3474
3475   llvm_unreachable("Unknown VFP cmp argument!");
3476 }
3477
3478 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3479 /// f32 and even f64 comparisons to integer ones.
3480 SDValue
3481 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3482   SDValue Chain = Op.getOperand(0);
3483   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3484   SDValue LHS = Op.getOperand(2);
3485   SDValue RHS = Op.getOperand(3);
3486   SDValue Dest = Op.getOperand(4);
3487   SDLoc dl(Op);
3488
3489   bool LHSSeenZero = false;
3490   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3491   bool RHSSeenZero = false;
3492   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3493   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3494     // If unsafe fp math optimization is enabled and there are no other uses of
3495     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3496     // to an integer comparison.
3497     if (CC == ISD::SETOEQ)
3498       CC = ISD::SETEQ;
3499     else if (CC == ISD::SETUNE)
3500       CC = ISD::SETNE;
3501
3502     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3503     SDValue ARMcc;
3504     if (LHS.getValueType() == MVT::f32) {
3505       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3506                         bitcastf32Toi32(LHS, DAG), Mask);
3507       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3508                         bitcastf32Toi32(RHS, DAG), Mask);
3509       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3510       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3511       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3512                          Chain, Dest, ARMcc, CCR, Cmp);
3513     }
3514
3515     SDValue LHS1, LHS2;
3516     SDValue RHS1, RHS2;
3517     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3518     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3519     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3520     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3521     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3522     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3523     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3524     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3525     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops, 7);
3526   }
3527
3528   return SDValue();
3529 }
3530
3531 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3532   SDValue Chain = Op.getOperand(0);
3533   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3534   SDValue LHS = Op.getOperand(2);
3535   SDValue RHS = Op.getOperand(3);
3536   SDValue Dest = Op.getOperand(4);
3537   SDLoc dl(Op);
3538
3539   if (LHS.getValueType() == MVT::i32) {
3540     SDValue ARMcc;
3541     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3542     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3543     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3544                        Chain, Dest, ARMcc, CCR, Cmp);
3545   }
3546
3547   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3548
3549   if (getTargetMachine().Options.UnsafeFPMath &&
3550       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3551        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3552     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3553     if (Result.getNode())
3554       return Result;
3555   }
3556
3557   ARMCC::CondCodes CondCode, CondCode2;
3558   FPCCToARMCC(CC, CondCode, CondCode2);
3559
3560   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3561   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3562   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3563   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3564   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3565   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3566   if (CondCode2 != ARMCC::AL) {
3567     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3568     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3569     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops, 5);
3570   }
3571   return Res;
3572 }
3573
3574 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3575   SDValue Chain = Op.getOperand(0);
3576   SDValue Table = Op.getOperand(1);
3577   SDValue Index = Op.getOperand(2);
3578   SDLoc dl(Op);
3579
3580   EVT PTy = getPointerTy();
3581   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3582   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3583   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3584   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3585   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3586   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3587   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3588   if (Subtarget->isThumb2()) {
3589     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3590     // which does another jump to the destination. This also makes it easier
3591     // to translate it to TBB / TBH later.
3592     // FIXME: This might not work if the function is extremely large.
3593     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3594                        Addr, Op.getOperand(2), JTI, UId);
3595   }
3596   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3597     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3598                        MachinePointerInfo::getJumpTable(),
3599                        false, false, false, 0);
3600     Chain = Addr.getValue(1);
3601     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3602     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3603   } else {
3604     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3605                        MachinePointerInfo::getJumpTable(),
3606                        false, false, false, 0);
3607     Chain = Addr.getValue(1);
3608     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3609   }
3610 }
3611
3612 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3613   EVT VT = Op.getValueType();
3614   SDLoc dl(Op);
3615
3616   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3617     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3618       return Op;
3619     return DAG.UnrollVectorOp(Op.getNode());
3620   }
3621
3622   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3623          "Invalid type for custom lowering!");
3624   if (VT != MVT::v4i16)
3625     return DAG.UnrollVectorOp(Op.getNode());
3626
3627   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3628   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3629 }
3630
3631 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3632   EVT VT = Op.getValueType();
3633   if (VT.isVector())
3634     return LowerVectorFP_TO_INT(Op, DAG);
3635
3636   SDLoc dl(Op);
3637   unsigned Opc;
3638
3639   switch (Op.getOpcode()) {
3640   default: llvm_unreachable("Invalid opcode!");
3641   case ISD::FP_TO_SINT:
3642     Opc = ARMISD::FTOSI;
3643     break;
3644   case ISD::FP_TO_UINT:
3645     Opc = ARMISD::FTOUI;
3646     break;
3647   }
3648   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3649   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3650 }
3651
3652 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3653   EVT VT = Op.getValueType();
3654   SDLoc dl(Op);
3655
3656   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3657     if (VT.getVectorElementType() == MVT::f32)
3658       return Op;
3659     return DAG.UnrollVectorOp(Op.getNode());
3660   }
3661
3662   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3663          "Invalid type for custom lowering!");
3664   if (VT != MVT::v4f32)
3665     return DAG.UnrollVectorOp(Op.getNode());
3666
3667   unsigned CastOpc;
3668   unsigned Opc;
3669   switch (Op.getOpcode()) {
3670   default: llvm_unreachable("Invalid opcode!");
3671   case ISD::SINT_TO_FP:
3672     CastOpc = ISD::SIGN_EXTEND;
3673     Opc = ISD::SINT_TO_FP;
3674     break;
3675   case ISD::UINT_TO_FP:
3676     CastOpc = ISD::ZERO_EXTEND;
3677     Opc = ISD::UINT_TO_FP;
3678     break;
3679   }
3680
3681   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3682   return DAG.getNode(Opc, dl, VT, Op);
3683 }
3684
3685 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3686   EVT VT = Op.getValueType();
3687   if (VT.isVector())
3688     return LowerVectorINT_TO_FP(Op, DAG);
3689
3690   SDLoc dl(Op);
3691   unsigned Opc;
3692
3693   switch (Op.getOpcode()) {
3694   default: llvm_unreachable("Invalid opcode!");
3695   case ISD::SINT_TO_FP:
3696     Opc = ARMISD::SITOF;
3697     break;
3698   case ISD::UINT_TO_FP:
3699     Opc = ARMISD::UITOF;
3700     break;
3701   }
3702
3703   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3704   return DAG.getNode(Opc, dl, VT, Op);
3705 }
3706
3707 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3708   // Implement fcopysign with a fabs and a conditional fneg.
3709   SDValue Tmp0 = Op.getOperand(0);
3710   SDValue Tmp1 = Op.getOperand(1);
3711   SDLoc dl(Op);
3712   EVT VT = Op.getValueType();
3713   EVT SrcVT = Tmp1.getValueType();
3714   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3715     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3716   bool UseNEON = !InGPR && Subtarget->hasNEON();
3717
3718   if (UseNEON) {
3719     // Use VBSL to copy the sign bit.
3720     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3721     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3722                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3723     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3724     if (VT == MVT::f64)
3725       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3726                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3727                          DAG.getConstant(32, MVT::i32));
3728     else /*if (VT == MVT::f32)*/
3729       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3730     if (SrcVT == MVT::f32) {
3731       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3732       if (VT == MVT::f64)
3733         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3734                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3735                            DAG.getConstant(32, MVT::i32));
3736     } else if (VT == MVT::f32)
3737       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3738                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3739                          DAG.getConstant(32, MVT::i32));
3740     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3741     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3742
3743     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3744                                             MVT::i32);
3745     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3746     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3747                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3748
3749     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3750                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3751                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3752     if (VT == MVT::f32) {
3753       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3754       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3755                         DAG.getConstant(0, MVT::i32));
3756     } else {
3757       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3758     }
3759
3760     return Res;
3761   }
3762
3763   // Bitcast operand 1 to i32.
3764   if (SrcVT == MVT::f64)
3765     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3766                        &Tmp1, 1).getValue(1);
3767   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3768
3769   // Or in the signbit with integer operations.
3770   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3771   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3772   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3773   if (VT == MVT::f32) {
3774     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3775                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3776     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3777                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3778   }
3779
3780   // f64: Or the high part with signbit and then combine two parts.
3781   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3782                      &Tmp0, 1);
3783   SDValue Lo = Tmp0.getValue(0);
3784   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3785   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3786   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3787 }
3788
3789 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3790   MachineFunction &MF = DAG.getMachineFunction();
3791   MachineFrameInfo *MFI = MF.getFrameInfo();
3792   MFI->setReturnAddressIsTaken(true);
3793
3794   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3795     return SDValue();
3796
3797   EVT VT = Op.getValueType();
3798   SDLoc dl(Op);
3799   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3800   if (Depth) {
3801     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3802     SDValue Offset = DAG.getConstant(4, MVT::i32);
3803     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3804                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3805                        MachinePointerInfo(), false, false, false, 0);
3806   }
3807
3808   // Return LR, which contains the return address. Mark it an implicit live-in.
3809   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3810   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3811 }
3812
3813 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3814   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3815   MFI->setFrameAddressIsTaken(true);
3816
3817   EVT VT = Op.getValueType();
3818   SDLoc dl(Op);  // FIXME probably not meaningful
3819   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3820   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3821     ? ARM::R7 : ARM::R11;
3822   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3823   while (Depth--)
3824     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3825                             MachinePointerInfo(),
3826                             false, false, false, 0);
3827   return FrameAddr;
3828 }
3829
3830 /// ExpandBITCAST - If the target supports VFP, this function is called to
3831 /// expand a bit convert where either the source or destination type is i64 to
3832 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3833 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3834 /// vectors), since the legalizer won't know what to do with that.
3835 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3836   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3837   SDLoc dl(N);
3838   SDValue Op = N->getOperand(0);
3839
3840   // This function is only supposed to be called for i64 types, either as the
3841   // source or destination of the bit convert.
3842   EVT SrcVT = Op.getValueType();
3843   EVT DstVT = N->getValueType(0);
3844   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3845          "ExpandBITCAST called for non-i64 type");
3846
3847   // Turn i64->f64 into VMOVDRR.
3848   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3849     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3850                              DAG.getConstant(0, MVT::i32));
3851     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3852                              DAG.getConstant(1, MVT::i32));
3853     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3854                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3855   }
3856
3857   // Turn f64->i64 into VMOVRRD.
3858   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3859     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3860                               DAG.getVTList(MVT::i32, MVT::i32), &Op, 1);
3861     // Merge the pieces into a single i64 value.
3862     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3863   }
3864
3865   return SDValue();
3866 }
3867
3868 /// getZeroVector - Returns a vector of specified type with all zero elements.
3869 /// Zero vectors are used to represent vector negation and in those cases
3870 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3871 /// not support i64 elements, so sometimes the zero vectors will need to be
3872 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3873 /// zero vector.
3874 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3875   assert(VT.isVector() && "Expected a vector type");
3876   // The canonical modified immediate encoding of a zero vector is....0!
3877   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3878   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3879   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3880   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3881 }
3882
3883 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3884 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3885 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3886                                                 SelectionDAG &DAG) const {
3887   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3888   EVT VT = Op.getValueType();
3889   unsigned VTBits = VT.getSizeInBits();
3890   SDLoc dl(Op);
3891   SDValue ShOpLo = Op.getOperand(0);
3892   SDValue ShOpHi = Op.getOperand(1);
3893   SDValue ShAmt  = Op.getOperand(2);
3894   SDValue ARMcc;
3895   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3896
3897   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3898
3899   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3900                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3901   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3902   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3903                                    DAG.getConstant(VTBits, MVT::i32));
3904   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3905   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3906   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3907
3908   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3909   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3910                           ARMcc, DAG, dl);
3911   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3912   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3913                            CCR, Cmp);
3914
3915   SDValue Ops[2] = { Lo, Hi };
3916   return DAG.getMergeValues(Ops, 2, dl);
3917 }
3918
3919 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3920 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3921 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3922                                                SelectionDAG &DAG) const {
3923   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3924   EVT VT = Op.getValueType();
3925   unsigned VTBits = VT.getSizeInBits();
3926   SDLoc dl(Op);
3927   SDValue ShOpLo = Op.getOperand(0);
3928   SDValue ShOpHi = Op.getOperand(1);
3929   SDValue ShAmt  = Op.getOperand(2);
3930   SDValue ARMcc;
3931
3932   assert(Op.getOpcode() == ISD::SHL_PARTS);
3933   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3934                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3935   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3936   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3937                                    DAG.getConstant(VTBits, MVT::i32));
3938   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3939   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3940
3941   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3942   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3943   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3944                           ARMcc, DAG, dl);
3945   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3946   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3947                            CCR, Cmp);
3948
3949   SDValue Ops[2] = { Lo, Hi };
3950   return DAG.getMergeValues(Ops, 2, dl);
3951 }
3952
3953 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3954                                             SelectionDAG &DAG) const {
3955   // The rounding mode is in bits 23:22 of the FPSCR.
3956   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3957   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3958   // so that the shift + and get folded into a bitfield extract.
3959   SDLoc dl(Op);
3960   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3961                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3962                                               MVT::i32));
3963   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3964                                   DAG.getConstant(1U << 22, MVT::i32));
3965   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3966                               DAG.getConstant(22, MVT::i32));
3967   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3968                      DAG.getConstant(3, MVT::i32));
3969 }
3970
3971 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3972                          const ARMSubtarget *ST) {
3973   EVT VT = N->getValueType(0);
3974   SDLoc dl(N);
3975
3976   if (!ST->hasV6T2Ops())
3977     return SDValue();
3978
3979   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3980   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3981 }
3982
3983 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3984 /// for each 16-bit element from operand, repeated.  The basic idea is to
3985 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3986 ///
3987 /// Trace for v4i16:
3988 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3989 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3990 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3991 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3992 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3993 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3994 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3995 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3996 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3997   EVT VT = N->getValueType(0);
3998   SDLoc DL(N);
3999
4000   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4001   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4002   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4003   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4004   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4005   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4006 }
4007
4008 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4009 /// bit-count for each 16-bit element from the operand.  We need slightly
4010 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4011 /// 64/128-bit registers.
4012 ///
4013 /// Trace for v4i16:
4014 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4015 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4016 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4017 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4018 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4019   EVT VT = N->getValueType(0);
4020   SDLoc DL(N);
4021
4022   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4023   if (VT.is64BitVector()) {
4024     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4025     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4026                        DAG.getIntPtrConstant(0));
4027   } else {
4028     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4029                                     BitCounts, DAG.getIntPtrConstant(0));
4030     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4031   }
4032 }
4033
4034 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4035 /// bit-count for each 32-bit element from the operand.  The idea here is
4036 /// to split the vector into 16-bit elements, leverage the 16-bit count
4037 /// routine, and then combine the results.
4038 ///
4039 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4040 /// input    = [v0    v1    ] (vi: 32-bit elements)
4041 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4042 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4043 /// vrev: N0 = [k1 k0 k3 k2 ]
4044 ///            [k0 k1 k2 k3 ]
4045 ///       N1 =+[k1 k0 k3 k2 ]
4046 ///            [k0 k2 k1 k3 ]
4047 ///       N2 =+[k1 k3 k0 k2 ]
4048 ///            [k0    k2    k1    k3    ]
4049 /// Extended =+[k1    k3    k0    k2    ]
4050 ///            [k0    k2    ]
4051 /// Extracted=+[k1    k3    ]
4052 ///
4053 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4054   EVT VT = N->getValueType(0);
4055   SDLoc DL(N);
4056
4057   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4058
4059   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4060   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4061   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4062   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4063   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4064
4065   if (VT.is64BitVector()) {
4066     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4067     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4068                        DAG.getIntPtrConstant(0));
4069   } else {
4070     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4071                                     DAG.getIntPtrConstant(0));
4072     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4073   }
4074 }
4075
4076 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4077                           const ARMSubtarget *ST) {
4078   EVT VT = N->getValueType(0);
4079
4080   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4081   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4082           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4083          "Unexpected type for custom ctpop lowering");
4084
4085   if (VT.getVectorElementType() == MVT::i32)
4086     return lowerCTPOP32BitElements(N, DAG);
4087   else
4088     return lowerCTPOP16BitElements(N, DAG);
4089 }
4090
4091 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4092                           const ARMSubtarget *ST) {
4093   EVT VT = N->getValueType(0);
4094   SDLoc dl(N);
4095
4096   if (!VT.isVector())
4097     return SDValue();
4098
4099   // Lower vector shifts on NEON to use VSHL.
4100   assert(ST->hasNEON() && "unexpected vector shift");
4101
4102   // Left shifts translate directly to the vshiftu intrinsic.
4103   if (N->getOpcode() == ISD::SHL)
4104     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4105                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4106                        N->getOperand(0), N->getOperand(1));
4107
4108   assert((N->getOpcode() == ISD::SRA ||
4109           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4110
4111   // NEON uses the same intrinsics for both left and right shifts.  For
4112   // right shifts, the shift amounts are negative, so negate the vector of
4113   // shift amounts.
4114   EVT ShiftVT = N->getOperand(1).getValueType();
4115   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4116                                      getZeroVector(ShiftVT, DAG, dl),
4117                                      N->getOperand(1));
4118   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4119                              Intrinsic::arm_neon_vshifts :
4120                              Intrinsic::arm_neon_vshiftu);
4121   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4122                      DAG.getConstant(vshiftInt, MVT::i32),
4123                      N->getOperand(0), NegatedCount);
4124 }
4125
4126 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4127                                 const ARMSubtarget *ST) {
4128   EVT VT = N->getValueType(0);
4129   SDLoc dl(N);
4130
4131   // We can get here for a node like i32 = ISD::SHL i32, i64
4132   if (VT != MVT::i64)
4133     return SDValue();
4134
4135   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4136          "Unknown shift to lower!");
4137
4138   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4139   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4140       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4141     return SDValue();
4142
4143   // If we are in thumb mode, we don't have RRX.
4144   if (ST->isThumb1Only()) return SDValue();
4145
4146   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4147   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4148                            DAG.getConstant(0, MVT::i32));
4149   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4150                            DAG.getConstant(1, MVT::i32));
4151
4152   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4153   // captures the result into a carry flag.
4154   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4155   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), &Hi, 1);
4156
4157   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4158   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4159
4160   // Merge the pieces into a single i64 value.
4161  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4162 }
4163
4164 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4165   SDValue TmpOp0, TmpOp1;
4166   bool Invert = false;
4167   bool Swap = false;
4168   unsigned Opc = 0;
4169
4170   SDValue Op0 = Op.getOperand(0);
4171   SDValue Op1 = Op.getOperand(1);
4172   SDValue CC = Op.getOperand(2);
4173   EVT VT = Op.getValueType();
4174   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4175   SDLoc dl(Op);
4176
4177   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4178     switch (SetCCOpcode) {
4179     default: llvm_unreachable("Illegal FP comparison");
4180     case ISD::SETUNE:
4181     case ISD::SETNE:  Invert = true; // Fallthrough
4182     case ISD::SETOEQ:
4183     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4184     case ISD::SETOLT:
4185     case ISD::SETLT: Swap = true; // Fallthrough
4186     case ISD::SETOGT:
4187     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4188     case ISD::SETOLE:
4189     case ISD::SETLE:  Swap = true; // Fallthrough
4190     case ISD::SETOGE:
4191     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4192     case ISD::SETUGE: Swap = true; // Fallthrough
4193     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4194     case ISD::SETUGT: Swap = true; // Fallthrough
4195     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4196     case ISD::SETUEQ: Invert = true; // Fallthrough
4197     case ISD::SETONE:
4198       // Expand this to (OLT | OGT).
4199       TmpOp0 = Op0;
4200       TmpOp1 = Op1;
4201       Opc = ISD::OR;
4202       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4203       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4204       break;
4205     case ISD::SETUO: Invert = true; // Fallthrough
4206     case ISD::SETO:
4207       // Expand this to (OLT | OGE).
4208       TmpOp0 = Op0;
4209       TmpOp1 = Op1;
4210       Opc = ISD::OR;
4211       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4212       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4213       break;
4214     }
4215   } else {
4216     // Integer comparisons.
4217     switch (SetCCOpcode) {
4218     default: llvm_unreachable("Illegal integer comparison");
4219     case ISD::SETNE:  Invert = true;
4220     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4221     case ISD::SETLT:  Swap = true;
4222     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4223     case ISD::SETLE:  Swap = true;
4224     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4225     case ISD::SETULT: Swap = true;
4226     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4227     case ISD::SETULE: Swap = true;
4228     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4229     }
4230
4231     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4232     if (Opc == ARMISD::VCEQ) {
4233
4234       SDValue AndOp;
4235       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4236         AndOp = Op0;
4237       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4238         AndOp = Op1;
4239
4240       // Ignore bitconvert.
4241       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4242         AndOp = AndOp.getOperand(0);
4243
4244       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4245         Opc = ARMISD::VTST;
4246         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4247         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4248         Invert = !Invert;
4249       }
4250     }
4251   }
4252
4253   if (Swap)
4254     std::swap(Op0, Op1);
4255
4256   // If one of the operands is a constant vector zero, attempt to fold the
4257   // comparison to a specialized compare-against-zero form.
4258   SDValue SingleOp;
4259   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4260     SingleOp = Op0;
4261   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4262     if (Opc == ARMISD::VCGE)
4263       Opc = ARMISD::VCLEZ;
4264     else if (Opc == ARMISD::VCGT)
4265       Opc = ARMISD::VCLTZ;
4266     SingleOp = Op1;
4267   }
4268
4269   SDValue Result;
4270   if (SingleOp.getNode()) {
4271     switch (Opc) {
4272     case ARMISD::VCEQ:
4273       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4274     case ARMISD::VCGE:
4275       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4276     case ARMISD::VCLEZ:
4277       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4278     case ARMISD::VCGT:
4279       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4280     case ARMISD::VCLTZ:
4281       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4282     default:
4283       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4284     }
4285   } else {
4286      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4287   }
4288
4289   if (Invert)
4290     Result = DAG.getNOT(dl, Result, VT);
4291
4292   return Result;
4293 }
4294
4295 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4296 /// valid vector constant for a NEON instruction with a "modified immediate"
4297 /// operand (e.g., VMOV).  If so, return the encoded value.
4298 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4299                                  unsigned SplatBitSize, SelectionDAG &DAG,
4300                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4301   unsigned OpCmode, Imm;
4302
4303   // SplatBitSize is set to the smallest size that splats the vector, so a
4304   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4305   // immediate instructions others than VMOV do not support the 8-bit encoding
4306   // of a zero vector, and the default encoding of zero is supposed to be the
4307   // 32-bit version.
4308   if (SplatBits == 0)
4309     SplatBitSize = 32;
4310
4311   switch (SplatBitSize) {
4312   case 8:
4313     if (type != VMOVModImm)
4314       return SDValue();
4315     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4316     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4317     OpCmode = 0xe;
4318     Imm = SplatBits;
4319     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4320     break;
4321
4322   case 16:
4323     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4324     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4325     if ((SplatBits & ~0xff) == 0) {
4326       // Value = 0x00nn: Op=x, Cmode=100x.
4327       OpCmode = 0x8;
4328       Imm = SplatBits;
4329       break;
4330     }
4331     if ((SplatBits & ~0xff00) == 0) {
4332       // Value = 0xnn00: Op=x, Cmode=101x.
4333       OpCmode = 0xa;
4334       Imm = SplatBits >> 8;
4335       break;
4336     }
4337     return SDValue();
4338
4339   case 32:
4340     // NEON's 32-bit VMOV supports splat values where:
4341     // * only one byte is nonzero, or
4342     // * the least significant byte is 0xff and the second byte is nonzero, or
4343     // * the least significant 2 bytes are 0xff and the third is nonzero.
4344     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4345     if ((SplatBits & ~0xff) == 0) {
4346       // Value = 0x000000nn: Op=x, Cmode=000x.
4347       OpCmode = 0;
4348       Imm = SplatBits;
4349       break;
4350     }
4351     if ((SplatBits & ~0xff00) == 0) {
4352       // Value = 0x0000nn00: Op=x, Cmode=001x.
4353       OpCmode = 0x2;
4354       Imm = SplatBits >> 8;
4355       break;
4356     }
4357     if ((SplatBits & ~0xff0000) == 0) {
4358       // Value = 0x00nn0000: Op=x, Cmode=010x.
4359       OpCmode = 0x4;
4360       Imm = SplatBits >> 16;
4361       break;
4362     }
4363     if ((SplatBits & ~0xff000000) == 0) {
4364       // Value = 0xnn000000: Op=x, Cmode=011x.
4365       OpCmode = 0x6;
4366       Imm = SplatBits >> 24;
4367       break;
4368     }
4369
4370     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4371     if (type == OtherModImm) return SDValue();
4372
4373     if ((SplatBits & ~0xffff) == 0 &&
4374         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4375       // Value = 0x0000nnff: Op=x, Cmode=1100.
4376       OpCmode = 0xc;
4377       Imm = SplatBits >> 8;
4378       break;
4379     }
4380
4381     if ((SplatBits & ~0xffffff) == 0 &&
4382         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4383       // Value = 0x00nnffff: Op=x, Cmode=1101.
4384       OpCmode = 0xd;
4385       Imm = SplatBits >> 16;
4386       break;
4387     }
4388
4389     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4390     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4391     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4392     // and fall through here to test for a valid 64-bit splat.  But, then the
4393     // caller would also need to check and handle the change in size.
4394     return SDValue();
4395
4396   case 64: {
4397     if (type != VMOVModImm)
4398       return SDValue();
4399     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4400     uint64_t BitMask = 0xff;
4401     uint64_t Val = 0;
4402     unsigned ImmMask = 1;
4403     Imm = 0;
4404     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4405       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4406         Val |= BitMask;
4407         Imm |= ImmMask;
4408       } else if ((SplatBits & BitMask) != 0) {
4409         return SDValue();
4410       }
4411       BitMask <<= 8;
4412       ImmMask <<= 1;
4413     }
4414     // Op=1, Cmode=1110.
4415     OpCmode = 0x1e;
4416     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4417     break;
4418   }
4419
4420   default:
4421     llvm_unreachable("unexpected size for isNEONModifiedImm");
4422   }
4423
4424   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4425   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4426 }
4427
4428 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4429                                            const ARMSubtarget *ST) const {
4430   if (!ST->hasVFP3())
4431     return SDValue();
4432
4433   bool IsDouble = Op.getValueType() == MVT::f64;
4434   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4435
4436   // Try splatting with a VMOV.f32...
4437   APFloat FPVal = CFP->getValueAPF();
4438   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4439
4440   if (ImmVal != -1) {
4441     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4442       // We have code in place to select a valid ConstantFP already, no need to
4443       // do any mangling.
4444       return Op;
4445     }
4446
4447     // It's a float and we are trying to use NEON operations where
4448     // possible. Lower it to a splat followed by an extract.
4449     SDLoc DL(Op);
4450     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4451     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4452                                       NewVal);
4453     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4454                        DAG.getConstant(0, MVT::i32));
4455   }
4456
4457   // The rest of our options are NEON only, make sure that's allowed before
4458   // proceeding..
4459   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4460     return SDValue();
4461
4462   EVT VMovVT;
4463   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4464
4465   // It wouldn't really be worth bothering for doubles except for one very
4466   // important value, which does happen to match: 0.0. So make sure we don't do
4467   // anything stupid.
4468   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4469     return SDValue();
4470
4471   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4472   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4473                                      false, VMOVModImm);
4474   if (NewVal != SDValue()) {
4475     SDLoc DL(Op);
4476     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4477                                       NewVal);
4478     if (IsDouble)
4479       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4480
4481     // It's a float: cast and extract a vector element.
4482     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4483                                        VecConstant);
4484     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4485                        DAG.getConstant(0, MVT::i32));
4486   }
4487
4488   // Finally, try a VMVN.i32
4489   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4490                              false, VMVNModImm);
4491   if (NewVal != SDValue()) {
4492     SDLoc DL(Op);
4493     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4494
4495     if (IsDouble)
4496       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4497
4498     // It's a float: cast and extract a vector element.
4499     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4500                                        VecConstant);
4501     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4502                        DAG.getConstant(0, MVT::i32));
4503   }
4504
4505   return SDValue();
4506 }
4507
4508 // check if an VEXT instruction can handle the shuffle mask when the
4509 // vector sources of the shuffle are the same.
4510 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4511   unsigned NumElts = VT.getVectorNumElements();
4512
4513   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4514   if (M[0] < 0)
4515     return false;
4516
4517   Imm = M[0];
4518
4519   // If this is a VEXT shuffle, the immediate value is the index of the first
4520   // element.  The other shuffle indices must be the successive elements after
4521   // the first one.
4522   unsigned ExpectedElt = Imm;
4523   for (unsigned i = 1; i < NumElts; ++i) {
4524     // Increment the expected index.  If it wraps around, just follow it
4525     // back to index zero and keep going.
4526     ++ExpectedElt;
4527     if (ExpectedElt == NumElts)
4528       ExpectedElt = 0;
4529
4530     if (M[i] < 0) continue; // ignore UNDEF indices
4531     if (ExpectedElt != static_cast<unsigned>(M[i]))
4532       return false;
4533   }
4534
4535   return true;
4536 }
4537
4538
4539 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4540                        bool &ReverseVEXT, unsigned &Imm) {
4541   unsigned NumElts = VT.getVectorNumElements();
4542   ReverseVEXT = false;
4543
4544   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4545   if (M[0] < 0)
4546     return false;
4547
4548   Imm = M[0];
4549
4550   // If this is a VEXT shuffle, the immediate value is the index of the first
4551   // element.  The other shuffle indices must be the successive elements after
4552   // the first one.
4553   unsigned ExpectedElt = Imm;
4554   for (unsigned i = 1; i < NumElts; ++i) {
4555     // Increment the expected index.  If it wraps around, it may still be
4556     // a VEXT but the source vectors must be swapped.
4557     ExpectedElt += 1;
4558     if (ExpectedElt == NumElts * 2) {
4559       ExpectedElt = 0;
4560       ReverseVEXT = true;
4561     }
4562
4563     if (M[i] < 0) continue; // ignore UNDEF indices
4564     if (ExpectedElt != static_cast<unsigned>(M[i]))
4565       return false;
4566   }
4567
4568   // Adjust the index value if the source operands will be swapped.
4569   if (ReverseVEXT)
4570     Imm -= NumElts;
4571
4572   return true;
4573 }
4574
4575 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4576 /// instruction with the specified blocksize.  (The order of the elements
4577 /// within each block of the vector is reversed.)
4578 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4579   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4580          "Only possible block sizes for VREV are: 16, 32, 64");
4581
4582   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4583   if (EltSz == 64)
4584     return false;
4585
4586   unsigned NumElts = VT.getVectorNumElements();
4587   unsigned BlockElts = M[0] + 1;
4588   // If the first shuffle index is UNDEF, be optimistic.
4589   if (M[0] < 0)
4590     BlockElts = BlockSize / EltSz;
4591
4592   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4593     return false;
4594
4595   for (unsigned i = 0; i < NumElts; ++i) {
4596     if (M[i] < 0) continue; // ignore UNDEF indices
4597     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4598       return false;
4599   }
4600
4601   return true;
4602 }
4603
4604 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4605   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4606   // range, then 0 is placed into the resulting vector. So pretty much any mask
4607   // of 8 elements can work here.
4608   return VT == MVT::v8i8 && M.size() == 8;
4609 }
4610
4611 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4612   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4613   if (EltSz == 64)
4614     return false;
4615
4616   unsigned NumElts = VT.getVectorNumElements();
4617   WhichResult = (M[0] == 0 ? 0 : 1);
4618   for (unsigned i = 0; i < NumElts; i += 2) {
4619     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4620         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4621       return false;
4622   }
4623   return true;
4624 }
4625
4626 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4627 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4628 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4629 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4630   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4631   if (EltSz == 64)
4632     return false;
4633
4634   unsigned NumElts = VT.getVectorNumElements();
4635   WhichResult = (M[0] == 0 ? 0 : 1);
4636   for (unsigned i = 0; i < NumElts; i += 2) {
4637     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4638         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4639       return false;
4640   }
4641   return true;
4642 }
4643
4644 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4645   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4646   if (EltSz == 64)
4647     return false;
4648
4649   unsigned NumElts = VT.getVectorNumElements();
4650   WhichResult = (M[0] == 0 ? 0 : 1);
4651   for (unsigned i = 0; i != NumElts; ++i) {
4652     if (M[i] < 0) continue; // ignore UNDEF indices
4653     if ((unsigned) M[i] != 2 * i + WhichResult)
4654       return false;
4655   }
4656
4657   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4658   if (VT.is64BitVector() && EltSz == 32)
4659     return false;
4660
4661   return true;
4662 }
4663
4664 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4665 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4666 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4667 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4668   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4669   if (EltSz == 64)
4670     return false;
4671
4672   unsigned Half = VT.getVectorNumElements() / 2;
4673   WhichResult = (M[0] == 0 ? 0 : 1);
4674   for (unsigned j = 0; j != 2; ++j) {
4675     unsigned Idx = WhichResult;
4676     for (unsigned i = 0; i != Half; ++i) {
4677       int MIdx = M[i + j * Half];
4678       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4679         return false;
4680       Idx += 2;
4681     }
4682   }
4683
4684   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4685   if (VT.is64BitVector() && EltSz == 32)
4686     return false;
4687
4688   return true;
4689 }
4690
4691 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4692   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4693   if (EltSz == 64)
4694     return false;
4695
4696   unsigned NumElts = VT.getVectorNumElements();
4697   WhichResult = (M[0] == 0 ? 0 : 1);
4698   unsigned Idx = WhichResult * NumElts / 2;
4699   for (unsigned i = 0; i != NumElts; i += 2) {
4700     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4701         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4702       return false;
4703     Idx += 1;
4704   }
4705
4706   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4707   if (VT.is64BitVector() && EltSz == 32)
4708     return false;
4709
4710   return true;
4711 }
4712
4713 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4714 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4715 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4716 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4717   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4718   if (EltSz == 64)
4719     return false;
4720
4721   unsigned NumElts = VT.getVectorNumElements();
4722   WhichResult = (M[0] == 0 ? 0 : 1);
4723   unsigned Idx = WhichResult * NumElts / 2;
4724   for (unsigned i = 0; i != NumElts; i += 2) {
4725     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4726         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4727       return false;
4728     Idx += 1;
4729   }
4730
4731   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4732   if (VT.is64BitVector() && EltSz == 32)
4733     return false;
4734
4735   return true;
4736 }
4737
4738 /// \return true if this is a reverse operation on an vector.
4739 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4740   unsigned NumElts = VT.getVectorNumElements();
4741   // Make sure the mask has the right size.
4742   if (NumElts != M.size())
4743       return false;
4744
4745   // Look for <15, ..., 3, -1, 1, 0>.
4746   for (unsigned i = 0; i != NumElts; ++i)
4747     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4748       return false;
4749
4750   return true;
4751 }
4752
4753 // If N is an integer constant that can be moved into a register in one
4754 // instruction, return an SDValue of such a constant (will become a MOV
4755 // instruction).  Otherwise return null.
4756 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4757                                      const ARMSubtarget *ST, SDLoc dl) {
4758   uint64_t Val;
4759   if (!isa<ConstantSDNode>(N))
4760     return SDValue();
4761   Val = cast<ConstantSDNode>(N)->getZExtValue();
4762
4763   if (ST->isThumb1Only()) {
4764     if (Val <= 255 || ~Val <= 255)
4765       return DAG.getConstant(Val, MVT::i32);
4766   } else {
4767     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4768       return DAG.getConstant(Val, MVT::i32);
4769   }
4770   return SDValue();
4771 }
4772
4773 // If this is a case we can't handle, return null and let the default
4774 // expansion code take care of it.
4775 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4776                                              const ARMSubtarget *ST) const {
4777   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4778   SDLoc dl(Op);
4779   EVT VT = Op.getValueType();
4780
4781   APInt SplatBits, SplatUndef;
4782   unsigned SplatBitSize;
4783   bool HasAnyUndefs;
4784   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4785     if (SplatBitSize <= 64) {
4786       // Check if an immediate VMOV works.
4787       EVT VmovVT;
4788       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4789                                       SplatUndef.getZExtValue(), SplatBitSize,
4790                                       DAG, VmovVT, VT.is128BitVector(),
4791                                       VMOVModImm);
4792       if (Val.getNode()) {
4793         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4794         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4795       }
4796
4797       // Try an immediate VMVN.
4798       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4799       Val = isNEONModifiedImm(NegatedImm,
4800                                       SplatUndef.getZExtValue(), SplatBitSize,
4801                                       DAG, VmovVT, VT.is128BitVector(),
4802                                       VMVNModImm);
4803       if (Val.getNode()) {
4804         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4805         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4806       }
4807
4808       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4809       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4810         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4811         if (ImmVal != -1) {
4812           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4813           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4814         }
4815       }
4816     }
4817   }
4818
4819   // Scan through the operands to see if only one value is used.
4820   //
4821   // As an optimisation, even if more than one value is used it may be more
4822   // profitable to splat with one value then change some lanes.
4823   //
4824   // Heuristically we decide to do this if the vector has a "dominant" value,
4825   // defined as splatted to more than half of the lanes.
4826   unsigned NumElts = VT.getVectorNumElements();
4827   bool isOnlyLowElement = true;
4828   bool usesOnlyOneValue = true;
4829   bool hasDominantValue = false;
4830   bool isConstant = true;
4831
4832   // Map of the number of times a particular SDValue appears in the
4833   // element list.
4834   DenseMap<SDValue, unsigned> ValueCounts;
4835   SDValue Value;
4836   for (unsigned i = 0; i < NumElts; ++i) {
4837     SDValue V = Op.getOperand(i);
4838     if (V.getOpcode() == ISD::UNDEF)
4839       continue;
4840     if (i > 0)
4841       isOnlyLowElement = false;
4842     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4843       isConstant = false;
4844
4845     ValueCounts.insert(std::make_pair(V, 0));
4846     unsigned &Count = ValueCounts[V];
4847
4848     // Is this value dominant? (takes up more than half of the lanes)
4849     if (++Count > (NumElts / 2)) {
4850       hasDominantValue = true;
4851       Value = V;
4852     }
4853   }
4854   if (ValueCounts.size() != 1)
4855     usesOnlyOneValue = false;
4856   if (!Value.getNode() && ValueCounts.size() > 0)
4857     Value = ValueCounts.begin()->first;
4858
4859   if (ValueCounts.size() == 0)
4860     return DAG.getUNDEF(VT);
4861
4862   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4863   // Keep going if we are hitting this case.
4864   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4865     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4866
4867   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4868
4869   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4870   // i32 and try again.
4871   if (hasDominantValue && EltSize <= 32) {
4872     if (!isConstant) {
4873       SDValue N;
4874
4875       // If we are VDUPing a value that comes directly from a vector, that will
4876       // cause an unnecessary move to and from a GPR, where instead we could
4877       // just use VDUPLANE. We can only do this if the lane being extracted
4878       // is at a constant index, as the VDUP from lane instructions only have
4879       // constant-index forms.
4880       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4881           isa<ConstantSDNode>(Value->getOperand(1))) {
4882         // We need to create a new undef vector to use for the VDUPLANE if the
4883         // size of the vector from which we get the value is different than the
4884         // size of the vector that we need to create. We will insert the element
4885         // such that the register coalescer will remove unnecessary copies.
4886         if (VT != Value->getOperand(0).getValueType()) {
4887           ConstantSDNode *constIndex;
4888           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4889           assert(constIndex && "The index is not a constant!");
4890           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4891                              VT.getVectorNumElements();
4892           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4893                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4894                         Value, DAG.getConstant(index, MVT::i32)),
4895                            DAG.getConstant(index, MVT::i32));
4896         } else
4897           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4898                         Value->getOperand(0), Value->getOperand(1));
4899       } else
4900         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4901
4902       if (!usesOnlyOneValue) {
4903         // The dominant value was splatted as 'N', but we now have to insert
4904         // all differing elements.
4905         for (unsigned I = 0; I < NumElts; ++I) {
4906           if (Op.getOperand(I) == Value)
4907             continue;
4908           SmallVector<SDValue, 3> Ops;
4909           Ops.push_back(N);
4910           Ops.push_back(Op.getOperand(I));
4911           Ops.push_back(DAG.getConstant(I, MVT::i32));
4912           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, &Ops[0], 3);
4913         }
4914       }
4915       return N;
4916     }
4917     if (VT.getVectorElementType().isFloatingPoint()) {
4918       SmallVector<SDValue, 8> Ops;
4919       for (unsigned i = 0; i < NumElts; ++i)
4920         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4921                                   Op.getOperand(i)));
4922       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4923       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
4924       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4925       if (Val.getNode())
4926         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4927     }
4928     if (usesOnlyOneValue) {
4929       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4930       if (isConstant && Val.getNode())
4931         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4932     }
4933   }
4934
4935   // If all elements are constants and the case above didn't get hit, fall back
4936   // to the default expansion, which will generate a load from the constant
4937   // pool.
4938   if (isConstant)
4939     return SDValue();
4940
4941   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4942   if (NumElts >= 4) {
4943     SDValue shuffle = ReconstructShuffle(Op, DAG);
4944     if (shuffle != SDValue())
4945       return shuffle;
4946   }
4947
4948   // Vectors with 32- or 64-bit elements can be built by directly assigning
4949   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4950   // will be legalized.
4951   if (EltSize >= 32) {
4952     // Do the expansion with floating-point types, since that is what the VFP
4953     // registers are defined to use, and since i64 is not legal.
4954     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4955     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4956     SmallVector<SDValue, 8> Ops;
4957     for (unsigned i = 0; i < NumElts; ++i)
4958       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4959     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
4960     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4961   }
4962
4963   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4964   // know the default expansion would otherwise fall back on something even
4965   // worse. For a vector with one or two non-undef values, that's
4966   // scalar_to_vector for the elements followed by a shuffle (provided the
4967   // shuffle is valid for the target) and materialization element by element
4968   // on the stack followed by a load for everything else.
4969   if (!isConstant && !usesOnlyOneValue) {
4970     SDValue Vec = DAG.getUNDEF(VT);
4971     for (unsigned i = 0 ; i < NumElts; ++i) {
4972       SDValue V = Op.getOperand(i);
4973       if (V.getOpcode() == ISD::UNDEF)
4974         continue;
4975       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4976       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4977     }
4978     return Vec;
4979   }
4980
4981   return SDValue();
4982 }
4983
4984 // Gather data to see if the operation can be modelled as a
4985 // shuffle in combination with VEXTs.
4986 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4987                                               SelectionDAG &DAG) const {
4988   SDLoc dl(Op);
4989   EVT VT = Op.getValueType();
4990   unsigned NumElts = VT.getVectorNumElements();
4991
4992   SmallVector<SDValue, 2> SourceVecs;
4993   SmallVector<unsigned, 2> MinElts;
4994   SmallVector<unsigned, 2> MaxElts;
4995
4996   for (unsigned i = 0; i < NumElts; ++i) {
4997     SDValue V = Op.getOperand(i);
4998     if (V.getOpcode() == ISD::UNDEF)
4999       continue;
5000     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5001       // A shuffle can only come from building a vector from various
5002       // elements of other vectors.
5003       return SDValue();
5004     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5005                VT.getVectorElementType()) {
5006       // This code doesn't know how to handle shuffles where the vector
5007       // element types do not match (this happens because type legalization
5008       // promotes the return type of EXTRACT_VECTOR_ELT).
5009       // FIXME: It might be appropriate to extend this code to handle
5010       // mismatched types.
5011       return SDValue();
5012     }
5013
5014     // Record this extraction against the appropriate vector if possible...
5015     SDValue SourceVec = V.getOperand(0);
5016     // If the element number isn't a constant, we can't effectively
5017     // analyze what's going on.
5018     if (!isa<ConstantSDNode>(V.getOperand(1)))
5019       return SDValue();
5020     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5021     bool FoundSource = false;
5022     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5023       if (SourceVecs[j] == SourceVec) {
5024         if (MinElts[j] > EltNo)
5025           MinElts[j] = EltNo;
5026         if (MaxElts[j] < EltNo)
5027           MaxElts[j] = EltNo;
5028         FoundSource = true;
5029         break;
5030       }
5031     }
5032
5033     // Or record a new source if not...
5034     if (!FoundSource) {
5035       SourceVecs.push_back(SourceVec);
5036       MinElts.push_back(EltNo);
5037       MaxElts.push_back(EltNo);
5038     }
5039   }
5040
5041   // Currently only do something sane when at most two source vectors
5042   // involved.
5043   if (SourceVecs.size() > 2)
5044     return SDValue();
5045
5046   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5047   int VEXTOffsets[2] = {0, 0};
5048
5049   // This loop extracts the usage patterns of the source vectors
5050   // and prepares appropriate SDValues for a shuffle if possible.
5051   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5052     if (SourceVecs[i].getValueType() == VT) {
5053       // No VEXT necessary
5054       ShuffleSrcs[i] = SourceVecs[i];
5055       VEXTOffsets[i] = 0;
5056       continue;
5057     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5058       // It probably isn't worth padding out a smaller vector just to
5059       // break it down again in a shuffle.
5060       return SDValue();
5061     }
5062
5063     // Since only 64-bit and 128-bit vectors are legal on ARM and
5064     // we've eliminated the other cases...
5065     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5066            "unexpected vector sizes in ReconstructShuffle");
5067
5068     if (MaxElts[i] - MinElts[i] >= NumElts) {
5069       // Span too large for a VEXT to cope
5070       return SDValue();
5071     }
5072
5073     if (MinElts[i] >= NumElts) {
5074       // The extraction can just take the second half
5075       VEXTOffsets[i] = NumElts;
5076       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5077                                    SourceVecs[i],
5078                                    DAG.getIntPtrConstant(NumElts));
5079     } else if (MaxElts[i] < NumElts) {
5080       // The extraction can just take the first half
5081       VEXTOffsets[i] = 0;
5082       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5083                                    SourceVecs[i],
5084                                    DAG.getIntPtrConstant(0));
5085     } else {
5086       // An actual VEXT is needed
5087       VEXTOffsets[i] = MinElts[i];
5088       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5089                                      SourceVecs[i],
5090                                      DAG.getIntPtrConstant(0));
5091       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5092                                      SourceVecs[i],
5093                                      DAG.getIntPtrConstant(NumElts));
5094       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5095                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5096     }
5097   }
5098
5099   SmallVector<int, 8> Mask;
5100
5101   for (unsigned i = 0; i < NumElts; ++i) {
5102     SDValue Entry = Op.getOperand(i);
5103     if (Entry.getOpcode() == ISD::UNDEF) {
5104       Mask.push_back(-1);
5105       continue;
5106     }
5107
5108     SDValue ExtractVec = Entry.getOperand(0);
5109     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5110                                           .getOperand(1))->getSExtValue();
5111     if (ExtractVec == SourceVecs[0]) {
5112       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5113     } else {
5114       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5115     }
5116   }
5117
5118   // Final check before we try to produce nonsense...
5119   if (isShuffleMaskLegal(Mask, VT))
5120     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5121                                 &Mask[0]);
5122
5123   return SDValue();
5124 }
5125
5126 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5127 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5128 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5129 /// are assumed to be legal.
5130 bool
5131 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5132                                       EVT VT) const {
5133   if (VT.getVectorNumElements() == 4 &&
5134       (VT.is128BitVector() || VT.is64BitVector())) {
5135     unsigned PFIndexes[4];
5136     for (unsigned i = 0; i != 4; ++i) {
5137       if (M[i] < 0)
5138         PFIndexes[i] = 8;
5139       else
5140         PFIndexes[i] = M[i];
5141     }
5142
5143     // Compute the index in the perfect shuffle table.
5144     unsigned PFTableIndex =
5145       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5146     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5147     unsigned Cost = (PFEntry >> 30);
5148
5149     if (Cost <= 4)
5150       return true;
5151   }
5152
5153   bool ReverseVEXT;
5154   unsigned Imm, WhichResult;
5155
5156   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5157   return (EltSize >= 32 ||
5158           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5159           isVREVMask(M, VT, 64) ||
5160           isVREVMask(M, VT, 32) ||
5161           isVREVMask(M, VT, 16) ||
5162           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5163           isVTBLMask(M, VT) ||
5164           isVTRNMask(M, VT, WhichResult) ||
5165           isVUZPMask(M, VT, WhichResult) ||
5166           isVZIPMask(M, VT, WhichResult) ||
5167           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5168           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5169           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5170           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5171 }
5172
5173 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5174 /// the specified operations to build the shuffle.
5175 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5176                                       SDValue RHS, SelectionDAG &DAG,
5177                                       SDLoc dl) {
5178   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5179   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5180   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5181
5182   enum {
5183     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5184     OP_VREV,
5185     OP_VDUP0,
5186     OP_VDUP1,
5187     OP_VDUP2,
5188     OP_VDUP3,
5189     OP_VEXT1,
5190     OP_VEXT2,
5191     OP_VEXT3,
5192     OP_VUZPL, // VUZP, left result
5193     OP_VUZPR, // VUZP, right result
5194     OP_VZIPL, // VZIP, left result
5195     OP_VZIPR, // VZIP, right result
5196     OP_VTRNL, // VTRN, left result
5197     OP_VTRNR  // VTRN, right result
5198   };
5199
5200   if (OpNum == OP_COPY) {
5201     if (LHSID == (1*9+2)*9+3) return LHS;
5202     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5203     return RHS;
5204   }
5205
5206   SDValue OpLHS, OpRHS;
5207   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5208   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5209   EVT VT = OpLHS.getValueType();
5210
5211   switch (OpNum) {
5212   default: llvm_unreachable("Unknown shuffle opcode!");
5213   case OP_VREV:
5214     // VREV divides the vector in half and swaps within the half.
5215     if (VT.getVectorElementType() == MVT::i32 ||
5216         VT.getVectorElementType() == MVT::f32)
5217       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5218     // vrev <4 x i16> -> VREV32
5219     if (VT.getVectorElementType() == MVT::i16)
5220       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5221     // vrev <4 x i8> -> VREV16
5222     assert(VT.getVectorElementType() == MVT::i8);
5223     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5224   case OP_VDUP0:
5225   case OP_VDUP1:
5226   case OP_VDUP2:
5227   case OP_VDUP3:
5228     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5229                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5230   case OP_VEXT1:
5231   case OP_VEXT2:
5232   case OP_VEXT3:
5233     return DAG.getNode(ARMISD::VEXT, dl, VT,
5234                        OpLHS, OpRHS,
5235                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5236   case OP_VUZPL:
5237   case OP_VUZPR:
5238     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5239                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5240   case OP_VZIPL:
5241   case OP_VZIPR:
5242     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5243                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5244   case OP_VTRNL:
5245   case OP_VTRNR:
5246     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5247                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5248   }
5249 }
5250
5251 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5252                                        ArrayRef<int> ShuffleMask,
5253                                        SelectionDAG &DAG) {
5254   // Check to see if we can use the VTBL instruction.
5255   SDValue V1 = Op.getOperand(0);
5256   SDValue V2 = Op.getOperand(1);
5257   SDLoc DL(Op);
5258
5259   SmallVector<SDValue, 8> VTBLMask;
5260   for (ArrayRef<int>::iterator
5261          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5262     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5263
5264   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5265     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5266                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5267                                    &VTBLMask[0], 8));
5268
5269   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5270                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8,
5271                                  &VTBLMask[0], 8));
5272 }
5273
5274 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5275                                                       SelectionDAG &DAG) {
5276   SDLoc DL(Op);
5277   SDValue OpLHS = Op.getOperand(0);
5278   EVT VT = OpLHS.getValueType();
5279
5280   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5281          "Expect an v8i16/v16i8 type");
5282   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5283   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5284   // extract the first 8 bytes into the top double word and the last 8 bytes
5285   // into the bottom double word. The v8i16 case is similar.
5286   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5287   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5288                      DAG.getConstant(ExtractNum, MVT::i32));
5289 }
5290
5291 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5292   SDValue V1 = Op.getOperand(0);
5293   SDValue V2 = Op.getOperand(1);
5294   SDLoc dl(Op);
5295   EVT VT = Op.getValueType();
5296   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5297
5298   // Convert shuffles that are directly supported on NEON to target-specific
5299   // DAG nodes, instead of keeping them as shuffles and matching them again
5300   // during code selection.  This is more efficient and avoids the possibility
5301   // of inconsistencies between legalization and selection.
5302   // FIXME: floating-point vectors should be canonicalized to integer vectors
5303   // of the same time so that they get CSEd properly.
5304   ArrayRef<int> ShuffleMask = SVN->getMask();
5305
5306   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5307   if (EltSize <= 32) {
5308     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5309       int Lane = SVN->getSplatIndex();
5310       // If this is undef splat, generate it via "just" vdup, if possible.
5311       if (Lane == -1) Lane = 0;
5312
5313       // Test if V1 is a SCALAR_TO_VECTOR.
5314       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5315         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5316       }
5317       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5318       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5319       // reaches it).
5320       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5321           !isa<ConstantSDNode>(V1.getOperand(0))) {
5322         bool IsScalarToVector = true;
5323         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5324           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5325             IsScalarToVector = false;
5326             break;
5327           }
5328         if (IsScalarToVector)
5329           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5330       }
5331       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5332                          DAG.getConstant(Lane, MVT::i32));
5333     }
5334
5335     bool ReverseVEXT;
5336     unsigned Imm;
5337     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5338       if (ReverseVEXT)
5339         std::swap(V1, V2);
5340       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5341                          DAG.getConstant(Imm, MVT::i32));
5342     }
5343
5344     if (isVREVMask(ShuffleMask, VT, 64))
5345       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5346     if (isVREVMask(ShuffleMask, VT, 32))
5347       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5348     if (isVREVMask(ShuffleMask, VT, 16))
5349       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5350
5351     if (V2->getOpcode() == ISD::UNDEF &&
5352         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5353       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5354                          DAG.getConstant(Imm, MVT::i32));
5355     }
5356
5357     // Check for Neon shuffles that modify both input vectors in place.
5358     // If both results are used, i.e., if there are two shuffles with the same
5359     // source operands and with masks corresponding to both results of one of
5360     // these operations, DAG memoization will ensure that a single node is
5361     // used for both shuffles.
5362     unsigned WhichResult;
5363     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5364       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5365                          V1, V2).getValue(WhichResult);
5366     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5367       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5368                          V1, V2).getValue(WhichResult);
5369     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5370       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5371                          V1, V2).getValue(WhichResult);
5372
5373     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5374       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5375                          V1, V1).getValue(WhichResult);
5376     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5377       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5378                          V1, V1).getValue(WhichResult);
5379     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5380       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5381                          V1, V1).getValue(WhichResult);
5382   }
5383
5384   // If the shuffle is not directly supported and it has 4 elements, use
5385   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5386   unsigned NumElts = VT.getVectorNumElements();
5387   if (NumElts == 4) {
5388     unsigned PFIndexes[4];
5389     for (unsigned i = 0; i != 4; ++i) {
5390       if (ShuffleMask[i] < 0)
5391         PFIndexes[i] = 8;
5392       else
5393         PFIndexes[i] = ShuffleMask[i];
5394     }
5395
5396     // Compute the index in the perfect shuffle table.
5397     unsigned PFTableIndex =
5398       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5399     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5400     unsigned Cost = (PFEntry >> 30);
5401
5402     if (Cost <= 4)
5403       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5404   }
5405
5406   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5407   if (EltSize >= 32) {
5408     // Do the expansion with floating-point types, since that is what the VFP
5409     // registers are defined to use, and since i64 is not legal.
5410     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5411     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5412     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5413     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5414     SmallVector<SDValue, 8> Ops;
5415     for (unsigned i = 0; i < NumElts; ++i) {
5416       if (ShuffleMask[i] < 0)
5417         Ops.push_back(DAG.getUNDEF(EltVT));
5418       else
5419         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5420                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5421                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5422                                                   MVT::i32)));
5423     }
5424     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, &Ops[0],NumElts);
5425     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5426   }
5427
5428   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5429     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5430
5431   if (VT == MVT::v8i8) {
5432     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5433     if (NewOp.getNode())
5434       return NewOp;
5435   }
5436
5437   return SDValue();
5438 }
5439
5440 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5441   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5442   SDValue Lane = Op.getOperand(2);
5443   if (!isa<ConstantSDNode>(Lane))
5444     return SDValue();
5445
5446   return Op;
5447 }
5448
5449 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5450   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5451   SDValue Lane = Op.getOperand(1);
5452   if (!isa<ConstantSDNode>(Lane))
5453     return SDValue();
5454
5455   SDValue Vec = Op.getOperand(0);
5456   if (Op.getValueType() == MVT::i32 &&
5457       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5458     SDLoc dl(Op);
5459     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5460   }
5461
5462   return Op;
5463 }
5464
5465 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5466   // The only time a CONCAT_VECTORS operation can have legal types is when
5467   // two 64-bit vectors are concatenated to a 128-bit vector.
5468   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5469          "unexpected CONCAT_VECTORS");
5470   SDLoc dl(Op);
5471   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5472   SDValue Op0 = Op.getOperand(0);
5473   SDValue Op1 = Op.getOperand(1);
5474   if (Op0.getOpcode() != ISD::UNDEF)
5475     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5476                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5477                       DAG.getIntPtrConstant(0));
5478   if (Op1.getOpcode() != ISD::UNDEF)
5479     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5480                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5481                       DAG.getIntPtrConstant(1));
5482   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5483 }
5484
5485 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5486 /// element has been zero/sign-extended, depending on the isSigned parameter,
5487 /// from an integer type half its size.
5488 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5489                                    bool isSigned) {
5490   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5491   EVT VT = N->getValueType(0);
5492   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5493     SDNode *BVN = N->getOperand(0).getNode();
5494     if (BVN->getValueType(0) != MVT::v4i32 ||
5495         BVN->getOpcode() != ISD::BUILD_VECTOR)
5496       return false;
5497     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5498     unsigned HiElt = 1 - LoElt;
5499     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5500     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5501     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5502     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5503     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5504       return false;
5505     if (isSigned) {
5506       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5507           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5508         return true;
5509     } else {
5510       if (Hi0->isNullValue() && Hi1->isNullValue())
5511         return true;
5512     }
5513     return false;
5514   }
5515
5516   if (N->getOpcode() != ISD::BUILD_VECTOR)
5517     return false;
5518
5519   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5520     SDNode *Elt = N->getOperand(i).getNode();
5521     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5522       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5523       unsigned HalfSize = EltSize / 2;
5524       if (isSigned) {
5525         if (!isIntN(HalfSize, C->getSExtValue()))
5526           return false;
5527       } else {
5528         if (!isUIntN(HalfSize, C->getZExtValue()))
5529           return false;
5530       }
5531       continue;
5532     }
5533     return false;
5534   }
5535
5536   return true;
5537 }
5538
5539 /// isSignExtended - Check if a node is a vector value that is sign-extended
5540 /// or a constant BUILD_VECTOR with sign-extended elements.
5541 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5542   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5543     return true;
5544   if (isExtendedBUILD_VECTOR(N, DAG, true))
5545     return true;
5546   return false;
5547 }
5548
5549 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5550 /// or a constant BUILD_VECTOR with zero-extended elements.
5551 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5552   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5553     return true;
5554   if (isExtendedBUILD_VECTOR(N, DAG, false))
5555     return true;
5556   return false;
5557 }
5558
5559 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5560   if (OrigVT.getSizeInBits() >= 64)
5561     return OrigVT;
5562
5563   assert(OrigVT.isSimple() && "Expecting a simple value type");
5564
5565   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5566   switch (OrigSimpleTy) {
5567   default: llvm_unreachable("Unexpected Vector Type");
5568   case MVT::v2i8:
5569   case MVT::v2i16:
5570      return MVT::v2i32;
5571   case MVT::v4i8:
5572     return  MVT::v4i16;
5573   }
5574 }
5575
5576 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5577 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5578 /// We insert the required extension here to get the vector to fill a D register.
5579 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5580                                             const EVT &OrigTy,
5581                                             const EVT &ExtTy,
5582                                             unsigned ExtOpcode) {
5583   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5584   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5585   // 64-bits we need to insert a new extension so that it will be 64-bits.
5586   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5587   if (OrigTy.getSizeInBits() >= 64)
5588     return N;
5589
5590   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5591   EVT NewVT = getExtensionTo64Bits(OrigTy);
5592
5593   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5594 }
5595
5596 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5597 /// does not do any sign/zero extension. If the original vector is less
5598 /// than 64 bits, an appropriate extension will be added after the load to
5599 /// reach a total size of 64 bits. We have to add the extension separately
5600 /// because ARM does not have a sign/zero extending load for vectors.
5601 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5602   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5603
5604   // The load already has the right type.
5605   if (ExtendedTy == LD->getMemoryVT())
5606     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5607                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5608                 LD->isNonTemporal(), LD->isInvariant(),
5609                 LD->getAlignment());
5610
5611   // We need to create a zextload/sextload. We cannot just create a load
5612   // followed by a zext/zext node because LowerMUL is also run during normal
5613   // operation legalization where we can't create illegal types.
5614   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5615                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5616                         LD->getMemoryVT(), LD->isVolatile(),
5617                         LD->isNonTemporal(), LD->getAlignment());
5618 }
5619
5620 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5621 /// extending load, or BUILD_VECTOR with extended elements, return the
5622 /// unextended value. The unextended vector should be 64 bits so that it can
5623 /// be used as an operand to a VMULL instruction. If the original vector size
5624 /// before extension is less than 64 bits we add a an extension to resize
5625 /// the vector to 64 bits.
5626 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5627   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5628     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5629                                         N->getOperand(0)->getValueType(0),
5630                                         N->getValueType(0),
5631                                         N->getOpcode());
5632
5633   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5634     return SkipLoadExtensionForVMULL(LD, DAG);
5635
5636   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5637   // have been legalized as a BITCAST from v4i32.
5638   if (N->getOpcode() == ISD::BITCAST) {
5639     SDNode *BVN = N->getOperand(0).getNode();
5640     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5641            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5642     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5643     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5644                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5645   }
5646   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5647   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5648   EVT VT = N->getValueType(0);
5649   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5650   unsigned NumElts = VT.getVectorNumElements();
5651   MVT TruncVT = MVT::getIntegerVT(EltSize);
5652   SmallVector<SDValue, 8> Ops;
5653   for (unsigned i = 0; i != NumElts; ++i) {
5654     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5655     const APInt &CInt = C->getAPIntValue();
5656     // Element types smaller than 32 bits are not legal, so use i32 elements.
5657     // The values are implicitly truncated so sext vs. zext doesn't matter.
5658     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5659   }
5660   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5661                      MVT::getVectorVT(TruncVT, NumElts), Ops.data(), NumElts);
5662 }
5663
5664 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5665   unsigned Opcode = N->getOpcode();
5666   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5667     SDNode *N0 = N->getOperand(0).getNode();
5668     SDNode *N1 = N->getOperand(1).getNode();
5669     return N0->hasOneUse() && N1->hasOneUse() &&
5670       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5671   }
5672   return false;
5673 }
5674
5675 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5676   unsigned Opcode = N->getOpcode();
5677   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5678     SDNode *N0 = N->getOperand(0).getNode();
5679     SDNode *N1 = N->getOperand(1).getNode();
5680     return N0->hasOneUse() && N1->hasOneUse() &&
5681       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5682   }
5683   return false;
5684 }
5685
5686 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5687   // Multiplications are only custom-lowered for 128-bit vectors so that
5688   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5689   EVT VT = Op.getValueType();
5690   assert(VT.is128BitVector() && VT.isInteger() &&
5691          "unexpected type for custom-lowering ISD::MUL");
5692   SDNode *N0 = Op.getOperand(0).getNode();
5693   SDNode *N1 = Op.getOperand(1).getNode();
5694   unsigned NewOpc = 0;
5695   bool isMLA = false;
5696   bool isN0SExt = isSignExtended(N0, DAG);
5697   bool isN1SExt = isSignExtended(N1, DAG);
5698   if (isN0SExt && isN1SExt)
5699     NewOpc = ARMISD::VMULLs;
5700   else {
5701     bool isN0ZExt = isZeroExtended(N0, DAG);
5702     bool isN1ZExt = isZeroExtended(N1, DAG);
5703     if (isN0ZExt && isN1ZExt)
5704       NewOpc = ARMISD::VMULLu;
5705     else if (isN1SExt || isN1ZExt) {
5706       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5707       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5708       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5709         NewOpc = ARMISD::VMULLs;
5710         isMLA = true;
5711       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5712         NewOpc = ARMISD::VMULLu;
5713         isMLA = true;
5714       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5715         std::swap(N0, N1);
5716         NewOpc = ARMISD::VMULLu;
5717         isMLA = true;
5718       }
5719     }
5720
5721     if (!NewOpc) {
5722       if (VT == MVT::v2i64)
5723         // Fall through to expand this.  It is not legal.
5724         return SDValue();
5725       else
5726         // Other vector multiplications are legal.
5727         return Op;
5728     }
5729   }
5730
5731   // Legalize to a VMULL instruction.
5732   SDLoc DL(Op);
5733   SDValue Op0;
5734   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5735   if (!isMLA) {
5736     Op0 = SkipExtensionForVMULL(N0, DAG);
5737     assert(Op0.getValueType().is64BitVector() &&
5738            Op1.getValueType().is64BitVector() &&
5739            "unexpected types for extended operands to VMULL");
5740     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5741   }
5742
5743   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5744   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5745   //   vmull q0, d4, d6
5746   //   vmlal q0, d5, d6
5747   // is faster than
5748   //   vaddl q0, d4, d5
5749   //   vmovl q1, d6
5750   //   vmul  q0, q0, q1
5751   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5752   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5753   EVT Op1VT = Op1.getValueType();
5754   return DAG.getNode(N0->getOpcode(), DL, VT,
5755                      DAG.getNode(NewOpc, DL, VT,
5756                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5757                      DAG.getNode(NewOpc, DL, VT,
5758                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5759 }
5760
5761 static SDValue
5762 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5763   // Convert to float
5764   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5765   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5766   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5767   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5768   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5769   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5770   // Get reciprocal estimate.
5771   // float4 recip = vrecpeq_f32(yf);
5772   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5773                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5774   // Because char has a smaller range than uchar, we can actually get away
5775   // without any newton steps.  This requires that we use a weird bias
5776   // of 0xb000, however (again, this has been exhaustively tested).
5777   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5778   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5779   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5780   Y = DAG.getConstant(0xb000, MVT::i32);
5781   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5782   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5783   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5784   // Convert back to short.
5785   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5786   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5787   return X;
5788 }
5789
5790 static SDValue
5791 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5792   SDValue N2;
5793   // Convert to float.
5794   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5795   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5796   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5797   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5798   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5799   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5800
5801   // Use reciprocal estimate and one refinement step.
5802   // float4 recip = vrecpeq_f32(yf);
5803   // recip *= vrecpsq_f32(yf, recip);
5804   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5805                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5806   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5807                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5808                    N1, N2);
5809   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5810   // Because short has a smaller range than ushort, we can actually get away
5811   // with only a single newton step.  This requires that we use a weird bias
5812   // of 89, however (again, this has been exhaustively tested).
5813   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5814   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5815   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5816   N1 = DAG.getConstant(0x89, MVT::i32);
5817   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5818   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5819   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5820   // Convert back to integer and return.
5821   // return vmovn_s32(vcvt_s32_f32(result));
5822   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5823   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5824   return N0;
5825 }
5826
5827 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5828   EVT VT = Op.getValueType();
5829   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5830          "unexpected type for custom-lowering ISD::SDIV");
5831
5832   SDLoc dl(Op);
5833   SDValue N0 = Op.getOperand(0);
5834   SDValue N1 = Op.getOperand(1);
5835   SDValue N2, N3;
5836
5837   if (VT == MVT::v8i8) {
5838     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5839     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5840
5841     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5842                      DAG.getIntPtrConstant(4));
5843     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5844                      DAG.getIntPtrConstant(4));
5845     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5846                      DAG.getIntPtrConstant(0));
5847     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5848                      DAG.getIntPtrConstant(0));
5849
5850     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5851     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5852
5853     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5854     N0 = LowerCONCAT_VECTORS(N0, DAG);
5855
5856     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5857     return N0;
5858   }
5859   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5860 }
5861
5862 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5863   EVT VT = Op.getValueType();
5864   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5865          "unexpected type for custom-lowering ISD::UDIV");
5866
5867   SDLoc dl(Op);
5868   SDValue N0 = Op.getOperand(0);
5869   SDValue N1 = Op.getOperand(1);
5870   SDValue N2, N3;
5871
5872   if (VT == MVT::v8i8) {
5873     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5874     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5875
5876     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5877                      DAG.getIntPtrConstant(4));
5878     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5879                      DAG.getIntPtrConstant(4));
5880     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5881                      DAG.getIntPtrConstant(0));
5882     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5883                      DAG.getIntPtrConstant(0));
5884
5885     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5886     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5887
5888     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5889     N0 = LowerCONCAT_VECTORS(N0, DAG);
5890
5891     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5892                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5893                      N0);
5894     return N0;
5895   }
5896
5897   // v4i16 sdiv ... Convert to float.
5898   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5899   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5900   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5901   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5902   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5903   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5904
5905   // Use reciprocal estimate and two refinement steps.
5906   // float4 recip = vrecpeq_f32(yf);
5907   // recip *= vrecpsq_f32(yf, recip);
5908   // recip *= vrecpsq_f32(yf, recip);
5909   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5910                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5911   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5912                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5913                    BN1, N2);
5914   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5915   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5916                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5917                    BN1, N2);
5918   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5919   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5920   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5921   // and that it will never cause us to return an answer too large).
5922   // float4 result = as_float4(as_int4(xf*recip) + 2);
5923   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5924   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5925   N1 = DAG.getConstant(2, MVT::i32);
5926   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5927   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5928   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5929   // Convert back to integer and return.
5930   // return vmovn_u32(vcvt_s32_f32(result));
5931   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5932   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5933   return N0;
5934 }
5935
5936 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5937   EVT VT = Op.getNode()->getValueType(0);
5938   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5939
5940   unsigned Opc;
5941   bool ExtraOp = false;
5942   switch (Op.getOpcode()) {
5943   default: llvm_unreachable("Invalid code");
5944   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5945   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5946   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5947   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5948   }
5949
5950   if (!ExtraOp)
5951     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5952                        Op.getOperand(1));
5953   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5954                      Op.getOperand(1), Op.getOperand(2));
5955 }
5956
5957 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5958   assert(Subtarget->isTargetDarwin());
5959
5960   // For iOS, we want to call an alternative entry point: __sincos_stret,
5961   // return values are passed via sret.
5962   SDLoc dl(Op);
5963   SDValue Arg = Op.getOperand(0);
5964   EVT ArgVT = Arg.getValueType();
5965   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5966
5967   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5969
5970   // Pair of floats / doubles used to pass the result.
5971   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5972
5973   // Create stack object for sret.
5974   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5975   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5976   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5977   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5978
5979   ArgListTy Args;
5980   ArgListEntry Entry;
5981
5982   Entry.Node = SRet;
5983   Entry.Ty = RetTy->getPointerTo();
5984   Entry.isSExt = false;
5985   Entry.isZExt = false;
5986   Entry.isSRet = true;
5987   Args.push_back(Entry);
5988
5989   Entry.Node = Arg;
5990   Entry.Ty = ArgTy;
5991   Entry.isSExt = false;
5992   Entry.isZExt = false;
5993   Args.push_back(Entry);
5994
5995   const char *LibcallName  = (ArgVT == MVT::f64)
5996   ? "__sincos_stret" : "__sincosf_stret";
5997   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5998
5999   TargetLowering::
6000   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
6001                        false, false, false, false, 0,
6002                        CallingConv::C, /*isTaillCall=*/false,
6003                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
6004                        Callee, Args, DAG, dl);
6005   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6006
6007   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6008                                 MachinePointerInfo(), false, false, false, 0);
6009
6010   // Address of cos field.
6011   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6012                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6013   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6014                                 MachinePointerInfo(), false, false, false, 0);
6015
6016   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6017   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6018                      LoadSin.getValue(0), LoadCos.getValue(0));
6019 }
6020
6021 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6022   // Monotonic load/store is legal for all targets
6023   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6024     return Op;
6025
6026   // Acquire/Release load/store is not legal for targets without a
6027   // dmb or equivalent available.
6028   return SDValue();
6029 }
6030
6031 static void
6032 ReplaceATOMIC_OP_64(SDNode *Node, SmallVectorImpl<SDValue>& Results,
6033                     SelectionDAG &DAG) {
6034   SDLoc dl(Node);
6035   assert (Node->getValueType(0) == MVT::i64 &&
6036           "Only know how to expand i64 atomics");
6037   AtomicSDNode *AN = cast<AtomicSDNode>(Node);
6038
6039   SmallVector<SDValue, 6> Ops;
6040   Ops.push_back(Node->getOperand(0)); // Chain
6041   Ops.push_back(Node->getOperand(1)); // Ptr
6042   for(unsigned i=2; i<Node->getNumOperands(); i++) {
6043     // Low part
6044     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6045                               Node->getOperand(i), DAG.getIntPtrConstant(0)));
6046     // High part
6047     Ops.push_back(DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6048                               Node->getOperand(i), DAG.getIntPtrConstant(1)));
6049   }
6050   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6051   SDValue Result = DAG.getAtomic(
6052       Node->getOpcode(), dl, MVT::i64, Tys, Ops.data(), Ops.size(),
6053       cast<MemSDNode>(Node)->getMemOperand(), AN->getSuccessOrdering(),
6054       AN->getFailureOrdering(), AN->getSynchScope());
6055   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1) };
6056   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6057   Results.push_back(Result.getValue(2));
6058 }
6059
6060 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6061                                     SmallVectorImpl<SDValue> &Results,
6062                                     SelectionDAG &DAG,
6063                                     const ARMSubtarget *Subtarget) {
6064   SDLoc DL(N);
6065   SDValue Cycles32, OutChain;
6066
6067   if (Subtarget->hasPerfMon()) {
6068     // Under Power Management extensions, the cycle-count is:
6069     //    mrc p15, #0, <Rt>, c9, c13, #0
6070     SDValue Ops[] = { N->getOperand(0), // Chain
6071                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6072                       DAG.getConstant(15, MVT::i32),
6073                       DAG.getConstant(0, MVT::i32),
6074                       DAG.getConstant(9, MVT::i32),
6075                       DAG.getConstant(13, MVT::i32),
6076                       DAG.getConstant(0, MVT::i32)
6077     };
6078
6079     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6080                            DAG.getVTList(MVT::i32, MVT::Other), &Ops[0],
6081                            array_lengthof(Ops));
6082     OutChain = Cycles32.getValue(1);
6083   } else {
6084     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6085     // there are older ARM CPUs that have implementation-specific ways of
6086     // obtaining this information (FIXME!).
6087     Cycles32 = DAG.getConstant(0, MVT::i32);
6088     OutChain = DAG.getEntryNode();
6089   }
6090
6091
6092   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6093                                  Cycles32, DAG.getConstant(0, MVT::i32));
6094   Results.push_back(Cycles64);
6095   Results.push_back(OutChain);
6096 }
6097
6098 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6099   switch (Op.getOpcode()) {
6100   default: llvm_unreachable("Don't know how to custom lower this!");
6101   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6102   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6103   case ISD::GlobalAddress:
6104     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6105       LowerGlobalAddressELF(Op, DAG);
6106   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6107   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6108   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6109   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6110   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6111   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6112   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6113   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6114   case ISD::SINT_TO_FP:
6115   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6116   case ISD::FP_TO_SINT:
6117   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6118   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6119   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6120   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6121   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6122   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6123   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6124   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6125                                                                Subtarget);
6126   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6127   case ISD::SHL:
6128   case ISD::SRL:
6129   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6130   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6131   case ISD::SRL_PARTS:
6132   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6133   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6134   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6135   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6136   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6137   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6138   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6139   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6140   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6141   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6142   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6143   case ISD::MUL:           return LowerMUL(Op, DAG);
6144   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6145   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6146   case ISD::ADDC:
6147   case ISD::ADDE:
6148   case ISD::SUBC:
6149   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6150   case ISD::ATOMIC_LOAD:
6151   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6152   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6153   case ISD::SDIVREM:
6154   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6155   }
6156 }
6157
6158 /// ReplaceNodeResults - Replace the results of node with an illegal result
6159 /// type with new values built out of custom code.
6160 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6161                                            SmallVectorImpl<SDValue>&Results,
6162                                            SelectionDAG &DAG) const {
6163   SDValue Res;
6164   switch (N->getOpcode()) {
6165   default:
6166     llvm_unreachable("Don't know how to custom expand this!");
6167   case ISD::BITCAST:
6168     Res = ExpandBITCAST(N, DAG);
6169     break;
6170   case ISD::SRL:
6171   case ISD::SRA:
6172     Res = Expand64BitShift(N, DAG, Subtarget);
6173     break;
6174   case ISD::READCYCLECOUNTER:
6175     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6176     return;
6177   case ISD::ATOMIC_STORE:
6178   case ISD::ATOMIC_LOAD:
6179   case ISD::ATOMIC_LOAD_ADD:
6180   case ISD::ATOMIC_LOAD_AND:
6181   case ISD::ATOMIC_LOAD_NAND:
6182   case ISD::ATOMIC_LOAD_OR:
6183   case ISD::ATOMIC_LOAD_SUB:
6184   case ISD::ATOMIC_LOAD_XOR:
6185   case ISD::ATOMIC_SWAP:
6186   case ISD::ATOMIC_CMP_SWAP:
6187   case ISD::ATOMIC_LOAD_MIN:
6188   case ISD::ATOMIC_LOAD_UMIN:
6189   case ISD::ATOMIC_LOAD_MAX:
6190   case ISD::ATOMIC_LOAD_UMAX:
6191     ReplaceATOMIC_OP_64(N, Results, DAG);
6192     return;
6193   }
6194   if (Res.getNode())
6195     Results.push_back(Res);
6196 }
6197
6198 //===----------------------------------------------------------------------===//
6199 //                           ARM Scheduler Hooks
6200 //===----------------------------------------------------------------------===//
6201
6202 MachineBasicBlock *
6203 ARMTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
6204                                      MachineBasicBlock *BB,
6205                                      unsigned Size) const {
6206   unsigned dest    = MI->getOperand(0).getReg();
6207   unsigned ptr     = MI->getOperand(1).getReg();
6208   unsigned oldval  = MI->getOperand(2).getReg();
6209   unsigned newval  = MI->getOperand(3).getReg();
6210   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6211   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(4).getImm());
6212   DebugLoc dl = MI->getDebugLoc();
6213   bool isThumb2 = Subtarget->isThumb2();
6214
6215   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6216   unsigned scratch = MRI.createVirtualRegister(isThumb2 ?
6217     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6218     (const TargetRegisterClass*)&ARM::GPRRegClass);
6219
6220   if (isThumb2) {
6221     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6222     MRI.constrainRegClass(oldval, &ARM::rGPRRegClass);
6223     MRI.constrainRegClass(newval, &ARM::rGPRRegClass);
6224   }
6225
6226   unsigned ldrOpc, strOpc;
6227   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6228
6229   MachineFunction *MF = BB->getParent();
6230   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6231   MachineFunction::iterator It = BB;
6232   ++It; // insert the new blocks after the current block
6233
6234   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6235   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
6236   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6237   MF->insert(It, loop1MBB);
6238   MF->insert(It, loop2MBB);
6239   MF->insert(It, exitMBB);
6240
6241   // Transfer the remainder of BB and its successor edges to exitMBB.
6242   exitMBB->splice(exitMBB->begin(), BB,
6243                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6244   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6245
6246   //  thisMBB:
6247   //   ...
6248   //   fallthrough --> loop1MBB
6249   BB->addSuccessor(loop1MBB);
6250
6251   // loop1MBB:
6252   //   ldrex dest, [ptr]
6253   //   cmp dest, oldval
6254   //   bne exitMBB
6255   BB = loop1MBB;
6256   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6257   if (ldrOpc == ARM::t2LDREX)
6258     MIB.addImm(0);
6259   AddDefaultPred(MIB);
6260   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6261                  .addReg(dest).addReg(oldval));
6262   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6263     .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6264   BB->addSuccessor(loop2MBB);
6265   BB->addSuccessor(exitMBB);
6266
6267   // loop2MBB:
6268   //   strex scratch, newval, [ptr]
6269   //   cmp scratch, #0
6270   //   bne loop1MBB
6271   BB = loop2MBB;
6272   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(newval).addReg(ptr);
6273   if (strOpc == ARM::t2STREX)
6274     MIB.addImm(0);
6275   AddDefaultPred(MIB);
6276   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6277                  .addReg(scratch).addImm(0));
6278   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6279     .addMBB(loop1MBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6280   BB->addSuccessor(loop1MBB);
6281   BB->addSuccessor(exitMBB);
6282
6283   //  exitMBB:
6284   //   ...
6285   BB = exitMBB;
6286
6287   MI->eraseFromParent();   // The instruction is gone now.
6288
6289   return BB;
6290 }
6291
6292 MachineBasicBlock *
6293 ARMTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6294                                     unsigned Size, unsigned BinOpcode) const {
6295   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6296   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6297
6298   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6299   MachineFunction *MF = BB->getParent();
6300   MachineFunction::iterator It = BB;
6301   ++It;
6302
6303   unsigned dest = MI->getOperand(0).getReg();
6304   unsigned ptr = MI->getOperand(1).getReg();
6305   unsigned incr = MI->getOperand(2).getReg();
6306   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6307   DebugLoc dl = MI->getDebugLoc();
6308   bool isThumb2 = Subtarget->isThumb2();
6309
6310   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6311   if (isThumb2) {
6312     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6313     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6314     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6315   }
6316
6317   unsigned ldrOpc, strOpc;
6318   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6319
6320   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6321   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6322   MF->insert(It, loopMBB);
6323   MF->insert(It, exitMBB);
6324
6325   // Transfer the remainder of BB and its successor edges to exitMBB.
6326   exitMBB->splice(exitMBB->begin(), BB,
6327                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6328   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6329
6330   const TargetRegisterClass *TRC = isThumb2 ?
6331     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6332     (const TargetRegisterClass*)&ARM::GPRRegClass;
6333   unsigned scratch = MRI.createVirtualRegister(TRC);
6334   unsigned scratch2 = (!BinOpcode) ? incr : MRI.createVirtualRegister(TRC);
6335
6336   //  thisMBB:
6337   //   ...
6338   //   fallthrough --> loopMBB
6339   BB->addSuccessor(loopMBB);
6340
6341   //  loopMBB:
6342   //   ldrex dest, ptr
6343   //   <binop> scratch2, dest, incr
6344   //   strex scratch, scratch2, ptr
6345   //   cmp scratch, #0
6346   //   bne- loopMBB
6347   //   fallthrough --> exitMBB
6348   BB = loopMBB;
6349   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6350   if (ldrOpc == ARM::t2LDREX)
6351     MIB.addImm(0);
6352   AddDefaultPred(MIB);
6353   if (BinOpcode) {
6354     // operand order needs to go the other way for NAND
6355     if (BinOpcode == ARM::BICrr || BinOpcode == ARM::t2BICrr)
6356       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6357                      addReg(incr).addReg(dest)).addReg(0);
6358     else
6359       AddDefaultPred(BuildMI(BB, dl, TII->get(BinOpcode), scratch2).
6360                      addReg(dest).addReg(incr)).addReg(0);
6361   }
6362
6363   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6364   if (strOpc == ARM::t2STREX)
6365     MIB.addImm(0);
6366   AddDefaultPred(MIB);
6367   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6368                  .addReg(scratch).addImm(0));
6369   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6370     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6371
6372   BB->addSuccessor(loopMBB);
6373   BB->addSuccessor(exitMBB);
6374
6375   //  exitMBB:
6376   //   ...
6377   BB = exitMBB;
6378
6379   MI->eraseFromParent();   // The instruction is gone now.
6380
6381   return BB;
6382 }
6383
6384 MachineBasicBlock *
6385 ARMTargetLowering::EmitAtomicBinaryMinMax(MachineInstr *MI,
6386                                           MachineBasicBlock *BB,
6387                                           unsigned Size,
6388                                           bool signExtend,
6389                                           ARMCC::CondCodes Cond) const {
6390   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6391
6392   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6393   MachineFunction *MF = BB->getParent();
6394   MachineFunction::iterator It = BB;
6395   ++It;
6396
6397   unsigned dest = MI->getOperand(0).getReg();
6398   unsigned ptr = MI->getOperand(1).getReg();
6399   unsigned incr = MI->getOperand(2).getReg();
6400   unsigned oldval = dest;
6401   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6402   DebugLoc dl = MI->getDebugLoc();
6403   bool isThumb2 = Subtarget->isThumb2();
6404
6405   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6406   if (isThumb2) {
6407     MRI.constrainRegClass(dest, &ARM::rGPRRegClass);
6408     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6409     MRI.constrainRegClass(incr, &ARM::rGPRRegClass);
6410   }
6411
6412   unsigned ldrOpc, strOpc, extendOpc;
6413   getExclusiveOperation(Size, Ord, isThumb2, ldrOpc, strOpc);
6414   switch (Size) {
6415   default: llvm_unreachable("unsupported size for AtomicBinaryMinMax!");
6416   case 1:
6417     extendOpc = isThumb2 ? ARM::t2SXTB : ARM::SXTB;
6418     break;
6419   case 2:
6420     extendOpc = isThumb2 ? ARM::t2SXTH : ARM::SXTH;
6421     break;
6422   case 4:
6423     extendOpc = 0;
6424     break;
6425   }
6426
6427   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6428   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6429   MF->insert(It, loopMBB);
6430   MF->insert(It, exitMBB);
6431
6432   // Transfer the remainder of BB and its successor edges to exitMBB.
6433   exitMBB->splice(exitMBB->begin(), BB,
6434                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6435   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6436
6437   const TargetRegisterClass *TRC = isThumb2 ?
6438     (const TargetRegisterClass*)&ARM::rGPRRegClass :
6439     (const TargetRegisterClass*)&ARM::GPRRegClass;
6440   unsigned scratch = MRI.createVirtualRegister(TRC);
6441   unsigned scratch2 = MRI.createVirtualRegister(TRC);
6442
6443   //  thisMBB:
6444   //   ...
6445   //   fallthrough --> loopMBB
6446   BB->addSuccessor(loopMBB);
6447
6448   //  loopMBB:
6449   //   ldrex dest, ptr
6450   //   (sign extend dest, if required)
6451   //   cmp dest, incr
6452   //   cmov.cond scratch2, incr, dest
6453   //   strex scratch, scratch2, ptr
6454   //   cmp scratch, #0
6455   //   bne- loopMBB
6456   //   fallthrough --> exitMBB
6457   BB = loopMBB;
6458   MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(ldrOpc), dest).addReg(ptr);
6459   if (ldrOpc == ARM::t2LDREX)
6460     MIB.addImm(0);
6461   AddDefaultPred(MIB);
6462
6463   // Sign extend the value, if necessary.
6464   if (signExtend && extendOpc) {
6465     oldval = MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass
6466                                                 : &ARM::GPRnopcRegClass);
6467     if (!isThumb2)
6468       MRI.constrainRegClass(dest, &ARM::GPRnopcRegClass);
6469     AddDefaultPred(BuildMI(BB, dl, TII->get(extendOpc), oldval)
6470                      .addReg(dest)
6471                      .addImm(0));
6472   }
6473
6474   // Build compare and cmov instructions.
6475   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
6476                  .addReg(oldval).addReg(incr));
6477   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr), scratch2)
6478          .addReg(incr).addReg(oldval).addImm(Cond).addReg(ARM::CPSR);
6479
6480   MIB = BuildMI(BB, dl, TII->get(strOpc), scratch).addReg(scratch2).addReg(ptr);
6481   if (strOpc == ARM::t2STREX)
6482     MIB.addImm(0);
6483   AddDefaultPred(MIB);
6484   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6485                  .addReg(scratch).addImm(0));
6486   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6487     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6488
6489   BB->addSuccessor(loopMBB);
6490   BB->addSuccessor(exitMBB);
6491
6492   //  exitMBB:
6493   //   ...
6494   BB = exitMBB;
6495
6496   MI->eraseFromParent();   // The instruction is gone now.
6497
6498   return BB;
6499 }
6500
6501 MachineBasicBlock *
6502 ARMTargetLowering::EmitAtomicBinary64(MachineInstr *MI, MachineBasicBlock *BB,
6503                                       unsigned Op1, unsigned Op2,
6504                                       bool NeedsCarry, bool IsCmpxchg,
6505                                       bool IsMinMax, ARMCC::CondCodes CC) const {
6506   // This also handles ATOMIC_SWAP and ATOMIC_STORE, indicated by Op1==0.
6507   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6508
6509   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6510   MachineFunction *MF = BB->getParent();
6511   MachineFunction::iterator It = BB;
6512   ++It;
6513
6514   unsigned destlo = MI->getOperand(0).getReg();
6515   unsigned desthi = MI->getOperand(1).getReg();
6516   unsigned ptr = MI->getOperand(2).getReg();
6517   unsigned vallo = MI->getOperand(3).getReg();
6518   unsigned valhi = MI->getOperand(4).getReg();
6519   AtomicOrdering Ord =
6520       static_cast<AtomicOrdering>(MI->getOperand(IsCmpxchg ? 7 : 5).getImm());
6521   DebugLoc dl = MI->getDebugLoc();
6522   bool isThumb2 = Subtarget->isThumb2();
6523
6524   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6525   if (isThumb2) {
6526     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6527     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6528     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6529     MRI.constrainRegClass(vallo, &ARM::rGPRRegClass);
6530     MRI.constrainRegClass(valhi, &ARM::rGPRRegClass);
6531   }
6532
6533   unsigned ldrOpc, strOpc;
6534   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6535
6536   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6537   MachineBasicBlock *contBB = 0, *cont2BB = 0;
6538   if (IsCmpxchg || IsMinMax)
6539     contBB = MF->CreateMachineBasicBlock(LLVM_BB);
6540   if (IsCmpxchg)
6541     cont2BB = MF->CreateMachineBasicBlock(LLVM_BB);
6542   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6543
6544   MF->insert(It, loopMBB);
6545   if (IsCmpxchg || IsMinMax) MF->insert(It, contBB);
6546   if (IsCmpxchg) MF->insert(It, cont2BB);
6547   MF->insert(It, exitMBB);
6548
6549   // Transfer the remainder of BB and its successor edges to exitMBB.
6550   exitMBB->splice(exitMBB->begin(), BB,
6551                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6552   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6553
6554   const TargetRegisterClass *TRC = isThumb2 ?
6555     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6556     (const TargetRegisterClass*)&ARM::GPRRegClass;
6557   unsigned storesuccess = MRI.createVirtualRegister(TRC);
6558
6559   //  thisMBB:
6560   //   ...
6561   //   fallthrough --> loopMBB
6562   BB->addSuccessor(loopMBB);
6563
6564   //  loopMBB:
6565   //   ldrexd r2, r3, ptr
6566   //   <binopa> r0, r2, incr
6567   //   <binopb> r1, r3, incr
6568   //   strexd storesuccess, r0, r1, ptr
6569   //   cmp storesuccess, #0
6570   //   bne- loopMBB
6571   //   fallthrough --> exitMBB
6572   BB = loopMBB;
6573
6574   // Load
6575   if (isThumb2) {
6576     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6577                        .addReg(destlo, RegState::Define)
6578                        .addReg(desthi, RegState::Define)
6579                        .addReg(ptr));
6580   } else {
6581     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6582     AddDefaultPred(BuildMI(BB, dl, TII->get(ldrOpc))
6583                        .addReg(GPRPair0, RegState::Define)
6584                        .addReg(ptr));
6585     // Copy r2/r3 into dest.  (This copy will normally be coalesced.)
6586     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), destlo)
6587         .addReg(GPRPair0, 0, ARM::gsub_0);
6588     BuildMI(BB, dl, TII->get(TargetOpcode::COPY), desthi)
6589         .addReg(GPRPair0, 0, ARM::gsub_1);
6590   }
6591
6592   unsigned StoreLo, StoreHi;
6593   if (IsCmpxchg) {
6594     // Add early exit
6595     for (unsigned i = 0; i < 2; i++) {
6596       AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr :
6597                                                          ARM::CMPrr))
6598                      .addReg(i == 0 ? destlo : desthi)
6599                      .addReg(i == 0 ? vallo : valhi));
6600       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6601         .addMBB(exitMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6602       BB->addSuccessor(exitMBB);
6603       BB->addSuccessor(i == 0 ? contBB : cont2BB);
6604       BB = (i == 0 ? contBB : cont2BB);
6605     }
6606
6607     // Copy to physregs for strexd
6608     StoreLo = MI->getOperand(5).getReg();
6609     StoreHi = MI->getOperand(6).getReg();
6610   } else if (Op1) {
6611     // Perform binary operation
6612     unsigned tmpRegLo = MRI.createVirtualRegister(TRC);
6613     AddDefaultPred(BuildMI(BB, dl, TII->get(Op1), tmpRegLo)
6614                    .addReg(destlo).addReg(vallo))
6615         .addReg(NeedsCarry ? ARM::CPSR : 0, getDefRegState(NeedsCarry));
6616     unsigned tmpRegHi = MRI.createVirtualRegister(TRC);
6617     AddDefaultPred(BuildMI(BB, dl, TII->get(Op2), tmpRegHi)
6618                    .addReg(desthi).addReg(valhi))
6619         .addReg(IsMinMax ? ARM::CPSR : 0, getDefRegState(IsMinMax));
6620
6621     StoreLo = tmpRegLo;
6622     StoreHi = tmpRegHi;
6623   } else {
6624     // Copy to physregs for strexd
6625     StoreLo = vallo;
6626     StoreHi = valhi;
6627   }
6628   if (IsMinMax) {
6629     // Compare and branch to exit block.
6630     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6631       .addMBB(exitMBB).addImm(CC).addReg(ARM::CPSR);
6632     BB->addSuccessor(exitMBB);
6633     BB->addSuccessor(contBB);
6634     BB = contBB;
6635     StoreLo = vallo;
6636     StoreHi = valhi;
6637   }
6638
6639   // Store
6640   if (isThumb2) {
6641     MRI.constrainRegClass(StoreLo, &ARM::rGPRRegClass);
6642     MRI.constrainRegClass(StoreHi, &ARM::rGPRRegClass);
6643     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6644                    .addReg(StoreLo).addReg(StoreHi).addReg(ptr));
6645   } else {
6646     // Marshal a pair...
6647     unsigned StorePair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6648     unsigned UndefPair = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6649     unsigned r1 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6650     BuildMI(BB, dl, TII->get(TargetOpcode::IMPLICIT_DEF), UndefPair);
6651     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), r1)
6652       .addReg(UndefPair)
6653       .addReg(StoreLo)
6654       .addImm(ARM::gsub_0);
6655     BuildMI(BB, dl, TII->get(TargetOpcode::INSERT_SUBREG), StorePair)
6656       .addReg(r1)
6657       .addReg(StoreHi)
6658       .addImm(ARM::gsub_1);
6659
6660     // ...and store it
6661     AddDefaultPred(BuildMI(BB, dl, TII->get(strOpc), storesuccess)
6662                    .addReg(StorePair).addReg(ptr));
6663   }
6664   // Cmp+jump
6665   AddDefaultPred(BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
6666                  .addReg(storesuccess).addImm(0));
6667   BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
6668     .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6669
6670   BB->addSuccessor(loopMBB);
6671   BB->addSuccessor(exitMBB);
6672
6673   //  exitMBB:
6674   //   ...
6675   BB = exitMBB;
6676
6677   MI->eraseFromParent();   // The instruction is gone now.
6678
6679   return BB;
6680 }
6681
6682 MachineBasicBlock *
6683 ARMTargetLowering::EmitAtomicLoad64(MachineInstr *MI, MachineBasicBlock *BB) const {
6684
6685   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6686
6687   unsigned destlo = MI->getOperand(0).getReg();
6688   unsigned desthi = MI->getOperand(1).getReg();
6689   unsigned ptr = MI->getOperand(2).getReg();
6690   AtomicOrdering Ord = static_cast<AtomicOrdering>(MI->getOperand(3).getImm());
6691   DebugLoc dl = MI->getDebugLoc();
6692   bool isThumb2 = Subtarget->isThumb2();
6693
6694   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
6695   if (isThumb2) {
6696     MRI.constrainRegClass(destlo, &ARM::rGPRRegClass);
6697     MRI.constrainRegClass(desthi, &ARM::rGPRRegClass);
6698     MRI.constrainRegClass(ptr, &ARM::rGPRRegClass);
6699   }
6700   unsigned ldrOpc, strOpc;
6701   getExclusiveOperation(8, Ord, isThumb2, ldrOpc, strOpc);
6702
6703   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(ldrOpc));
6704
6705   if (isThumb2) {
6706     MIB.addReg(destlo, RegState::Define)
6707        .addReg(desthi, RegState::Define)
6708        .addReg(ptr);
6709
6710   } else {
6711     unsigned GPRPair0 = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
6712     MIB.addReg(GPRPair0, RegState::Define).addReg(ptr);
6713
6714     // Copy GPRPair0 into dest.  (This copy will normally be coalesced.)
6715     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), destlo)
6716       .addReg(GPRPair0, 0, ARM::gsub_0);
6717     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), desthi)
6718       .addReg(GPRPair0, 0, ARM::gsub_1);
6719   }
6720   AddDefaultPred(MIB);
6721
6722   MI->eraseFromParent();   // The instruction is gone now.
6723
6724   return BB;
6725 }
6726
6727 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6728 /// registers the function context.
6729 void ARMTargetLowering::
6730 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6731                        MachineBasicBlock *DispatchBB, int FI) const {
6732   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6733   DebugLoc dl = MI->getDebugLoc();
6734   MachineFunction *MF = MBB->getParent();
6735   MachineRegisterInfo *MRI = &MF->getRegInfo();
6736   MachineConstantPool *MCP = MF->getConstantPool();
6737   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6738   const Function *F = MF->getFunction();
6739
6740   bool isThumb = Subtarget->isThumb();
6741   bool isThumb2 = Subtarget->isThumb2();
6742
6743   unsigned PCLabelId = AFI->createPICLabelUId();
6744   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6745   ARMConstantPoolValue *CPV =
6746     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6747   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6748
6749   const TargetRegisterClass *TRC = isThumb ?
6750     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6751     (const TargetRegisterClass*)&ARM::GPRRegClass;
6752
6753   // Grab constant pool and fixed stack memory operands.
6754   MachineMemOperand *CPMMO =
6755     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6756                              MachineMemOperand::MOLoad, 4, 4);
6757
6758   MachineMemOperand *FIMMOSt =
6759     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6760                              MachineMemOperand::MOStore, 4, 4);
6761
6762   // Load the address of the dispatch MBB into the jump buffer.
6763   if (isThumb2) {
6764     // Incoming value: jbuf
6765     //   ldr.n  r5, LCPI1_1
6766     //   orr    r5, r5, #1
6767     //   add    r5, pc
6768     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6769     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6770     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6771                    .addConstantPoolIndex(CPI)
6772                    .addMemOperand(CPMMO));
6773     // Set the low bit because of thumb mode.
6774     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6775     AddDefaultCC(
6776       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6777                      .addReg(NewVReg1, RegState::Kill)
6778                      .addImm(0x01)));
6779     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6780     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6781       .addReg(NewVReg2, RegState::Kill)
6782       .addImm(PCLabelId);
6783     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6784                    .addReg(NewVReg3, RegState::Kill)
6785                    .addFrameIndex(FI)
6786                    .addImm(36)  // &jbuf[1] :: pc
6787                    .addMemOperand(FIMMOSt));
6788   } else if (isThumb) {
6789     // Incoming value: jbuf
6790     //   ldr.n  r1, LCPI1_4
6791     //   add    r1, pc
6792     //   mov    r2, #1
6793     //   orrs   r1, r2
6794     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6795     //   str    r1, [r2]
6796     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6797     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6798                    .addConstantPoolIndex(CPI)
6799                    .addMemOperand(CPMMO));
6800     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6801     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6802       .addReg(NewVReg1, RegState::Kill)
6803       .addImm(PCLabelId);
6804     // Set the low bit because of thumb mode.
6805     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6806     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6807                    .addReg(ARM::CPSR, RegState::Define)
6808                    .addImm(1));
6809     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6810     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6811                    .addReg(ARM::CPSR, RegState::Define)
6812                    .addReg(NewVReg2, RegState::Kill)
6813                    .addReg(NewVReg3, RegState::Kill));
6814     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6815     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6816                    .addFrameIndex(FI)
6817                    .addImm(36)); // &jbuf[1] :: pc
6818     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6819                    .addReg(NewVReg4, RegState::Kill)
6820                    .addReg(NewVReg5, RegState::Kill)
6821                    .addImm(0)
6822                    .addMemOperand(FIMMOSt));
6823   } else {
6824     // Incoming value: jbuf
6825     //   ldr  r1, LCPI1_1
6826     //   add  r1, pc, r1
6827     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6828     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6829     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6830                    .addConstantPoolIndex(CPI)
6831                    .addImm(0)
6832                    .addMemOperand(CPMMO));
6833     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6834     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6835                    .addReg(NewVReg1, RegState::Kill)
6836                    .addImm(PCLabelId));
6837     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6838                    .addReg(NewVReg2, RegState::Kill)
6839                    .addFrameIndex(FI)
6840                    .addImm(36)  // &jbuf[1] :: pc
6841                    .addMemOperand(FIMMOSt));
6842   }
6843 }
6844
6845 MachineBasicBlock *ARMTargetLowering::
6846 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6847   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6848   DebugLoc dl = MI->getDebugLoc();
6849   MachineFunction *MF = MBB->getParent();
6850   MachineRegisterInfo *MRI = &MF->getRegInfo();
6851   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6852   MachineFrameInfo *MFI = MF->getFrameInfo();
6853   int FI = MFI->getFunctionContextIndex();
6854
6855   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6856     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6857     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6858
6859   // Get a mapping of the call site numbers to all of the landing pads they're
6860   // associated with.
6861   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6862   unsigned MaxCSNum = 0;
6863   MachineModuleInfo &MMI = MF->getMMI();
6864   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6865        ++BB) {
6866     if (!BB->isLandingPad()) continue;
6867
6868     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6869     // pad.
6870     for (MachineBasicBlock::iterator
6871            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6872       if (!II->isEHLabel()) continue;
6873
6874       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6875       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6876
6877       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6878       for (SmallVectorImpl<unsigned>::iterator
6879              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6880            CSI != CSE; ++CSI) {
6881         CallSiteNumToLPad[*CSI].push_back(BB);
6882         MaxCSNum = std::max(MaxCSNum, *CSI);
6883       }
6884       break;
6885     }
6886   }
6887
6888   // Get an ordered list of the machine basic blocks for the jump table.
6889   std::vector<MachineBasicBlock*> LPadList;
6890   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6891   LPadList.reserve(CallSiteNumToLPad.size());
6892   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6893     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6894     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6895            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6896       LPadList.push_back(*II);
6897       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6898     }
6899   }
6900
6901   assert(!LPadList.empty() &&
6902          "No landing pad destinations for the dispatch jump table!");
6903
6904   // Create the jump table and associated information.
6905   MachineJumpTableInfo *JTI =
6906     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6907   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6908   unsigned UId = AFI->createJumpTableUId();
6909   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6910
6911   // Create the MBBs for the dispatch code.
6912
6913   // Shove the dispatch's address into the return slot in the function context.
6914   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6915   DispatchBB->setIsLandingPad();
6916
6917   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6918   unsigned trap_opcode;
6919   if (Subtarget->isThumb())
6920     trap_opcode = ARM::tTRAP;
6921   else
6922     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6923
6924   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6925   DispatchBB->addSuccessor(TrapBB);
6926
6927   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6928   DispatchBB->addSuccessor(DispContBB);
6929
6930   // Insert and MBBs.
6931   MF->insert(MF->end(), DispatchBB);
6932   MF->insert(MF->end(), DispContBB);
6933   MF->insert(MF->end(), TrapBB);
6934
6935   // Insert code into the entry block that creates and registers the function
6936   // context.
6937   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6938
6939   MachineMemOperand *FIMMOLd =
6940     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6941                              MachineMemOperand::MOLoad |
6942                              MachineMemOperand::MOVolatile, 4, 4);
6943
6944   MachineInstrBuilder MIB;
6945   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6946
6947   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6948   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6949
6950   // Add a register mask with no preserved registers.  This results in all
6951   // registers being marked as clobbered.
6952   MIB.addRegMask(RI.getNoPreservedMask());
6953
6954   unsigned NumLPads = LPadList.size();
6955   if (Subtarget->isThumb2()) {
6956     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6957     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6958                    .addFrameIndex(FI)
6959                    .addImm(4)
6960                    .addMemOperand(FIMMOLd));
6961
6962     if (NumLPads < 256) {
6963       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6964                      .addReg(NewVReg1)
6965                      .addImm(LPadList.size()));
6966     } else {
6967       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6968       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6969                      .addImm(NumLPads & 0xFFFF));
6970
6971       unsigned VReg2 = VReg1;
6972       if ((NumLPads & 0xFFFF0000) != 0) {
6973         VReg2 = MRI->createVirtualRegister(TRC);
6974         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6975                        .addReg(VReg1)
6976                        .addImm(NumLPads >> 16));
6977       }
6978
6979       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6980                      .addReg(NewVReg1)
6981                      .addReg(VReg2));
6982     }
6983
6984     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6985       .addMBB(TrapBB)
6986       .addImm(ARMCC::HI)
6987       .addReg(ARM::CPSR);
6988
6989     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6990     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6991                    .addJumpTableIndex(MJTI)
6992                    .addImm(UId));
6993
6994     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6995     AddDefaultCC(
6996       AddDefaultPred(
6997         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6998         .addReg(NewVReg3, RegState::Kill)
6999         .addReg(NewVReg1)
7000         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7001
7002     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7003       .addReg(NewVReg4, RegState::Kill)
7004       .addReg(NewVReg1)
7005       .addJumpTableIndex(MJTI)
7006       .addImm(UId);
7007   } else if (Subtarget->isThumb()) {
7008     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7009     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7010                    .addFrameIndex(FI)
7011                    .addImm(1)
7012                    .addMemOperand(FIMMOLd));
7013
7014     if (NumLPads < 256) {
7015       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7016                      .addReg(NewVReg1)
7017                      .addImm(NumLPads));
7018     } else {
7019       MachineConstantPool *ConstantPool = MF->getConstantPool();
7020       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7021       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7022
7023       // MachineConstantPool wants an explicit alignment.
7024       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7025       if (Align == 0)
7026         Align = getDataLayout()->getTypeAllocSize(C->getType());
7027       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7028
7029       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7030       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7031                      .addReg(VReg1, RegState::Define)
7032                      .addConstantPoolIndex(Idx));
7033       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7034                      .addReg(NewVReg1)
7035                      .addReg(VReg1));
7036     }
7037
7038     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7039       .addMBB(TrapBB)
7040       .addImm(ARMCC::HI)
7041       .addReg(ARM::CPSR);
7042
7043     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7044     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7045                    .addReg(ARM::CPSR, RegState::Define)
7046                    .addReg(NewVReg1)
7047                    .addImm(2));
7048
7049     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7050     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7051                    .addJumpTableIndex(MJTI)
7052                    .addImm(UId));
7053
7054     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7055     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7056                    .addReg(ARM::CPSR, RegState::Define)
7057                    .addReg(NewVReg2, RegState::Kill)
7058                    .addReg(NewVReg3));
7059
7060     MachineMemOperand *JTMMOLd =
7061       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7062                                MachineMemOperand::MOLoad, 4, 4);
7063
7064     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7065     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7066                    .addReg(NewVReg4, RegState::Kill)
7067                    .addImm(0)
7068                    .addMemOperand(JTMMOLd));
7069
7070     unsigned NewVReg6 = NewVReg5;
7071     if (RelocM == Reloc::PIC_) {
7072       NewVReg6 = MRI->createVirtualRegister(TRC);
7073       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7074                      .addReg(ARM::CPSR, RegState::Define)
7075                      .addReg(NewVReg5, RegState::Kill)
7076                      .addReg(NewVReg3));
7077     }
7078
7079     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7080       .addReg(NewVReg6, RegState::Kill)
7081       .addJumpTableIndex(MJTI)
7082       .addImm(UId);
7083   } else {
7084     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7085     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7086                    .addFrameIndex(FI)
7087                    .addImm(4)
7088                    .addMemOperand(FIMMOLd));
7089
7090     if (NumLPads < 256) {
7091       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7092                      .addReg(NewVReg1)
7093                      .addImm(NumLPads));
7094     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7095       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7096       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7097                      .addImm(NumLPads & 0xFFFF));
7098
7099       unsigned VReg2 = VReg1;
7100       if ((NumLPads & 0xFFFF0000) != 0) {
7101         VReg2 = MRI->createVirtualRegister(TRC);
7102         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7103                        .addReg(VReg1)
7104                        .addImm(NumLPads >> 16));
7105       }
7106
7107       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7108                      .addReg(NewVReg1)
7109                      .addReg(VReg2));
7110     } else {
7111       MachineConstantPool *ConstantPool = MF->getConstantPool();
7112       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7113       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7114
7115       // MachineConstantPool wants an explicit alignment.
7116       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7117       if (Align == 0)
7118         Align = getDataLayout()->getTypeAllocSize(C->getType());
7119       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7120
7121       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7122       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7123                      .addReg(VReg1, RegState::Define)
7124                      .addConstantPoolIndex(Idx)
7125                      .addImm(0));
7126       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7127                      .addReg(NewVReg1)
7128                      .addReg(VReg1, RegState::Kill));
7129     }
7130
7131     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7132       .addMBB(TrapBB)
7133       .addImm(ARMCC::HI)
7134       .addReg(ARM::CPSR);
7135
7136     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7137     AddDefaultCC(
7138       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7139                      .addReg(NewVReg1)
7140                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7141     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7142     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7143                    .addJumpTableIndex(MJTI)
7144                    .addImm(UId));
7145
7146     MachineMemOperand *JTMMOLd =
7147       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7148                                MachineMemOperand::MOLoad, 4, 4);
7149     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7150     AddDefaultPred(
7151       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7152       .addReg(NewVReg3, RegState::Kill)
7153       .addReg(NewVReg4)
7154       .addImm(0)
7155       .addMemOperand(JTMMOLd));
7156
7157     if (RelocM == Reloc::PIC_) {
7158       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7159         .addReg(NewVReg5, RegState::Kill)
7160         .addReg(NewVReg4)
7161         .addJumpTableIndex(MJTI)
7162         .addImm(UId);
7163     } else {
7164       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7165         .addReg(NewVReg5, RegState::Kill)
7166         .addJumpTableIndex(MJTI)
7167         .addImm(UId);
7168     }
7169   }
7170
7171   // Add the jump table entries as successors to the MBB.
7172   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7173   for (std::vector<MachineBasicBlock*>::iterator
7174          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7175     MachineBasicBlock *CurMBB = *I;
7176     if (SeenMBBs.insert(CurMBB))
7177       DispContBB->addSuccessor(CurMBB);
7178   }
7179
7180   // N.B. the order the invoke BBs are processed in doesn't matter here.
7181   const uint16_t *SavedRegs = RI.getCalleeSavedRegs(MF);
7182   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7183   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
7184          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
7185     MachineBasicBlock *BB = *I;
7186
7187     // Remove the landing pad successor from the invoke block and replace it
7188     // with the new dispatch block.
7189     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7190                                                   BB->succ_end());
7191     while (!Successors.empty()) {
7192       MachineBasicBlock *SMBB = Successors.pop_back_val();
7193       if (SMBB->isLandingPad()) {
7194         BB->removeSuccessor(SMBB);
7195         MBBLPads.push_back(SMBB);
7196       }
7197     }
7198
7199     BB->addSuccessor(DispatchBB);
7200
7201     // Find the invoke call and mark all of the callee-saved registers as
7202     // 'implicit defined' so that they're spilled. This prevents code from
7203     // moving instructions to before the EH block, where they will never be
7204     // executed.
7205     for (MachineBasicBlock::reverse_iterator
7206            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7207       if (!II->isCall()) continue;
7208
7209       DenseMap<unsigned, bool> DefRegs;
7210       for (MachineInstr::mop_iterator
7211              OI = II->operands_begin(), OE = II->operands_end();
7212            OI != OE; ++OI) {
7213         if (!OI->isReg()) continue;
7214         DefRegs[OI->getReg()] = true;
7215       }
7216
7217       MachineInstrBuilder MIB(*MF, &*II);
7218
7219       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7220         unsigned Reg = SavedRegs[i];
7221         if (Subtarget->isThumb2() &&
7222             !ARM::tGPRRegClass.contains(Reg) &&
7223             !ARM::hGPRRegClass.contains(Reg))
7224           continue;
7225         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7226           continue;
7227         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7228           continue;
7229         if (!DefRegs[Reg])
7230           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7231       }
7232
7233       break;
7234     }
7235   }
7236
7237   // Mark all former landing pads as non-landing pads. The dispatch is the only
7238   // landing pad now.
7239   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7240          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7241     (*I)->setIsLandingPad(false);
7242
7243   // The instruction is gone now.
7244   MI->eraseFromParent();
7245
7246   return MBB;
7247 }
7248
7249 static
7250 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7251   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7252        E = MBB->succ_end(); I != E; ++I)
7253     if (*I != Succ)
7254       return *I;
7255   llvm_unreachable("Expecting a BB with two successors!");
7256 }
7257
7258 /// Return the load opcode for a given load size. If load size >= 8,
7259 /// neon opcode will be returned.
7260 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7261   if (LdSize >= 8)
7262     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7263                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7264   if (IsThumb1)
7265     return LdSize == 4 ? ARM::tLDRi
7266                        : LdSize == 2 ? ARM::tLDRHi
7267                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7268   if (IsThumb2)
7269     return LdSize == 4 ? ARM::t2LDR_POST
7270                        : LdSize == 2 ? ARM::t2LDRH_POST
7271                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7272   return LdSize == 4 ? ARM::LDR_POST_IMM
7273                      : LdSize == 2 ? ARM::LDRH_POST
7274                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7275 }
7276
7277 /// Return the store opcode for a given store size. If store size >= 8,
7278 /// neon opcode will be returned.
7279 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7280   if (StSize >= 8)
7281     return StSize == 16 ? ARM::VST1q32wb_fixed
7282                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7283   if (IsThumb1)
7284     return StSize == 4 ? ARM::tSTRi
7285                        : StSize == 2 ? ARM::tSTRHi
7286                                      : StSize == 1 ? ARM::tSTRBi : 0;
7287   if (IsThumb2)
7288     return StSize == 4 ? ARM::t2STR_POST
7289                        : StSize == 2 ? ARM::t2STRH_POST
7290                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7291   return StSize == 4 ? ARM::STR_POST_IMM
7292                      : StSize == 2 ? ARM::STRH_POST
7293                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7294 }
7295
7296 /// Emit a post-increment load operation with given size. The instructions
7297 /// will be added to BB at Pos.
7298 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7299                        const TargetInstrInfo *TII, DebugLoc dl,
7300                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7301                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7302   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7303   assert(LdOpc != 0 && "Should have a load opcode");
7304   if (LdSize >= 8) {
7305     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7306                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7307                        .addImm(0));
7308   } else if (IsThumb1) {
7309     // load + update AddrIn
7310     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7311                        .addReg(AddrIn).addImm(0));
7312     MachineInstrBuilder MIB =
7313         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7314     MIB = AddDefaultT1CC(MIB);
7315     MIB.addReg(AddrIn).addImm(LdSize);
7316     AddDefaultPred(MIB);
7317   } else if (IsThumb2) {
7318     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7319                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7320                        .addImm(LdSize));
7321   } else { // arm
7322     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7323                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7324                        .addReg(0).addImm(LdSize));
7325   }
7326 }
7327
7328 /// Emit a post-increment store operation with given size. The instructions
7329 /// will be added to BB at Pos.
7330 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7331                        const TargetInstrInfo *TII, DebugLoc dl,
7332                        unsigned StSize, unsigned Data, unsigned AddrIn,
7333                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7334   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7335   assert(StOpc != 0 && "Should have a store opcode");
7336   if (StSize >= 8) {
7337     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7338                        .addReg(AddrIn).addImm(0).addReg(Data));
7339   } else if (IsThumb1) {
7340     // store + update AddrIn
7341     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7342                        .addReg(AddrIn).addImm(0));
7343     MachineInstrBuilder MIB =
7344         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7345     MIB = AddDefaultT1CC(MIB);
7346     MIB.addReg(AddrIn).addImm(StSize);
7347     AddDefaultPred(MIB);
7348   } else if (IsThumb2) {
7349     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7350                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7351   } else { // arm
7352     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7353                        .addReg(Data).addReg(AddrIn).addReg(0)
7354                        .addImm(StSize));
7355   }
7356 }
7357
7358 MachineBasicBlock *
7359 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7360                                    MachineBasicBlock *BB) const {
7361   // This pseudo instruction has 3 operands: dst, src, size
7362   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7363   // Otherwise, we will generate unrolled scalar copies.
7364   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7365   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7366   MachineFunction::iterator It = BB;
7367   ++It;
7368
7369   unsigned dest = MI->getOperand(0).getReg();
7370   unsigned src = MI->getOperand(1).getReg();
7371   unsigned SizeVal = MI->getOperand(2).getImm();
7372   unsigned Align = MI->getOperand(3).getImm();
7373   DebugLoc dl = MI->getDebugLoc();
7374
7375   MachineFunction *MF = BB->getParent();
7376   MachineRegisterInfo &MRI = MF->getRegInfo();
7377   unsigned UnitSize = 0;
7378   const TargetRegisterClass *TRC = 0;
7379   const TargetRegisterClass *VecTRC = 0;
7380
7381   bool IsThumb1 = Subtarget->isThumb1Only();
7382   bool IsThumb2 = Subtarget->isThumb2();
7383
7384   if (Align & 1) {
7385     UnitSize = 1;
7386   } else if (Align & 2) {
7387     UnitSize = 2;
7388   } else {
7389     // Check whether we can use NEON instructions.
7390     if (!MF->getFunction()->getAttributes().
7391           hasAttribute(AttributeSet::FunctionIndex,
7392                        Attribute::NoImplicitFloat) &&
7393         Subtarget->hasNEON()) {
7394       if ((Align % 16 == 0) && SizeVal >= 16)
7395         UnitSize = 16;
7396       else if ((Align % 8 == 0) && SizeVal >= 8)
7397         UnitSize = 8;
7398     }
7399     // Can't use NEON instructions.
7400     if (UnitSize == 0)
7401       UnitSize = 4;
7402   }
7403
7404   // Select the correct opcode and register class for unit size load/store
7405   bool IsNeon = UnitSize >= 8;
7406   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7407                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7408   if (IsNeon)
7409     VecTRC = UnitSize == 16
7410                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7411                  : UnitSize == 8
7412                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7413                        : 0;
7414
7415   unsigned BytesLeft = SizeVal % UnitSize;
7416   unsigned LoopSize = SizeVal - BytesLeft;
7417
7418   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7419     // Use LDR and STR to copy.
7420     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7421     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7422     unsigned srcIn = src;
7423     unsigned destIn = dest;
7424     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7425       unsigned srcOut = MRI.createVirtualRegister(TRC);
7426       unsigned destOut = MRI.createVirtualRegister(TRC);
7427       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7428       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7429                  IsThumb1, IsThumb2);
7430       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7431                  IsThumb1, IsThumb2);
7432       srcIn = srcOut;
7433       destIn = destOut;
7434     }
7435
7436     // Handle the leftover bytes with LDRB and STRB.
7437     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7438     // [destOut] = STRB_POST(scratch, destIn, 1)
7439     for (unsigned i = 0; i < BytesLeft; i++) {
7440       unsigned srcOut = MRI.createVirtualRegister(TRC);
7441       unsigned destOut = MRI.createVirtualRegister(TRC);
7442       unsigned scratch = MRI.createVirtualRegister(TRC);
7443       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7444                  IsThumb1, IsThumb2);
7445       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7446                  IsThumb1, IsThumb2);
7447       srcIn = srcOut;
7448       destIn = destOut;
7449     }
7450     MI->eraseFromParent();   // The instruction is gone now.
7451     return BB;
7452   }
7453
7454   // Expand the pseudo op to a loop.
7455   // thisMBB:
7456   //   ...
7457   //   movw varEnd, # --> with thumb2
7458   //   movt varEnd, #
7459   //   ldrcp varEnd, idx --> without thumb2
7460   //   fallthrough --> loopMBB
7461   // loopMBB:
7462   //   PHI varPhi, varEnd, varLoop
7463   //   PHI srcPhi, src, srcLoop
7464   //   PHI destPhi, dst, destLoop
7465   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7466   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7467   //   subs varLoop, varPhi, #UnitSize
7468   //   bne loopMBB
7469   //   fallthrough --> exitMBB
7470   // exitMBB:
7471   //   epilogue to handle left-over bytes
7472   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7473   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7474   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7475   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7476   MF->insert(It, loopMBB);
7477   MF->insert(It, exitMBB);
7478
7479   // Transfer the remainder of BB and its successor edges to exitMBB.
7480   exitMBB->splice(exitMBB->begin(), BB,
7481                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7482   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7483
7484   // Load an immediate to varEnd.
7485   unsigned varEnd = MRI.createVirtualRegister(TRC);
7486   if (IsThumb2) {
7487     unsigned Vtmp = varEnd;
7488     if ((LoopSize & 0xFFFF0000) != 0)
7489       Vtmp = MRI.createVirtualRegister(TRC);
7490     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7491                        .addImm(LoopSize & 0xFFFF));
7492
7493     if ((LoopSize & 0xFFFF0000) != 0)
7494       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7495                          .addReg(Vtmp).addImm(LoopSize >> 16));
7496   } else {
7497     MachineConstantPool *ConstantPool = MF->getConstantPool();
7498     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7499     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7500
7501     // MachineConstantPool wants an explicit alignment.
7502     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7503     if (Align == 0)
7504       Align = getDataLayout()->getTypeAllocSize(C->getType());
7505     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7506
7507     if (IsThumb1)
7508       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7509           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7510     else
7511       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7512           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7513   }
7514   BB->addSuccessor(loopMBB);
7515
7516   // Generate the loop body:
7517   //   varPhi = PHI(varLoop, varEnd)
7518   //   srcPhi = PHI(srcLoop, src)
7519   //   destPhi = PHI(destLoop, dst)
7520   MachineBasicBlock *entryBB = BB;
7521   BB = loopMBB;
7522   unsigned varLoop = MRI.createVirtualRegister(TRC);
7523   unsigned varPhi = MRI.createVirtualRegister(TRC);
7524   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7525   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7526   unsigned destLoop = MRI.createVirtualRegister(TRC);
7527   unsigned destPhi = MRI.createVirtualRegister(TRC);
7528
7529   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7530     .addReg(varLoop).addMBB(loopMBB)
7531     .addReg(varEnd).addMBB(entryBB);
7532   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7533     .addReg(srcLoop).addMBB(loopMBB)
7534     .addReg(src).addMBB(entryBB);
7535   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7536     .addReg(destLoop).addMBB(loopMBB)
7537     .addReg(dest).addMBB(entryBB);
7538
7539   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7540   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7541   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7542   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7543              IsThumb1, IsThumb2);
7544   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7545              IsThumb1, IsThumb2);
7546
7547   // Decrement loop variable by UnitSize.
7548   if (IsThumb1) {
7549     MachineInstrBuilder MIB =
7550         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7551     MIB = AddDefaultT1CC(MIB);
7552     MIB.addReg(varPhi).addImm(UnitSize);
7553     AddDefaultPred(MIB);
7554   } else {
7555     MachineInstrBuilder MIB =
7556         BuildMI(*BB, BB->end(), dl,
7557                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7558     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7559     MIB->getOperand(5).setReg(ARM::CPSR);
7560     MIB->getOperand(5).setIsDef(true);
7561   }
7562   BuildMI(*BB, BB->end(), dl,
7563           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7564       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7565
7566   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7567   BB->addSuccessor(loopMBB);
7568   BB->addSuccessor(exitMBB);
7569
7570   // Add epilogue to handle BytesLeft.
7571   BB = exitMBB;
7572   MachineInstr *StartOfExit = exitMBB->begin();
7573
7574   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7575   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7576   unsigned srcIn = srcLoop;
7577   unsigned destIn = destLoop;
7578   for (unsigned i = 0; i < BytesLeft; i++) {
7579     unsigned srcOut = MRI.createVirtualRegister(TRC);
7580     unsigned destOut = MRI.createVirtualRegister(TRC);
7581     unsigned scratch = MRI.createVirtualRegister(TRC);
7582     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7583                IsThumb1, IsThumb2);
7584     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7585                IsThumb1, IsThumb2);
7586     srcIn = srcOut;
7587     destIn = destOut;
7588   }
7589
7590   MI->eraseFromParent();   // The instruction is gone now.
7591   return BB;
7592 }
7593
7594 MachineBasicBlock *
7595 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7596                                                MachineBasicBlock *BB) const {
7597   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7598   DebugLoc dl = MI->getDebugLoc();
7599   bool isThumb2 = Subtarget->isThumb2();
7600   switch (MI->getOpcode()) {
7601   default: {
7602     MI->dump();
7603     llvm_unreachable("Unexpected instr type to insert");
7604   }
7605   // The Thumb2 pre-indexed stores have the same MI operands, they just
7606   // define them differently in the .td files from the isel patterns, so
7607   // they need pseudos.
7608   case ARM::t2STR_preidx:
7609     MI->setDesc(TII->get(ARM::t2STR_PRE));
7610     return BB;
7611   case ARM::t2STRB_preidx:
7612     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7613     return BB;
7614   case ARM::t2STRH_preidx:
7615     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7616     return BB;
7617
7618   case ARM::STRi_preidx:
7619   case ARM::STRBi_preidx: {
7620     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7621       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7622     // Decode the offset.
7623     unsigned Offset = MI->getOperand(4).getImm();
7624     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7625     Offset = ARM_AM::getAM2Offset(Offset);
7626     if (isSub)
7627       Offset = -Offset;
7628
7629     MachineMemOperand *MMO = *MI->memoperands_begin();
7630     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7631       .addOperand(MI->getOperand(0))  // Rn_wb
7632       .addOperand(MI->getOperand(1))  // Rt
7633       .addOperand(MI->getOperand(2))  // Rn
7634       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7635       .addOperand(MI->getOperand(5))  // pred
7636       .addOperand(MI->getOperand(6))
7637       .addMemOperand(MMO);
7638     MI->eraseFromParent();
7639     return BB;
7640   }
7641   case ARM::STRr_preidx:
7642   case ARM::STRBr_preidx:
7643   case ARM::STRH_preidx: {
7644     unsigned NewOpc;
7645     switch (MI->getOpcode()) {
7646     default: llvm_unreachable("unexpected opcode!");
7647     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7648     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7649     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7650     }
7651     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7652     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7653       MIB.addOperand(MI->getOperand(i));
7654     MI->eraseFromParent();
7655     return BB;
7656   }
7657   case ARM::ATOMIC_LOAD_ADD_I8:
7658      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7659   case ARM::ATOMIC_LOAD_ADD_I16:
7660      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7661   case ARM::ATOMIC_LOAD_ADD_I32:
7662      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr);
7663
7664   case ARM::ATOMIC_LOAD_AND_I8:
7665      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7666   case ARM::ATOMIC_LOAD_AND_I16:
7667      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7668   case ARM::ATOMIC_LOAD_AND_I32:
7669      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7670
7671   case ARM::ATOMIC_LOAD_OR_I8:
7672      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7673   case ARM::ATOMIC_LOAD_OR_I16:
7674      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7675   case ARM::ATOMIC_LOAD_OR_I32:
7676      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7677
7678   case ARM::ATOMIC_LOAD_XOR_I8:
7679      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7680   case ARM::ATOMIC_LOAD_XOR_I16:
7681      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7682   case ARM::ATOMIC_LOAD_XOR_I32:
7683      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7684
7685   case ARM::ATOMIC_LOAD_NAND_I8:
7686      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7687   case ARM::ATOMIC_LOAD_NAND_I16:
7688      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7689   case ARM::ATOMIC_LOAD_NAND_I32:
7690      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2BICrr : ARM::BICrr);
7691
7692   case ARM::ATOMIC_LOAD_SUB_I8:
7693      return EmitAtomicBinary(MI, BB, 1, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7694   case ARM::ATOMIC_LOAD_SUB_I16:
7695      return EmitAtomicBinary(MI, BB, 2, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7696   case ARM::ATOMIC_LOAD_SUB_I32:
7697      return EmitAtomicBinary(MI, BB, 4, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr);
7698
7699   case ARM::ATOMIC_LOAD_MIN_I8:
7700      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::LT);
7701   case ARM::ATOMIC_LOAD_MIN_I16:
7702      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::LT);
7703   case ARM::ATOMIC_LOAD_MIN_I32:
7704      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::LT);
7705
7706   case ARM::ATOMIC_LOAD_MAX_I8:
7707      return EmitAtomicBinaryMinMax(MI, BB, 1, true, ARMCC::GT);
7708   case ARM::ATOMIC_LOAD_MAX_I16:
7709      return EmitAtomicBinaryMinMax(MI, BB, 2, true, ARMCC::GT);
7710   case ARM::ATOMIC_LOAD_MAX_I32:
7711      return EmitAtomicBinaryMinMax(MI, BB, 4, true, ARMCC::GT);
7712
7713   case ARM::ATOMIC_LOAD_UMIN_I8:
7714      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::LO);
7715   case ARM::ATOMIC_LOAD_UMIN_I16:
7716      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::LO);
7717   case ARM::ATOMIC_LOAD_UMIN_I32:
7718      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::LO);
7719
7720   case ARM::ATOMIC_LOAD_UMAX_I8:
7721      return EmitAtomicBinaryMinMax(MI, BB, 1, false, ARMCC::HI);
7722   case ARM::ATOMIC_LOAD_UMAX_I16:
7723      return EmitAtomicBinaryMinMax(MI, BB, 2, false, ARMCC::HI);
7724   case ARM::ATOMIC_LOAD_UMAX_I32:
7725      return EmitAtomicBinaryMinMax(MI, BB, 4, false, ARMCC::HI);
7726
7727   case ARM::ATOMIC_SWAP_I8:  return EmitAtomicBinary(MI, BB, 1, 0);
7728   case ARM::ATOMIC_SWAP_I16: return EmitAtomicBinary(MI, BB, 2, 0);
7729   case ARM::ATOMIC_SWAP_I32: return EmitAtomicBinary(MI, BB, 4, 0);
7730
7731   case ARM::ATOMIC_CMP_SWAP_I8:  return EmitAtomicCmpSwap(MI, BB, 1);
7732   case ARM::ATOMIC_CMP_SWAP_I16: return EmitAtomicCmpSwap(MI, BB, 2);
7733   case ARM::ATOMIC_CMP_SWAP_I32: return EmitAtomicCmpSwap(MI, BB, 4);
7734
7735   case ARM::ATOMIC_LOAD_I64:
7736     return EmitAtomicLoad64(MI, BB);
7737
7738   case ARM::ATOMIC_LOAD_ADD_I64:
7739     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ADDrr : ARM::ADDrr,
7740                               isThumb2 ? ARM::t2ADCrr : ARM::ADCrr,
7741                               /*NeedsCarry*/ true);
7742   case ARM::ATOMIC_LOAD_SUB_I64:
7743     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7744                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7745                               /*NeedsCarry*/ true);
7746   case ARM::ATOMIC_LOAD_OR_I64:
7747     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ORRrr : ARM::ORRrr,
7748                               isThumb2 ? ARM::t2ORRrr : ARM::ORRrr);
7749   case ARM::ATOMIC_LOAD_XOR_I64:
7750     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2EORrr : ARM::EORrr,
7751                               isThumb2 ? ARM::t2EORrr : ARM::EORrr);
7752   case ARM::ATOMIC_LOAD_AND_I64:
7753     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2ANDrr : ARM::ANDrr,
7754                               isThumb2 ? ARM::t2ANDrr : ARM::ANDrr);
7755   case ARM::ATOMIC_SWAP_I64:
7756     return EmitAtomicBinary64(MI, BB, 0, 0, false);
7757   case ARM::ATOMIC_CMP_SWAP_I64:
7758     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7759                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7760                               /*NeedsCarry*/ false, /*IsCmpxchg*/true);
7761   case ARM::ATOMIC_LOAD_MIN_I64:
7762     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7763                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7764                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7765                               /*IsMinMax*/ true, ARMCC::LT);
7766   case ARM::ATOMIC_LOAD_MAX_I64:
7767     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7768                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7769                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7770                               /*IsMinMax*/ true, ARMCC::GE);
7771   case ARM::ATOMIC_LOAD_UMIN_I64:
7772     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7773                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7774                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7775                               /*IsMinMax*/ true, ARMCC::LO);
7776   case ARM::ATOMIC_LOAD_UMAX_I64:
7777     return EmitAtomicBinary64(MI, BB, isThumb2 ? ARM::t2SUBrr : ARM::SUBrr,
7778                               isThumb2 ? ARM::t2SBCrr : ARM::SBCrr,
7779                               /*NeedsCarry*/ true, /*IsCmpxchg*/false,
7780                               /*IsMinMax*/ true, ARMCC::HS);
7781
7782   case ARM::tMOVCCr_pseudo: {
7783     // To "insert" a SELECT_CC instruction, we actually have to insert the
7784     // diamond control-flow pattern.  The incoming instruction knows the
7785     // destination vreg to set, the condition code register to branch on, the
7786     // true/false values to select between, and a branch opcode to use.
7787     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7788     MachineFunction::iterator It = BB;
7789     ++It;
7790
7791     //  thisMBB:
7792     //  ...
7793     //   TrueVal = ...
7794     //   cmpTY ccX, r1, r2
7795     //   bCC copy1MBB
7796     //   fallthrough --> copy0MBB
7797     MachineBasicBlock *thisMBB  = BB;
7798     MachineFunction *F = BB->getParent();
7799     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7800     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7801     F->insert(It, copy0MBB);
7802     F->insert(It, sinkMBB);
7803
7804     // Transfer the remainder of BB and its successor edges to sinkMBB.
7805     sinkMBB->splice(sinkMBB->begin(), BB,
7806                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7807     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7808
7809     BB->addSuccessor(copy0MBB);
7810     BB->addSuccessor(sinkMBB);
7811
7812     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7813       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7814
7815     //  copy0MBB:
7816     //   %FalseValue = ...
7817     //   # fallthrough to sinkMBB
7818     BB = copy0MBB;
7819
7820     // Update machine-CFG edges
7821     BB->addSuccessor(sinkMBB);
7822
7823     //  sinkMBB:
7824     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7825     //  ...
7826     BB = sinkMBB;
7827     BuildMI(*BB, BB->begin(), dl,
7828             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7829       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7830       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7831
7832     MI->eraseFromParent();   // The pseudo instruction is gone now.
7833     return BB;
7834   }
7835
7836   case ARM::BCCi64:
7837   case ARM::BCCZi64: {
7838     // If there is an unconditional branch to the other successor, remove it.
7839     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7840
7841     // Compare both parts that make up the double comparison separately for
7842     // equality.
7843     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7844
7845     unsigned LHS1 = MI->getOperand(1).getReg();
7846     unsigned LHS2 = MI->getOperand(2).getReg();
7847     if (RHSisZero) {
7848       AddDefaultPred(BuildMI(BB, dl,
7849                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7850                      .addReg(LHS1).addImm(0));
7851       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7852         .addReg(LHS2).addImm(0)
7853         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7854     } else {
7855       unsigned RHS1 = MI->getOperand(3).getReg();
7856       unsigned RHS2 = MI->getOperand(4).getReg();
7857       AddDefaultPred(BuildMI(BB, dl,
7858                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7859                      .addReg(LHS1).addReg(RHS1));
7860       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7861         .addReg(LHS2).addReg(RHS2)
7862         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7863     }
7864
7865     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7866     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7867     if (MI->getOperand(0).getImm() == ARMCC::NE)
7868       std::swap(destMBB, exitMBB);
7869
7870     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7871       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7872     if (isThumb2)
7873       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7874     else
7875       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7876
7877     MI->eraseFromParent();   // The pseudo instruction is gone now.
7878     return BB;
7879   }
7880
7881   case ARM::Int_eh_sjlj_setjmp:
7882   case ARM::Int_eh_sjlj_setjmp_nofp:
7883   case ARM::tInt_eh_sjlj_setjmp:
7884   case ARM::t2Int_eh_sjlj_setjmp:
7885   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7886     EmitSjLjDispatchBlock(MI, BB);
7887     return BB;
7888
7889   case ARM::ABS:
7890   case ARM::t2ABS: {
7891     // To insert an ABS instruction, we have to insert the
7892     // diamond control-flow pattern.  The incoming instruction knows the
7893     // source vreg to test against 0, the destination vreg to set,
7894     // the condition code register to branch on, the
7895     // true/false values to select between, and a branch opcode to use.
7896     // It transforms
7897     //     V1 = ABS V0
7898     // into
7899     //     V2 = MOVS V0
7900     //     BCC                      (branch to SinkBB if V0 >= 0)
7901     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7902     //     SinkBB: V1 = PHI(V2, V3)
7903     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7904     MachineFunction::iterator BBI = BB;
7905     ++BBI;
7906     MachineFunction *Fn = BB->getParent();
7907     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7908     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7909     Fn->insert(BBI, RSBBB);
7910     Fn->insert(BBI, SinkBB);
7911
7912     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7913     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7914     bool isThumb2 = Subtarget->isThumb2();
7915     MachineRegisterInfo &MRI = Fn->getRegInfo();
7916     // In Thumb mode S must not be specified if source register is the SP or
7917     // PC and if destination register is the SP, so restrict register class
7918     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7919       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7920       (const TargetRegisterClass*)&ARM::GPRRegClass);
7921
7922     // Transfer the remainder of BB and its successor edges to sinkMBB.
7923     SinkBB->splice(SinkBB->begin(), BB,
7924                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7925     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7926
7927     BB->addSuccessor(RSBBB);
7928     BB->addSuccessor(SinkBB);
7929
7930     // fall through to SinkMBB
7931     RSBBB->addSuccessor(SinkBB);
7932
7933     // insert a cmp at the end of BB
7934     AddDefaultPred(BuildMI(BB, dl,
7935                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7936                    .addReg(ABSSrcReg).addImm(0));
7937
7938     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7939     BuildMI(BB, dl,
7940       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7941       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7942
7943     // insert rsbri in RSBBB
7944     // Note: BCC and rsbri will be converted into predicated rsbmi
7945     // by if-conversion pass
7946     BuildMI(*RSBBB, RSBBB->begin(), dl,
7947       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7948       .addReg(ABSSrcReg, RegState::Kill)
7949       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7950
7951     // insert PHI in SinkBB,
7952     // reuse ABSDstReg to not change uses of ABS instruction
7953     BuildMI(*SinkBB, SinkBB->begin(), dl,
7954       TII->get(ARM::PHI), ABSDstReg)
7955       .addReg(NewRsbDstReg).addMBB(RSBBB)
7956       .addReg(ABSSrcReg).addMBB(BB);
7957
7958     // remove ABS instruction
7959     MI->eraseFromParent();
7960
7961     // return last added BB
7962     return SinkBB;
7963   }
7964   case ARM::COPY_STRUCT_BYVAL_I32:
7965     ++NumLoopByVals;
7966     return EmitStructByval(MI, BB);
7967   }
7968 }
7969
7970 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7971                                                       SDNode *Node) const {
7972   if (!MI->hasPostISelHook()) {
7973     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7974            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7975     return;
7976   }
7977
7978   const MCInstrDesc *MCID = &MI->getDesc();
7979   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7980   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7981   // operand is still set to noreg. If needed, set the optional operand's
7982   // register to CPSR, and remove the redundant implicit def.
7983   //
7984   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7985
7986   // Rename pseudo opcodes.
7987   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7988   if (NewOpc) {
7989     const ARMBaseInstrInfo *TII =
7990       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7991     MCID = &TII->get(NewOpc);
7992
7993     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7994            "converted opcode should be the same except for cc_out");
7995
7996     MI->setDesc(*MCID);
7997
7998     // Add the optional cc_out operand
7999     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8000   }
8001   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8002
8003   // Any ARM instruction that sets the 's' bit should specify an optional
8004   // "cc_out" operand in the last operand position.
8005   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8006     assert(!NewOpc && "Optional cc_out operand required");
8007     return;
8008   }
8009   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8010   // since we already have an optional CPSR def.
8011   bool definesCPSR = false;
8012   bool deadCPSR = false;
8013   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8014        i != e; ++i) {
8015     const MachineOperand &MO = MI->getOperand(i);
8016     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8017       definesCPSR = true;
8018       if (MO.isDead())
8019         deadCPSR = true;
8020       MI->RemoveOperand(i);
8021       break;
8022     }
8023   }
8024   if (!definesCPSR) {
8025     assert(!NewOpc && "Optional cc_out operand required");
8026     return;
8027   }
8028   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8029   if (deadCPSR) {
8030     assert(!MI->getOperand(ccOutIdx).getReg() &&
8031            "expect uninitialized optional cc_out operand");
8032     return;
8033   }
8034
8035   // If this instruction was defined with an optional CPSR def and its dag node
8036   // had a live implicit CPSR def, then activate the optional CPSR def.
8037   MachineOperand &MO = MI->getOperand(ccOutIdx);
8038   MO.setReg(ARM::CPSR);
8039   MO.setIsDef(true);
8040 }
8041
8042 //===----------------------------------------------------------------------===//
8043 //                           ARM Optimization Hooks
8044 //===----------------------------------------------------------------------===//
8045
8046 // Helper function that checks if N is a null or all ones constant.
8047 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8048   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8049   if (!C)
8050     return false;
8051   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8052 }
8053
8054 // Return true if N is conditionally 0 or all ones.
8055 // Detects these expressions where cc is an i1 value:
8056 //
8057 //   (select cc 0, y)   [AllOnes=0]
8058 //   (select cc y, 0)   [AllOnes=0]
8059 //   (zext cc)          [AllOnes=0]
8060 //   (sext cc)          [AllOnes=0/1]
8061 //   (select cc -1, y)  [AllOnes=1]
8062 //   (select cc y, -1)  [AllOnes=1]
8063 //
8064 // Invert is set when N is the null/all ones constant when CC is false.
8065 // OtherOp is set to the alternative value of N.
8066 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8067                                        SDValue &CC, bool &Invert,
8068                                        SDValue &OtherOp,
8069                                        SelectionDAG &DAG) {
8070   switch (N->getOpcode()) {
8071   default: return false;
8072   case ISD::SELECT: {
8073     CC = N->getOperand(0);
8074     SDValue N1 = N->getOperand(1);
8075     SDValue N2 = N->getOperand(2);
8076     if (isZeroOrAllOnes(N1, AllOnes)) {
8077       Invert = false;
8078       OtherOp = N2;
8079       return true;
8080     }
8081     if (isZeroOrAllOnes(N2, AllOnes)) {
8082       Invert = true;
8083       OtherOp = N1;
8084       return true;
8085     }
8086     return false;
8087   }
8088   case ISD::ZERO_EXTEND:
8089     // (zext cc) can never be the all ones value.
8090     if (AllOnes)
8091       return false;
8092     // Fall through.
8093   case ISD::SIGN_EXTEND: {
8094     EVT VT = N->getValueType(0);
8095     CC = N->getOperand(0);
8096     if (CC.getValueType() != MVT::i1)
8097       return false;
8098     Invert = !AllOnes;
8099     if (AllOnes)
8100       // When looking for an AllOnes constant, N is an sext, and the 'other'
8101       // value is 0.
8102       OtherOp = DAG.getConstant(0, VT);
8103     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8104       // When looking for a 0 constant, N can be zext or sext.
8105       OtherOp = DAG.getConstant(1, VT);
8106     else
8107       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
8108     return true;
8109   }
8110   }
8111 }
8112
8113 // Combine a constant select operand into its use:
8114 //
8115 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8116 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8117 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8118 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8119 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8120 //
8121 // The transform is rejected if the select doesn't have a constant operand that
8122 // is null, or all ones when AllOnes is set.
8123 //
8124 // Also recognize sext/zext from i1:
8125 //
8126 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8127 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8128 //
8129 // These transformations eventually create predicated instructions.
8130 //
8131 // @param N       The node to transform.
8132 // @param Slct    The N operand that is a select.
8133 // @param OtherOp The other N operand (x above).
8134 // @param DCI     Context.
8135 // @param AllOnes Require the select constant to be all ones instead of null.
8136 // @returns The new node, or SDValue() on failure.
8137 static
8138 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8139                             TargetLowering::DAGCombinerInfo &DCI,
8140                             bool AllOnes = false) {
8141   SelectionDAG &DAG = DCI.DAG;
8142   EVT VT = N->getValueType(0);
8143   SDValue NonConstantVal;
8144   SDValue CCOp;
8145   bool SwapSelectOps;
8146   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8147                                   NonConstantVal, DAG))
8148     return SDValue();
8149
8150   // Slct is now know to be the desired identity constant when CC is true.
8151   SDValue TrueVal = OtherOp;
8152   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8153                                  OtherOp, NonConstantVal);
8154   // Unless SwapSelectOps says CC should be false.
8155   if (SwapSelectOps)
8156     std::swap(TrueVal, FalseVal);
8157
8158   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8159                      CCOp, TrueVal, FalseVal);
8160 }
8161
8162 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8163 static
8164 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8165                                        TargetLowering::DAGCombinerInfo &DCI) {
8166   SDValue N0 = N->getOperand(0);
8167   SDValue N1 = N->getOperand(1);
8168   if (N0.getNode()->hasOneUse()) {
8169     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8170     if (Result.getNode())
8171       return Result;
8172   }
8173   if (N1.getNode()->hasOneUse()) {
8174     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8175     if (Result.getNode())
8176       return Result;
8177   }
8178   return SDValue();
8179 }
8180
8181 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8182 // (only after legalization).
8183 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8184                                  TargetLowering::DAGCombinerInfo &DCI,
8185                                  const ARMSubtarget *Subtarget) {
8186
8187   // Only perform optimization if after legalize, and if NEON is available. We
8188   // also expected both operands to be BUILD_VECTORs.
8189   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8190       || N0.getOpcode() != ISD::BUILD_VECTOR
8191       || N1.getOpcode() != ISD::BUILD_VECTOR)
8192     return SDValue();
8193
8194   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8195   EVT VT = N->getValueType(0);
8196   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8197     return SDValue();
8198
8199   // Check that the vector operands are of the right form.
8200   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8201   // operands, where N is the size of the formed vector.
8202   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8203   // index such that we have a pair wise add pattern.
8204
8205   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8206   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8207     return SDValue();
8208   SDValue Vec = N0->getOperand(0)->getOperand(0);
8209   SDNode *V = Vec.getNode();
8210   unsigned nextIndex = 0;
8211
8212   // For each operands to the ADD which are BUILD_VECTORs,
8213   // check to see if each of their operands are an EXTRACT_VECTOR with
8214   // the same vector and appropriate index.
8215   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8216     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8217         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8218
8219       SDValue ExtVec0 = N0->getOperand(i);
8220       SDValue ExtVec1 = N1->getOperand(i);
8221
8222       // First operand is the vector, verify its the same.
8223       if (V != ExtVec0->getOperand(0).getNode() ||
8224           V != ExtVec1->getOperand(0).getNode())
8225         return SDValue();
8226
8227       // Second is the constant, verify its correct.
8228       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8229       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8230
8231       // For the constant, we want to see all the even or all the odd.
8232       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8233           || C1->getZExtValue() != nextIndex+1)
8234         return SDValue();
8235
8236       // Increment index.
8237       nextIndex+=2;
8238     } else
8239       return SDValue();
8240   }
8241
8242   // Create VPADDL node.
8243   SelectionDAG &DAG = DCI.DAG;
8244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8245
8246   // Build operand list.
8247   SmallVector<SDValue, 8> Ops;
8248   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
8249                                 TLI.getPointerTy()));
8250
8251   // Input is the vector.
8252   Ops.push_back(Vec);
8253
8254   // Get widened type and narrowed type.
8255   MVT widenType;
8256   unsigned numElem = VT.getVectorNumElements();
8257   switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
8258     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8259     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8260     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8261     default:
8262       llvm_unreachable("Invalid vector element type for padd optimization.");
8263   }
8264
8265   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8266                             widenType, &Ops[0], Ops.size());
8267   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, tmp);
8268 }
8269
8270 static SDValue findMUL_LOHI(SDValue V) {
8271   if (V->getOpcode() == ISD::UMUL_LOHI ||
8272       V->getOpcode() == ISD::SMUL_LOHI)
8273     return V;
8274   return SDValue();
8275 }
8276
8277 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8278                                      TargetLowering::DAGCombinerInfo &DCI,
8279                                      const ARMSubtarget *Subtarget) {
8280
8281   if (Subtarget->isThumb1Only()) return SDValue();
8282
8283   // Only perform the checks after legalize when the pattern is available.
8284   if (DCI.isBeforeLegalize()) return SDValue();
8285
8286   // Look for multiply add opportunities.
8287   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8288   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8289   // a glue link from the first add to the second add.
8290   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8291   // a S/UMLAL instruction.
8292   //          loAdd   UMUL_LOHI
8293   //            \    / :lo    \ :hi
8294   //             \  /          \          [no multiline comment]
8295   //              ADDC         |  hiAdd
8296   //                 \ :glue  /  /
8297   //                  \      /  /
8298   //                    ADDE
8299   //
8300   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8301   SDValue AddcOp0 = AddcNode->getOperand(0);
8302   SDValue AddcOp1 = AddcNode->getOperand(1);
8303
8304   // Check if the two operands are from the same mul_lohi node.
8305   if (AddcOp0.getNode() == AddcOp1.getNode())
8306     return SDValue();
8307
8308   assert(AddcNode->getNumValues() == 2 &&
8309          AddcNode->getValueType(0) == MVT::i32 &&
8310          "Expect ADDC with two result values. First: i32");
8311
8312   // Check that we have a glued ADDC node.
8313   if (AddcNode->getValueType(1) != MVT::Glue)
8314     return SDValue();
8315
8316   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8317   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8318       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8319       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8320       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8321     return SDValue();
8322
8323   // Look for the glued ADDE.
8324   SDNode* AddeNode = AddcNode->getGluedUser();
8325   if (AddeNode == NULL)
8326     return SDValue();
8327
8328   // Make sure it is really an ADDE.
8329   if (AddeNode->getOpcode() != ISD::ADDE)
8330     return SDValue();
8331
8332   assert(AddeNode->getNumOperands() == 3 &&
8333          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8334          "ADDE node has the wrong inputs");
8335
8336   // Check for the triangle shape.
8337   SDValue AddeOp0 = AddeNode->getOperand(0);
8338   SDValue AddeOp1 = AddeNode->getOperand(1);
8339
8340   // Make sure that the ADDE operands are not coming from the same node.
8341   if (AddeOp0.getNode() == AddeOp1.getNode())
8342     return SDValue();
8343
8344   // Find the MUL_LOHI node walking up ADDE's operands.
8345   bool IsLeftOperandMUL = false;
8346   SDValue MULOp = findMUL_LOHI(AddeOp0);
8347   if (MULOp == SDValue())
8348    MULOp = findMUL_LOHI(AddeOp1);
8349   else
8350     IsLeftOperandMUL = true;
8351   if (MULOp == SDValue())
8352      return SDValue();
8353
8354   // Figure out the right opcode.
8355   unsigned Opc = MULOp->getOpcode();
8356   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8357
8358   // Figure out the high and low input values to the MLAL node.
8359   SDValue* HiMul = &MULOp;
8360   SDValue* HiAdd = NULL;
8361   SDValue* LoMul = NULL;
8362   SDValue* LowAdd = NULL;
8363
8364   if (IsLeftOperandMUL)
8365     HiAdd = &AddeOp1;
8366   else
8367     HiAdd = &AddeOp0;
8368
8369
8370   if (AddcOp0->getOpcode() == Opc) {
8371     LoMul = &AddcOp0;
8372     LowAdd = &AddcOp1;
8373   }
8374   if (AddcOp1->getOpcode() == Opc) {
8375     LoMul = &AddcOp1;
8376     LowAdd = &AddcOp0;
8377   }
8378
8379   if (LoMul == NULL)
8380     return SDValue();
8381
8382   if (LoMul->getNode() != HiMul->getNode())
8383     return SDValue();
8384
8385   // Create the merged node.
8386   SelectionDAG &DAG = DCI.DAG;
8387
8388   // Build operand list.
8389   SmallVector<SDValue, 8> Ops;
8390   Ops.push_back(LoMul->getOperand(0));
8391   Ops.push_back(LoMul->getOperand(1));
8392   Ops.push_back(*LowAdd);
8393   Ops.push_back(*HiAdd);
8394
8395   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8396                                  DAG.getVTList(MVT::i32, MVT::i32),
8397                                  &Ops[0], Ops.size());
8398
8399   // Replace the ADDs' nodes uses by the MLA node's values.
8400   SDValue HiMLALResult(MLALNode.getNode(), 1);
8401   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8402
8403   SDValue LoMLALResult(MLALNode.getNode(), 0);
8404   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8405
8406   // Return original node to notify the driver to stop replacing.
8407   SDValue resNode(AddcNode, 0);
8408   return resNode;
8409 }
8410
8411 /// PerformADDCCombine - Target-specific dag combine transform from
8412 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8413 static SDValue PerformADDCCombine(SDNode *N,
8414                                  TargetLowering::DAGCombinerInfo &DCI,
8415                                  const ARMSubtarget *Subtarget) {
8416
8417   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8418
8419 }
8420
8421 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8422 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8423 /// called with the default operands, and if that fails, with commuted
8424 /// operands.
8425 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8426                                           TargetLowering::DAGCombinerInfo &DCI,
8427                                           const ARMSubtarget *Subtarget){
8428
8429   // Attempt to create vpaddl for this add.
8430   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8431   if (Result.getNode())
8432     return Result;
8433
8434   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8435   if (N0.getNode()->hasOneUse()) {
8436     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8437     if (Result.getNode()) return Result;
8438   }
8439   return SDValue();
8440 }
8441
8442 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8443 ///
8444 static SDValue PerformADDCombine(SDNode *N,
8445                                  TargetLowering::DAGCombinerInfo &DCI,
8446                                  const ARMSubtarget *Subtarget) {
8447   SDValue N0 = N->getOperand(0);
8448   SDValue N1 = N->getOperand(1);
8449
8450   // First try with the default operand order.
8451   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8452   if (Result.getNode())
8453     return Result;
8454
8455   // If that didn't work, try again with the operands commuted.
8456   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8457 }
8458
8459 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8460 ///
8461 static SDValue PerformSUBCombine(SDNode *N,
8462                                  TargetLowering::DAGCombinerInfo &DCI) {
8463   SDValue N0 = N->getOperand(0);
8464   SDValue N1 = N->getOperand(1);
8465
8466   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8467   if (N1.getNode()->hasOneUse()) {
8468     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8469     if (Result.getNode()) return Result;
8470   }
8471
8472   return SDValue();
8473 }
8474
8475 /// PerformVMULCombine
8476 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8477 /// special multiplier accumulator forwarding.
8478 ///   vmul d3, d0, d2
8479 ///   vmla d3, d1, d2
8480 /// is faster than
8481 ///   vadd d3, d0, d1
8482 ///   vmul d3, d3, d2
8483 //  However, for (A + B) * (A + B),
8484 //    vadd d2, d0, d1
8485 //    vmul d3, d0, d2
8486 //    vmla d3, d1, d2
8487 //  is slower than
8488 //    vadd d2, d0, d1
8489 //    vmul d3, d2, d2
8490 static SDValue PerformVMULCombine(SDNode *N,
8491                                   TargetLowering::DAGCombinerInfo &DCI,
8492                                   const ARMSubtarget *Subtarget) {
8493   if (!Subtarget->hasVMLxForwarding())
8494     return SDValue();
8495
8496   SelectionDAG &DAG = DCI.DAG;
8497   SDValue N0 = N->getOperand(0);
8498   SDValue N1 = N->getOperand(1);
8499   unsigned Opcode = N0.getOpcode();
8500   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8501       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8502     Opcode = N1.getOpcode();
8503     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8504         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8505       return SDValue();
8506     std::swap(N0, N1);
8507   }
8508
8509   if (N0 == N1)
8510     return SDValue();
8511
8512   EVT VT = N->getValueType(0);
8513   SDLoc DL(N);
8514   SDValue N00 = N0->getOperand(0);
8515   SDValue N01 = N0->getOperand(1);
8516   return DAG.getNode(Opcode, DL, VT,
8517                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8518                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8519 }
8520
8521 static SDValue PerformMULCombine(SDNode *N,
8522                                  TargetLowering::DAGCombinerInfo &DCI,
8523                                  const ARMSubtarget *Subtarget) {
8524   SelectionDAG &DAG = DCI.DAG;
8525
8526   if (Subtarget->isThumb1Only())
8527     return SDValue();
8528
8529   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8530     return SDValue();
8531
8532   EVT VT = N->getValueType(0);
8533   if (VT.is64BitVector() || VT.is128BitVector())
8534     return PerformVMULCombine(N, DCI, Subtarget);
8535   if (VT != MVT::i32)
8536     return SDValue();
8537
8538   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8539   if (!C)
8540     return SDValue();
8541
8542   int64_t MulAmt = C->getSExtValue();
8543   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8544
8545   ShiftAmt = ShiftAmt & (32 - 1);
8546   SDValue V = N->getOperand(0);
8547   SDLoc DL(N);
8548
8549   SDValue Res;
8550   MulAmt >>= ShiftAmt;
8551
8552   if (MulAmt >= 0) {
8553     if (isPowerOf2_32(MulAmt - 1)) {
8554       // (mul x, 2^N + 1) => (add (shl x, N), x)
8555       Res = DAG.getNode(ISD::ADD, DL, VT,
8556                         V,
8557                         DAG.getNode(ISD::SHL, DL, VT,
8558                                     V,
8559                                     DAG.getConstant(Log2_32(MulAmt - 1),
8560                                                     MVT::i32)));
8561     } else if (isPowerOf2_32(MulAmt + 1)) {
8562       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8563       Res = DAG.getNode(ISD::SUB, DL, VT,
8564                         DAG.getNode(ISD::SHL, DL, VT,
8565                                     V,
8566                                     DAG.getConstant(Log2_32(MulAmt + 1),
8567                                                     MVT::i32)),
8568                         V);
8569     } else
8570       return SDValue();
8571   } else {
8572     uint64_t MulAmtAbs = -MulAmt;
8573     if (isPowerOf2_32(MulAmtAbs + 1)) {
8574       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8575       Res = DAG.getNode(ISD::SUB, DL, VT,
8576                         V,
8577                         DAG.getNode(ISD::SHL, DL, VT,
8578                                     V,
8579                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8580                                                     MVT::i32)));
8581     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8582       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8583       Res = DAG.getNode(ISD::ADD, DL, VT,
8584                         V,
8585                         DAG.getNode(ISD::SHL, DL, VT,
8586                                     V,
8587                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8588                                                     MVT::i32)));
8589       Res = DAG.getNode(ISD::SUB, DL, VT,
8590                         DAG.getConstant(0, MVT::i32),Res);
8591
8592     } else
8593       return SDValue();
8594   }
8595
8596   if (ShiftAmt != 0)
8597     Res = DAG.getNode(ISD::SHL, DL, VT,
8598                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8599
8600   // Do not add new nodes to DAG combiner worklist.
8601   DCI.CombineTo(N, Res, false);
8602   return SDValue();
8603 }
8604
8605 static SDValue PerformANDCombine(SDNode *N,
8606                                  TargetLowering::DAGCombinerInfo &DCI,
8607                                  const ARMSubtarget *Subtarget) {
8608
8609   // Attempt to use immediate-form VBIC
8610   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8611   SDLoc dl(N);
8612   EVT VT = N->getValueType(0);
8613   SelectionDAG &DAG = DCI.DAG;
8614
8615   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8616     return SDValue();
8617
8618   APInt SplatBits, SplatUndef;
8619   unsigned SplatBitSize;
8620   bool HasAnyUndefs;
8621   if (BVN &&
8622       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8623     if (SplatBitSize <= 64) {
8624       EVT VbicVT;
8625       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8626                                       SplatUndef.getZExtValue(), SplatBitSize,
8627                                       DAG, VbicVT, VT.is128BitVector(),
8628                                       OtherModImm);
8629       if (Val.getNode()) {
8630         SDValue Input =
8631           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8632         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8633         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8634       }
8635     }
8636   }
8637
8638   if (!Subtarget->isThumb1Only()) {
8639     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8640     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8641     if (Result.getNode())
8642       return Result;
8643   }
8644
8645   return SDValue();
8646 }
8647
8648 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8649 static SDValue PerformORCombine(SDNode *N,
8650                                 TargetLowering::DAGCombinerInfo &DCI,
8651                                 const ARMSubtarget *Subtarget) {
8652   // Attempt to use immediate-form VORR
8653   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8654   SDLoc dl(N);
8655   EVT VT = N->getValueType(0);
8656   SelectionDAG &DAG = DCI.DAG;
8657
8658   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8659     return SDValue();
8660
8661   APInt SplatBits, SplatUndef;
8662   unsigned SplatBitSize;
8663   bool HasAnyUndefs;
8664   if (BVN && Subtarget->hasNEON() &&
8665       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8666     if (SplatBitSize <= 64) {
8667       EVT VorrVT;
8668       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8669                                       SplatUndef.getZExtValue(), SplatBitSize,
8670                                       DAG, VorrVT, VT.is128BitVector(),
8671                                       OtherModImm);
8672       if (Val.getNode()) {
8673         SDValue Input =
8674           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8675         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8676         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8677       }
8678     }
8679   }
8680
8681   if (!Subtarget->isThumb1Only()) {
8682     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8683     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8684     if (Result.getNode())
8685       return Result;
8686   }
8687
8688   // The code below optimizes (or (and X, Y), Z).
8689   // The AND operand needs to have a single user to make these optimizations
8690   // profitable.
8691   SDValue N0 = N->getOperand(0);
8692   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8693     return SDValue();
8694   SDValue N1 = N->getOperand(1);
8695
8696   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8697   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8698       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8699     APInt SplatUndef;
8700     unsigned SplatBitSize;
8701     bool HasAnyUndefs;
8702
8703     APInt SplatBits0, SplatBits1;
8704     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8705     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8706     // Ensure that the second operand of both ands are constants
8707     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8708                                       HasAnyUndefs) && !HasAnyUndefs) {
8709         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8710                                           HasAnyUndefs) && !HasAnyUndefs) {
8711             // Ensure that the bit width of the constants are the same and that
8712             // the splat arguments are logical inverses as per the pattern we
8713             // are trying to simplify.
8714             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8715                 SplatBits0 == ~SplatBits1) {
8716                 // Canonicalize the vector type to make instruction selection
8717                 // simpler.
8718                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8719                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8720                                              N0->getOperand(1),
8721                                              N0->getOperand(0),
8722                                              N1->getOperand(0));
8723                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8724             }
8725         }
8726     }
8727   }
8728
8729   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8730   // reasonable.
8731
8732   // BFI is only available on V6T2+
8733   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8734     return SDValue();
8735
8736   SDLoc DL(N);
8737   // 1) or (and A, mask), val => ARMbfi A, val, mask
8738   //      iff (val & mask) == val
8739   //
8740   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8741   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8742   //          && mask == ~mask2
8743   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8744   //          && ~mask == mask2
8745   //  (i.e., copy a bitfield value into another bitfield of the same width)
8746
8747   if (VT != MVT::i32)
8748     return SDValue();
8749
8750   SDValue N00 = N0.getOperand(0);
8751
8752   // The value and the mask need to be constants so we can verify this is
8753   // actually a bitfield set. If the mask is 0xffff, we can do better
8754   // via a movt instruction, so don't use BFI in that case.
8755   SDValue MaskOp = N0.getOperand(1);
8756   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8757   if (!MaskC)
8758     return SDValue();
8759   unsigned Mask = MaskC->getZExtValue();
8760   if (Mask == 0xffff)
8761     return SDValue();
8762   SDValue Res;
8763   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8765   if (N1C) {
8766     unsigned Val = N1C->getZExtValue();
8767     if ((Val & ~Mask) != Val)
8768       return SDValue();
8769
8770     if (ARM::isBitFieldInvertedMask(Mask)) {
8771       Val >>= countTrailingZeros(~Mask);
8772
8773       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8774                         DAG.getConstant(Val, MVT::i32),
8775                         DAG.getConstant(Mask, MVT::i32));
8776
8777       // Do not add new nodes to DAG combiner worklist.
8778       DCI.CombineTo(N, Res, false);
8779       return SDValue();
8780     }
8781   } else if (N1.getOpcode() == ISD::AND) {
8782     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8783     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8784     if (!N11C)
8785       return SDValue();
8786     unsigned Mask2 = N11C->getZExtValue();
8787
8788     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8789     // as is to match.
8790     if (ARM::isBitFieldInvertedMask(Mask) &&
8791         (Mask == ~Mask2)) {
8792       // The pack halfword instruction works better for masks that fit it,
8793       // so use that when it's available.
8794       if (Subtarget->hasT2ExtractPack() &&
8795           (Mask == 0xffff || Mask == 0xffff0000))
8796         return SDValue();
8797       // 2a
8798       unsigned amt = countTrailingZeros(Mask2);
8799       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8800                         DAG.getConstant(amt, MVT::i32));
8801       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8802                         DAG.getConstant(Mask, MVT::i32));
8803       // Do not add new nodes to DAG combiner worklist.
8804       DCI.CombineTo(N, Res, false);
8805       return SDValue();
8806     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8807                (~Mask == Mask2)) {
8808       // The pack halfword instruction works better for masks that fit it,
8809       // so use that when it's available.
8810       if (Subtarget->hasT2ExtractPack() &&
8811           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8812         return SDValue();
8813       // 2b
8814       unsigned lsb = countTrailingZeros(Mask);
8815       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8816                         DAG.getConstant(lsb, MVT::i32));
8817       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8818                         DAG.getConstant(Mask2, MVT::i32));
8819       // Do not add new nodes to DAG combiner worklist.
8820       DCI.CombineTo(N, Res, false);
8821       return SDValue();
8822     }
8823   }
8824
8825   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8826       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8827       ARM::isBitFieldInvertedMask(~Mask)) {
8828     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8829     // where lsb(mask) == #shamt and masked bits of B are known zero.
8830     SDValue ShAmt = N00.getOperand(1);
8831     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8832     unsigned LSB = countTrailingZeros(Mask);
8833     if (ShAmtC != LSB)
8834       return SDValue();
8835
8836     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8837                       DAG.getConstant(~Mask, MVT::i32));
8838
8839     // Do not add new nodes to DAG combiner worklist.
8840     DCI.CombineTo(N, Res, false);
8841   }
8842
8843   return SDValue();
8844 }
8845
8846 static SDValue PerformXORCombine(SDNode *N,
8847                                  TargetLowering::DAGCombinerInfo &DCI,
8848                                  const ARMSubtarget *Subtarget) {
8849   EVT VT = N->getValueType(0);
8850   SelectionDAG &DAG = DCI.DAG;
8851
8852   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8853     return SDValue();
8854
8855   if (!Subtarget->isThumb1Only()) {
8856     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8857     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8858     if (Result.getNode())
8859       return Result;
8860   }
8861
8862   return SDValue();
8863 }
8864
8865 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8866 /// the bits being cleared by the AND are not demanded by the BFI.
8867 static SDValue PerformBFICombine(SDNode *N,
8868                                  TargetLowering::DAGCombinerInfo &DCI) {
8869   SDValue N1 = N->getOperand(1);
8870   if (N1.getOpcode() == ISD::AND) {
8871     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8872     if (!N11C)
8873       return SDValue();
8874     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8875     unsigned LSB = countTrailingZeros(~InvMask);
8876     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8877     unsigned Mask = (1 << Width)-1;
8878     unsigned Mask2 = N11C->getZExtValue();
8879     if ((Mask & (~Mask2)) == 0)
8880       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8881                              N->getOperand(0), N1.getOperand(0),
8882                              N->getOperand(2));
8883   }
8884   return SDValue();
8885 }
8886
8887 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8888 /// ARMISD::VMOVRRD.
8889 static SDValue PerformVMOVRRDCombine(SDNode *N,
8890                                      TargetLowering::DAGCombinerInfo &DCI) {
8891   // vmovrrd(vmovdrr x, y) -> x,y
8892   SDValue InDouble = N->getOperand(0);
8893   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8894     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8895
8896   // vmovrrd(load f64) -> (load i32), (load i32)
8897   SDNode *InNode = InDouble.getNode();
8898   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8899       InNode->getValueType(0) == MVT::f64 &&
8900       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8901       !cast<LoadSDNode>(InNode)->isVolatile()) {
8902     // TODO: Should this be done for non-FrameIndex operands?
8903     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8904
8905     SelectionDAG &DAG = DCI.DAG;
8906     SDLoc DL(LD);
8907     SDValue BasePtr = LD->getBasePtr();
8908     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8909                                  LD->getPointerInfo(), LD->isVolatile(),
8910                                  LD->isNonTemporal(), LD->isInvariant(),
8911                                  LD->getAlignment());
8912
8913     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8914                                     DAG.getConstant(4, MVT::i32));
8915     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8916                                  LD->getPointerInfo(), LD->isVolatile(),
8917                                  LD->isNonTemporal(), LD->isInvariant(),
8918                                  std::min(4U, LD->getAlignment() / 2));
8919
8920     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8921     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8922     DCI.RemoveFromWorklist(LD);
8923     DAG.DeleteNode(LD);
8924     return Result;
8925   }
8926
8927   return SDValue();
8928 }
8929
8930 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8931 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8932 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8933   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8934   SDValue Op0 = N->getOperand(0);
8935   SDValue Op1 = N->getOperand(1);
8936   if (Op0.getOpcode() == ISD::BITCAST)
8937     Op0 = Op0.getOperand(0);
8938   if (Op1.getOpcode() == ISD::BITCAST)
8939     Op1 = Op1.getOperand(0);
8940   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8941       Op0.getNode() == Op1.getNode() &&
8942       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8943     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8944                        N->getValueType(0), Op0.getOperand(0));
8945   return SDValue();
8946 }
8947
8948 /// PerformSTORECombine - Target-specific dag combine xforms for
8949 /// ISD::STORE.
8950 static SDValue PerformSTORECombine(SDNode *N,
8951                                    TargetLowering::DAGCombinerInfo &DCI) {
8952   StoreSDNode *St = cast<StoreSDNode>(N);
8953   if (St->isVolatile())
8954     return SDValue();
8955
8956   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8957   // pack all of the elements in one place.  Next, store to memory in fewer
8958   // chunks.
8959   SDValue StVal = St->getValue();
8960   EVT VT = StVal.getValueType();
8961   if (St->isTruncatingStore() && VT.isVector()) {
8962     SelectionDAG &DAG = DCI.DAG;
8963     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8964     EVT StVT = St->getMemoryVT();
8965     unsigned NumElems = VT.getVectorNumElements();
8966     assert(StVT != VT && "Cannot truncate to the same type");
8967     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8968     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8969
8970     // From, To sizes and ElemCount must be pow of two
8971     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8972
8973     // We are going to use the original vector elt for storing.
8974     // Accumulated smaller vector elements must be a multiple of the store size.
8975     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8976
8977     unsigned SizeRatio  = FromEltSz / ToEltSz;
8978     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8979
8980     // Create a type on which we perform the shuffle.
8981     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8982                                      NumElems*SizeRatio);
8983     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8984
8985     SDLoc DL(St);
8986     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8987     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8988     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8989
8990     // Can't shuffle using an illegal type.
8991     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8992
8993     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8994                                 DAG.getUNDEF(WideVec.getValueType()),
8995                                 ShuffleVec.data());
8996     // At this point all of the data is stored at the bottom of the
8997     // register. We now need to save it to mem.
8998
8999     // Find the largest store unit
9000     MVT StoreType = MVT::i8;
9001     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
9002          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
9003       MVT Tp = (MVT::SimpleValueType)tp;
9004       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9005         StoreType = Tp;
9006     }
9007     // Didn't find a legal store type.
9008     if (!TLI.isTypeLegal(StoreType))
9009       return SDValue();
9010
9011     // Bitcast the original vector into a vector of store-size units
9012     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9013             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9014     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9015     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9016     SmallVector<SDValue, 8> Chains;
9017     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
9018                                         TLI.getPointerTy());
9019     SDValue BasePtr = St->getBasePtr();
9020
9021     // Perform one or more big stores into memory.
9022     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9023     for (unsigned I = 0; I < E; I++) {
9024       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9025                                    StoreType, ShuffWide,
9026                                    DAG.getIntPtrConstant(I));
9027       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9028                                 St->getPointerInfo(), St->isVolatile(),
9029                                 St->isNonTemporal(), St->getAlignment());
9030       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9031                             Increment);
9032       Chains.push_back(Ch);
9033     }
9034     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Chains[0],
9035                        Chains.size());
9036   }
9037
9038   if (!ISD::isNormalStore(St))
9039     return SDValue();
9040
9041   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9042   // ARM stores of arguments in the same cache line.
9043   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9044       StVal.getNode()->hasOneUse()) {
9045     SelectionDAG  &DAG = DCI.DAG;
9046     SDLoc DL(St);
9047     SDValue BasePtr = St->getBasePtr();
9048     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9049                                   StVal.getNode()->getOperand(0), BasePtr,
9050                                   St->getPointerInfo(), St->isVolatile(),
9051                                   St->isNonTemporal(), St->getAlignment());
9052
9053     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9054                                     DAG.getConstant(4, MVT::i32));
9055     return DAG.getStore(NewST1.getValue(0), DL, StVal.getNode()->getOperand(1),
9056                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9057                         St->isNonTemporal(),
9058                         std::min(4U, St->getAlignment() / 2));
9059   }
9060
9061   if (StVal.getValueType() != MVT::i64 ||
9062       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9063     return SDValue();
9064
9065   // Bitcast an i64 store extracted from a vector to f64.
9066   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9067   SelectionDAG &DAG = DCI.DAG;
9068   SDLoc dl(StVal);
9069   SDValue IntVec = StVal.getOperand(0);
9070   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9071                                  IntVec.getValueType().getVectorNumElements());
9072   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9073   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9074                                Vec, StVal.getOperand(1));
9075   dl = SDLoc(N);
9076   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9077   // Make the DAGCombiner fold the bitcasts.
9078   DCI.AddToWorklist(Vec.getNode());
9079   DCI.AddToWorklist(ExtElt.getNode());
9080   DCI.AddToWorklist(V.getNode());
9081   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9082                       St->getPointerInfo(), St->isVolatile(),
9083                       St->isNonTemporal(), St->getAlignment(),
9084                       St->getTBAAInfo());
9085 }
9086
9087 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
9088 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
9089 /// i64 vector to have f64 elements, since the value can then be loaded
9090 /// directly into a VFP register.
9091 static bool hasNormalLoadOperand(SDNode *N) {
9092   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9093   for (unsigned i = 0; i < NumElts; ++i) {
9094     SDNode *Elt = N->getOperand(i).getNode();
9095     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9096       return true;
9097   }
9098   return false;
9099 }
9100
9101 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9102 /// ISD::BUILD_VECTOR.
9103 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9104                                           TargetLowering::DAGCombinerInfo &DCI){
9105   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9106   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9107   // into a pair of GPRs, which is fine when the value is used as a scalar,
9108   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9109   SelectionDAG &DAG = DCI.DAG;
9110   if (N->getNumOperands() == 2) {
9111     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9112     if (RV.getNode())
9113       return RV;
9114   }
9115
9116   // Load i64 elements as f64 values so that type legalization does not split
9117   // them up into i32 values.
9118   EVT VT = N->getValueType(0);
9119   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9120     return SDValue();
9121   SDLoc dl(N);
9122   SmallVector<SDValue, 8> Ops;
9123   unsigned NumElts = VT.getVectorNumElements();
9124   for (unsigned i = 0; i < NumElts; ++i) {
9125     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9126     Ops.push_back(V);
9127     // Make the DAGCombiner fold the bitcast.
9128     DCI.AddToWorklist(V.getNode());
9129   }
9130   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9131   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops.data(), NumElts);
9132   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9133 }
9134
9135 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9136 static SDValue
9137 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9138   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9139   // At that time, we may have inserted bitcasts from integer to float.
9140   // If these bitcasts have survived DAGCombine, change the lowering of this
9141   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9142   // force to use floating point types.
9143
9144   // Make sure we can change the type of the vector.
9145   // This is possible iff:
9146   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9147   //    1.1. Vector is used only once.
9148   //    1.2. Use is a bit convert to an integer type.
9149   // 2. The size of its operands are 32-bits (64-bits are not legal).
9150   EVT VT = N->getValueType(0);
9151   EVT EltVT = VT.getVectorElementType();
9152
9153   // Check 1.1. and 2.
9154   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9155     return SDValue();
9156
9157   // By construction, the input type must be float.
9158   assert(EltVT == MVT::f32 && "Unexpected type!");
9159
9160   // Check 1.2.
9161   SDNode *Use = *N->use_begin();
9162   if (Use->getOpcode() != ISD::BITCAST ||
9163       Use->getValueType(0).isFloatingPoint())
9164     return SDValue();
9165
9166   // Check profitability.
9167   // Model is, if more than half of the relevant operands are bitcast from
9168   // i32, turn the build_vector into a sequence of insert_vector_elt.
9169   // Relevant operands are everything that is not statically
9170   // (i.e., at compile time) bitcasted.
9171   unsigned NumOfBitCastedElts = 0;
9172   unsigned NumElts = VT.getVectorNumElements();
9173   unsigned NumOfRelevantElts = NumElts;
9174   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9175     SDValue Elt = N->getOperand(Idx);
9176     if (Elt->getOpcode() == ISD::BITCAST) {
9177       // Assume only bit cast to i32 will go away.
9178       if (Elt->getOperand(0).getValueType() == MVT::i32)
9179         ++NumOfBitCastedElts;
9180     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9181       // Constants are statically casted, thus do not count them as
9182       // relevant operands.
9183       --NumOfRelevantElts;
9184   }
9185
9186   // Check if more than half of the elements require a non-free bitcast.
9187   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9188     return SDValue();
9189
9190   SelectionDAG &DAG = DCI.DAG;
9191   // Create the new vector type.
9192   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9193   // Check if the type is legal.
9194   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9195   if (!TLI.isTypeLegal(VecVT))
9196     return SDValue();
9197
9198   // Combine:
9199   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9200   // => BITCAST INSERT_VECTOR_ELT
9201   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9202   //                      (BITCAST EN), N.
9203   SDValue Vec = DAG.getUNDEF(VecVT);
9204   SDLoc dl(N);
9205   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9206     SDValue V = N->getOperand(Idx);
9207     if (V.getOpcode() == ISD::UNDEF)
9208       continue;
9209     if (V.getOpcode() == ISD::BITCAST &&
9210         V->getOperand(0).getValueType() == MVT::i32)
9211       // Fold obvious case.
9212       V = V.getOperand(0);
9213     else {
9214       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V); 
9215       // Make the DAGCombiner fold the bitcasts.
9216       DCI.AddToWorklist(V.getNode());
9217     }
9218     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
9219     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9220   }
9221   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9222   // Make the DAGCombiner fold the bitcasts.
9223   DCI.AddToWorklist(Vec.getNode());
9224   return Vec;
9225 }
9226
9227 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9228 /// ISD::INSERT_VECTOR_ELT.
9229 static SDValue PerformInsertEltCombine(SDNode *N,
9230                                        TargetLowering::DAGCombinerInfo &DCI) {
9231   // Bitcast an i64 load inserted into a vector to f64.
9232   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9233   EVT VT = N->getValueType(0);
9234   SDNode *Elt = N->getOperand(1).getNode();
9235   if (VT.getVectorElementType() != MVT::i64 ||
9236       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9237     return SDValue();
9238
9239   SelectionDAG &DAG = DCI.DAG;
9240   SDLoc dl(N);
9241   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9242                                  VT.getVectorNumElements());
9243   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9244   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9245   // Make the DAGCombiner fold the bitcasts.
9246   DCI.AddToWorklist(Vec.getNode());
9247   DCI.AddToWorklist(V.getNode());
9248   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9249                                Vec, V, N->getOperand(2));
9250   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9251 }
9252
9253 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9254 /// ISD::VECTOR_SHUFFLE.
9255 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9256   // The LLVM shufflevector instruction does not require the shuffle mask
9257   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9258   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9259   // operands do not match the mask length, they are extended by concatenating
9260   // them with undef vectors.  That is probably the right thing for other
9261   // targets, but for NEON it is better to concatenate two double-register
9262   // size vector operands into a single quad-register size vector.  Do that
9263   // transformation here:
9264   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9265   //   shuffle(concat(v1, v2), undef)
9266   SDValue Op0 = N->getOperand(0);
9267   SDValue Op1 = N->getOperand(1);
9268   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9269       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9270       Op0.getNumOperands() != 2 ||
9271       Op1.getNumOperands() != 2)
9272     return SDValue();
9273   SDValue Concat0Op1 = Op0.getOperand(1);
9274   SDValue Concat1Op1 = Op1.getOperand(1);
9275   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9276       Concat1Op1.getOpcode() != ISD::UNDEF)
9277     return SDValue();
9278   // Skip the transformation if any of the types are illegal.
9279   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9280   EVT VT = N->getValueType(0);
9281   if (!TLI.isTypeLegal(VT) ||
9282       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9283       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9284     return SDValue();
9285
9286   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9287                                   Op0.getOperand(0), Op1.getOperand(0));
9288   // Translate the shuffle mask.
9289   SmallVector<int, 16> NewMask;
9290   unsigned NumElts = VT.getVectorNumElements();
9291   unsigned HalfElts = NumElts/2;
9292   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9293   for (unsigned n = 0; n < NumElts; ++n) {
9294     int MaskElt = SVN->getMaskElt(n);
9295     int NewElt = -1;
9296     if (MaskElt < (int)HalfElts)
9297       NewElt = MaskElt;
9298     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9299       NewElt = HalfElts + MaskElt - NumElts;
9300     NewMask.push_back(NewElt);
9301   }
9302   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9303                               DAG.getUNDEF(VT), NewMask.data());
9304 }
9305
9306 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9307 /// NEON load/store intrinsics to merge base address updates.
9308 static SDValue CombineBaseUpdate(SDNode *N,
9309                                  TargetLowering::DAGCombinerInfo &DCI) {
9310   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9311     return SDValue();
9312
9313   SelectionDAG &DAG = DCI.DAG;
9314   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9315                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9316   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9317   SDValue Addr = N->getOperand(AddrOpIdx);
9318
9319   // Search for a use of the address operand that is an increment.
9320   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9321          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9322     SDNode *User = *UI;
9323     if (User->getOpcode() != ISD::ADD ||
9324         UI.getUse().getResNo() != Addr.getResNo())
9325       continue;
9326
9327     // Check that the add is independent of the load/store.  Otherwise, folding
9328     // it would create a cycle.
9329     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9330       continue;
9331
9332     // Find the new opcode for the updating load/store.
9333     bool isLoad = true;
9334     bool isLaneOp = false;
9335     unsigned NewOpc = 0;
9336     unsigned NumVecs = 0;
9337     if (isIntrinsic) {
9338       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9339       switch (IntNo) {
9340       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9341       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9342         NumVecs = 1; break;
9343       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9344         NumVecs = 2; break;
9345       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9346         NumVecs = 3; break;
9347       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9348         NumVecs = 4; break;
9349       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9350         NumVecs = 2; isLaneOp = true; break;
9351       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9352         NumVecs = 3; isLaneOp = true; break;
9353       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9354         NumVecs = 4; isLaneOp = true; break;
9355       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9356         NumVecs = 1; isLoad = false; break;
9357       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9358         NumVecs = 2; isLoad = false; break;
9359       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9360         NumVecs = 3; isLoad = false; break;
9361       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9362         NumVecs = 4; isLoad = false; break;
9363       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9364         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9365       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9366         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9367       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9368         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9369       }
9370     } else {
9371       isLaneOp = true;
9372       switch (N->getOpcode()) {
9373       default: llvm_unreachable("unexpected opcode for Neon base update");
9374       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9375       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9376       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9377       }
9378     }
9379
9380     // Find the size of memory referenced by the load/store.
9381     EVT VecTy;
9382     if (isLoad)
9383       VecTy = N->getValueType(0);
9384     else
9385       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9386     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9387     if (isLaneOp)
9388       NumBytes /= VecTy.getVectorNumElements();
9389
9390     // If the increment is a constant, it must match the memory ref size.
9391     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9392     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9393       uint64_t IncVal = CInc->getZExtValue();
9394       if (IncVal != NumBytes)
9395         continue;
9396     } else if (NumBytes >= 3 * 16) {
9397       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9398       // separate instructions that make it harder to use a non-constant update.
9399       continue;
9400     }
9401
9402     // Create the new updating load/store node.
9403     EVT Tys[6];
9404     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9405     unsigned n;
9406     for (n = 0; n < NumResultVecs; ++n)
9407       Tys[n] = VecTy;
9408     Tys[n++] = MVT::i32;
9409     Tys[n] = MVT::Other;
9410     SDVTList SDTys = DAG.getVTList(Tys, NumResultVecs+2);
9411     SmallVector<SDValue, 8> Ops;
9412     Ops.push_back(N->getOperand(0)); // incoming chain
9413     Ops.push_back(N->getOperand(AddrOpIdx));
9414     Ops.push_back(Inc);
9415     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9416       Ops.push_back(N->getOperand(i));
9417     }
9418     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9419     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9420                                            Ops.data(), Ops.size(),
9421                                            MemInt->getMemoryVT(),
9422                                            MemInt->getMemOperand());
9423
9424     // Update the uses.
9425     std::vector<SDValue> NewResults;
9426     for (unsigned i = 0; i < NumResultVecs; ++i) {
9427       NewResults.push_back(SDValue(UpdN.getNode(), i));
9428     }
9429     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9430     DCI.CombineTo(N, NewResults);
9431     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9432
9433     break;
9434   }
9435   return SDValue();
9436 }
9437
9438 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9439 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9440 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9441 /// return true.
9442 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9443   SelectionDAG &DAG = DCI.DAG;
9444   EVT VT = N->getValueType(0);
9445   // vldN-dup instructions only support 64-bit vectors for N > 1.
9446   if (!VT.is64BitVector())
9447     return false;
9448
9449   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9450   SDNode *VLD = N->getOperand(0).getNode();
9451   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9452     return false;
9453   unsigned NumVecs = 0;
9454   unsigned NewOpc = 0;
9455   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9456   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9457     NumVecs = 2;
9458     NewOpc = ARMISD::VLD2DUP;
9459   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9460     NumVecs = 3;
9461     NewOpc = ARMISD::VLD3DUP;
9462   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9463     NumVecs = 4;
9464     NewOpc = ARMISD::VLD4DUP;
9465   } else {
9466     return false;
9467   }
9468
9469   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9470   // numbers match the load.
9471   unsigned VLDLaneNo =
9472     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9473   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9474        UI != UE; ++UI) {
9475     // Ignore uses of the chain result.
9476     if (UI.getUse().getResNo() == NumVecs)
9477       continue;
9478     SDNode *User = *UI;
9479     if (User->getOpcode() != ARMISD::VDUPLANE ||
9480         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9481       return false;
9482   }
9483
9484   // Create the vldN-dup node.
9485   EVT Tys[5];
9486   unsigned n;
9487   for (n = 0; n < NumVecs; ++n)
9488     Tys[n] = VT;
9489   Tys[n] = MVT::Other;
9490   SDVTList SDTys = DAG.getVTList(Tys, NumVecs+1);
9491   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9492   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9493   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9494                                            Ops, 2, VLDMemInt->getMemoryVT(),
9495                                            VLDMemInt->getMemOperand());
9496
9497   // Update the uses.
9498   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9499        UI != UE; ++UI) {
9500     unsigned ResNo = UI.getUse().getResNo();
9501     // Ignore uses of the chain result.
9502     if (ResNo == NumVecs)
9503       continue;
9504     SDNode *User = *UI;
9505     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9506   }
9507
9508   // Now the vldN-lane intrinsic is dead except for its chain result.
9509   // Update uses of the chain.
9510   std::vector<SDValue> VLDDupResults;
9511   for (unsigned n = 0; n < NumVecs; ++n)
9512     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9513   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9514   DCI.CombineTo(VLD, VLDDupResults);
9515
9516   return true;
9517 }
9518
9519 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9520 /// ARMISD::VDUPLANE.
9521 static SDValue PerformVDUPLANECombine(SDNode *N,
9522                                       TargetLowering::DAGCombinerInfo &DCI) {
9523   SDValue Op = N->getOperand(0);
9524
9525   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9526   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9527   if (CombineVLDDUP(N, DCI))
9528     return SDValue(N, 0);
9529
9530   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9531   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9532   while (Op.getOpcode() == ISD::BITCAST)
9533     Op = Op.getOperand(0);
9534   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9535     return SDValue();
9536
9537   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9538   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9539   // The canonical VMOV for a zero vector uses a 32-bit element size.
9540   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9541   unsigned EltBits;
9542   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9543     EltSize = 8;
9544   EVT VT = N->getValueType(0);
9545   if (EltSize > VT.getVectorElementType().getSizeInBits())
9546     return SDValue();
9547
9548   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9549 }
9550
9551 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9552 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9553 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9554 {
9555   integerPart cN;
9556   integerPart c0 = 0;
9557   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9558        I != E; I++) {
9559     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9560     if (!C)
9561       return false;
9562
9563     bool isExact;
9564     APFloat APF = C->getValueAPF();
9565     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9566         != APFloat::opOK || !isExact)
9567       return false;
9568
9569     c0 = (I == 0) ? cN : c0;
9570     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9571       return false;
9572   }
9573   C = c0;
9574   return true;
9575 }
9576
9577 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9578 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9579 /// when the VMUL has a constant operand that is a power of 2.
9580 ///
9581 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9582 ///  vmul.f32        d16, d17, d16
9583 ///  vcvt.s32.f32    d16, d16
9584 /// becomes:
9585 ///  vcvt.s32.f32    d16, d16, #3
9586 static SDValue PerformVCVTCombine(SDNode *N,
9587                                   TargetLowering::DAGCombinerInfo &DCI,
9588                                   const ARMSubtarget *Subtarget) {
9589   SelectionDAG &DAG = DCI.DAG;
9590   SDValue Op = N->getOperand(0);
9591
9592   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9593       Op.getOpcode() != ISD::FMUL)
9594     return SDValue();
9595
9596   uint64_t C;
9597   SDValue N0 = Op->getOperand(0);
9598   SDValue ConstVec = Op->getOperand(1);
9599   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9600
9601   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9602       !isConstVecPow2(ConstVec, isSigned, C))
9603     return SDValue();
9604
9605   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9606   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9607   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9608     // These instructions only exist converting from f32 to i32. We can handle
9609     // smaller integers by generating an extra truncate, but larger ones would
9610     // be lossy.
9611     return SDValue();
9612   }
9613
9614   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9615     Intrinsic::arm_neon_vcvtfp2fxu;
9616   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9617   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9618                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9619                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9620                                  DAG.getConstant(Log2_64(C), MVT::i32));
9621
9622   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9623     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9624
9625   return FixConv;
9626 }
9627
9628 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9629 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9630 /// when the VDIV has a constant operand that is a power of 2.
9631 ///
9632 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9633 ///  vcvt.f32.s32    d16, d16
9634 ///  vdiv.f32        d16, d17, d16
9635 /// becomes:
9636 ///  vcvt.f32.s32    d16, d16, #3
9637 static SDValue PerformVDIVCombine(SDNode *N,
9638                                   TargetLowering::DAGCombinerInfo &DCI,
9639                                   const ARMSubtarget *Subtarget) {
9640   SelectionDAG &DAG = DCI.DAG;
9641   SDValue Op = N->getOperand(0);
9642   unsigned OpOpcode = Op.getNode()->getOpcode();
9643
9644   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9645       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9646     return SDValue();
9647
9648   uint64_t C;
9649   SDValue ConstVec = N->getOperand(1);
9650   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9651
9652   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9653       !isConstVecPow2(ConstVec, isSigned, C))
9654     return SDValue();
9655
9656   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9657   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9658   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9659     // These instructions only exist converting from i32 to f32. We can handle
9660     // smaller integers by generating an extra extend, but larger ones would
9661     // be lossy.
9662     return SDValue();
9663   }
9664
9665   SDValue ConvInput = Op.getOperand(0);
9666   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9667   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9668     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9669                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9670                             ConvInput);
9671
9672   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9673     Intrinsic::arm_neon_vcvtfxu2fp;
9674   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9675                      Op.getValueType(),
9676                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9677                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9678 }
9679
9680 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9681 /// operand of a vector shift operation, where all the elements of the
9682 /// build_vector must have the same constant integer value.
9683 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9684   // Ignore bit_converts.
9685   while (Op.getOpcode() == ISD::BITCAST)
9686     Op = Op.getOperand(0);
9687   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9688   APInt SplatBits, SplatUndef;
9689   unsigned SplatBitSize;
9690   bool HasAnyUndefs;
9691   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9692                                       HasAnyUndefs, ElementBits) ||
9693       SplatBitSize > ElementBits)
9694     return false;
9695   Cnt = SplatBits.getSExtValue();
9696   return true;
9697 }
9698
9699 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9700 /// operand of a vector shift left operation.  That value must be in the range:
9701 ///   0 <= Value < ElementBits for a left shift; or
9702 ///   0 <= Value <= ElementBits for a long left shift.
9703 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9704   assert(VT.isVector() && "vector shift count is not a vector type");
9705   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9706   if (! getVShiftImm(Op, ElementBits, Cnt))
9707     return false;
9708   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9709 }
9710
9711 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9712 /// operand of a vector shift right operation.  For a shift opcode, the value
9713 /// is positive, but for an intrinsic the value count must be negative. The
9714 /// absolute value must be in the range:
9715 ///   1 <= |Value| <= ElementBits for a right shift; or
9716 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9717 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9718                          int64_t &Cnt) {
9719   assert(VT.isVector() && "vector shift count is not a vector type");
9720   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9721   if (! getVShiftImm(Op, ElementBits, Cnt))
9722     return false;
9723   if (isIntrinsic)
9724     Cnt = -Cnt;
9725   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9726 }
9727
9728 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9729 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9730   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9731   switch (IntNo) {
9732   default:
9733     // Don't do anything for most intrinsics.
9734     break;
9735
9736   // Vector shifts: check for immediate versions and lower them.
9737   // Note: This is done during DAG combining instead of DAG legalizing because
9738   // the build_vectors for 64-bit vector element shift counts are generally
9739   // not legal, and it is hard to see their values after they get legalized to
9740   // loads from a constant pool.
9741   case Intrinsic::arm_neon_vshifts:
9742   case Intrinsic::arm_neon_vshiftu:
9743   case Intrinsic::arm_neon_vrshifts:
9744   case Intrinsic::arm_neon_vrshiftu:
9745   case Intrinsic::arm_neon_vrshiftn:
9746   case Intrinsic::arm_neon_vqshifts:
9747   case Intrinsic::arm_neon_vqshiftu:
9748   case Intrinsic::arm_neon_vqshiftsu:
9749   case Intrinsic::arm_neon_vqshiftns:
9750   case Intrinsic::arm_neon_vqshiftnu:
9751   case Intrinsic::arm_neon_vqshiftnsu:
9752   case Intrinsic::arm_neon_vqrshiftns:
9753   case Intrinsic::arm_neon_vqrshiftnu:
9754   case Intrinsic::arm_neon_vqrshiftnsu: {
9755     EVT VT = N->getOperand(1).getValueType();
9756     int64_t Cnt;
9757     unsigned VShiftOpc = 0;
9758
9759     switch (IntNo) {
9760     case Intrinsic::arm_neon_vshifts:
9761     case Intrinsic::arm_neon_vshiftu:
9762       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9763         VShiftOpc = ARMISD::VSHL;
9764         break;
9765       }
9766       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9767         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9768                      ARMISD::VSHRs : ARMISD::VSHRu);
9769         break;
9770       }
9771       return SDValue();
9772
9773     case Intrinsic::arm_neon_vrshifts:
9774     case Intrinsic::arm_neon_vrshiftu:
9775       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9776         break;
9777       return SDValue();
9778
9779     case Intrinsic::arm_neon_vqshifts:
9780     case Intrinsic::arm_neon_vqshiftu:
9781       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9782         break;
9783       return SDValue();
9784
9785     case Intrinsic::arm_neon_vqshiftsu:
9786       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9787         break;
9788       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9789
9790     case Intrinsic::arm_neon_vrshiftn:
9791     case Intrinsic::arm_neon_vqshiftns:
9792     case Intrinsic::arm_neon_vqshiftnu:
9793     case Intrinsic::arm_neon_vqshiftnsu:
9794     case Intrinsic::arm_neon_vqrshiftns:
9795     case Intrinsic::arm_neon_vqrshiftnu:
9796     case Intrinsic::arm_neon_vqrshiftnsu:
9797       // Narrowing shifts require an immediate right shift.
9798       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9799         break;
9800       llvm_unreachable("invalid shift count for narrowing vector shift "
9801                        "intrinsic");
9802
9803     default:
9804       llvm_unreachable("unhandled vector shift");
9805     }
9806
9807     switch (IntNo) {
9808     case Intrinsic::arm_neon_vshifts:
9809     case Intrinsic::arm_neon_vshiftu:
9810       // Opcode already set above.
9811       break;
9812     case Intrinsic::arm_neon_vrshifts:
9813       VShiftOpc = ARMISD::VRSHRs; break;
9814     case Intrinsic::arm_neon_vrshiftu:
9815       VShiftOpc = ARMISD::VRSHRu; break;
9816     case Intrinsic::arm_neon_vrshiftn:
9817       VShiftOpc = ARMISD::VRSHRN; break;
9818     case Intrinsic::arm_neon_vqshifts:
9819       VShiftOpc = ARMISD::VQSHLs; break;
9820     case Intrinsic::arm_neon_vqshiftu:
9821       VShiftOpc = ARMISD::VQSHLu; break;
9822     case Intrinsic::arm_neon_vqshiftsu:
9823       VShiftOpc = ARMISD::VQSHLsu; break;
9824     case Intrinsic::arm_neon_vqshiftns:
9825       VShiftOpc = ARMISD::VQSHRNs; break;
9826     case Intrinsic::arm_neon_vqshiftnu:
9827       VShiftOpc = ARMISD::VQSHRNu; break;
9828     case Intrinsic::arm_neon_vqshiftnsu:
9829       VShiftOpc = ARMISD::VQSHRNsu; break;
9830     case Intrinsic::arm_neon_vqrshiftns:
9831       VShiftOpc = ARMISD::VQRSHRNs; break;
9832     case Intrinsic::arm_neon_vqrshiftnu:
9833       VShiftOpc = ARMISD::VQRSHRNu; break;
9834     case Intrinsic::arm_neon_vqrshiftnsu:
9835       VShiftOpc = ARMISD::VQRSHRNsu; break;
9836     }
9837
9838     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9839                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9840   }
9841
9842   case Intrinsic::arm_neon_vshiftins: {
9843     EVT VT = N->getOperand(1).getValueType();
9844     int64_t Cnt;
9845     unsigned VShiftOpc = 0;
9846
9847     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9848       VShiftOpc = ARMISD::VSLI;
9849     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9850       VShiftOpc = ARMISD::VSRI;
9851     else {
9852       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9853     }
9854
9855     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9856                        N->getOperand(1), N->getOperand(2),
9857                        DAG.getConstant(Cnt, MVT::i32));
9858   }
9859
9860   case Intrinsic::arm_neon_vqrshifts:
9861   case Intrinsic::arm_neon_vqrshiftu:
9862     // No immediate versions of these to check for.
9863     break;
9864   }
9865
9866   return SDValue();
9867 }
9868
9869 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9870 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9871 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9872 /// vector element shift counts are generally not legal, and it is hard to see
9873 /// their values after they get legalized to loads from a constant pool.
9874 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9875                                    const ARMSubtarget *ST) {
9876   EVT VT = N->getValueType(0);
9877   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9878     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9879     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9880     SDValue N1 = N->getOperand(1);
9881     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9882       SDValue N0 = N->getOperand(0);
9883       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9884           DAG.MaskedValueIsZero(N0.getOperand(0),
9885                                 APInt::getHighBitsSet(32, 16)))
9886         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9887     }
9888   }
9889
9890   // Nothing to be done for scalar shifts.
9891   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9892   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9893     return SDValue();
9894
9895   assert(ST->hasNEON() && "unexpected vector shift");
9896   int64_t Cnt;
9897
9898   switch (N->getOpcode()) {
9899   default: llvm_unreachable("unexpected shift opcode");
9900
9901   case ISD::SHL:
9902     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9903       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9904                          DAG.getConstant(Cnt, MVT::i32));
9905     break;
9906
9907   case ISD::SRA:
9908   case ISD::SRL:
9909     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9910       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9911                             ARMISD::VSHRs : ARMISD::VSHRu);
9912       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9913                          DAG.getConstant(Cnt, MVT::i32));
9914     }
9915   }
9916   return SDValue();
9917 }
9918
9919 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9920 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9921 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9922                                     const ARMSubtarget *ST) {
9923   SDValue N0 = N->getOperand(0);
9924
9925   // Check for sign- and zero-extensions of vector extract operations of 8-
9926   // and 16-bit vector elements.  NEON supports these directly.  They are
9927   // handled during DAG combining because type legalization will promote them
9928   // to 32-bit types and it is messy to recognize the operations after that.
9929   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9930     SDValue Vec = N0.getOperand(0);
9931     SDValue Lane = N0.getOperand(1);
9932     EVT VT = N->getValueType(0);
9933     EVT EltVT = N0.getValueType();
9934     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9935
9936     if (VT == MVT::i32 &&
9937         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9938         TLI.isTypeLegal(Vec.getValueType()) &&
9939         isa<ConstantSDNode>(Lane)) {
9940
9941       unsigned Opc = 0;
9942       switch (N->getOpcode()) {
9943       default: llvm_unreachable("unexpected opcode");
9944       case ISD::SIGN_EXTEND:
9945         Opc = ARMISD::VGETLANEs;
9946         break;
9947       case ISD::ZERO_EXTEND:
9948       case ISD::ANY_EXTEND:
9949         Opc = ARMISD::VGETLANEu;
9950         break;
9951       }
9952       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9953     }
9954   }
9955
9956   return SDValue();
9957 }
9958
9959 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9960 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9961 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9962                                        const ARMSubtarget *ST) {
9963   // If the target supports NEON, try to use vmax/vmin instructions for f32
9964   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9965   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9966   // a NaN; only do the transformation when it matches that behavior.
9967
9968   // For now only do this when using NEON for FP operations; if using VFP, it
9969   // is not obvious that the benefit outweighs the cost of switching to the
9970   // NEON pipeline.
9971   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9972       N->getValueType(0) != MVT::f32)
9973     return SDValue();
9974
9975   SDValue CondLHS = N->getOperand(0);
9976   SDValue CondRHS = N->getOperand(1);
9977   SDValue LHS = N->getOperand(2);
9978   SDValue RHS = N->getOperand(3);
9979   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9980
9981   unsigned Opcode = 0;
9982   bool IsReversed;
9983   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9984     IsReversed = false; // x CC y ? x : y
9985   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9986     IsReversed = true ; // x CC y ? y : x
9987   } else {
9988     return SDValue();
9989   }
9990
9991   bool IsUnordered;
9992   switch (CC) {
9993   default: break;
9994   case ISD::SETOLT:
9995   case ISD::SETOLE:
9996   case ISD::SETLT:
9997   case ISD::SETLE:
9998   case ISD::SETULT:
9999   case ISD::SETULE:
10000     // If LHS is NaN, an ordered comparison will be false and the result will
10001     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10002     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10003     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10004     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10005       break;
10006     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10007     // will return -0, so vmin can only be used for unsafe math or if one of
10008     // the operands is known to be nonzero.
10009     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10010         !DAG.getTarget().Options.UnsafeFPMath &&
10011         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10012       break;
10013     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
10014     break;
10015
10016   case ISD::SETOGT:
10017   case ISD::SETOGE:
10018   case ISD::SETGT:
10019   case ISD::SETGE:
10020   case ISD::SETUGT:
10021   case ISD::SETUGE:
10022     // If LHS is NaN, an ordered comparison will be false and the result will
10023     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10024     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10025     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10026     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10027       break;
10028     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10029     // will return +0, so vmax can only be used for unsafe math or if one of
10030     // the operands is known to be nonzero.
10031     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10032         !DAG.getTarget().Options.UnsafeFPMath &&
10033         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10034       break;
10035     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
10036     break;
10037   }
10038
10039   if (!Opcode)
10040     return SDValue();
10041   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10042 }
10043
10044 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10045 SDValue
10046 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10047   SDValue Cmp = N->getOperand(4);
10048   if (Cmp.getOpcode() != ARMISD::CMPZ)
10049     // Only looking at EQ and NE cases.
10050     return SDValue();
10051
10052   EVT VT = N->getValueType(0);
10053   SDLoc dl(N);
10054   SDValue LHS = Cmp.getOperand(0);
10055   SDValue RHS = Cmp.getOperand(1);
10056   SDValue FalseVal = N->getOperand(0);
10057   SDValue TrueVal = N->getOperand(1);
10058   SDValue ARMcc = N->getOperand(2);
10059   ARMCC::CondCodes CC =
10060     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10061
10062   // Simplify
10063   //   mov     r1, r0
10064   //   cmp     r1, x
10065   //   mov     r0, y
10066   //   moveq   r0, x
10067   // to
10068   //   cmp     r0, x
10069   //   movne   r0, y
10070   //
10071   //   mov     r1, r0
10072   //   cmp     r1, x
10073   //   mov     r0, x
10074   //   movne   r0, y
10075   // to
10076   //   cmp     r0, x
10077   //   movne   r0, y
10078   /// FIXME: Turn this into a target neutral optimization?
10079   SDValue Res;
10080   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10081     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10082                       N->getOperand(3), Cmp);
10083   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10084     SDValue ARMcc;
10085     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10086     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10087                       N->getOperand(3), NewCmp);
10088   }
10089
10090   if (Res.getNode()) {
10091     APInt KnownZero, KnownOne;
10092     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
10093     // Capture demanded bits information that would be otherwise lost.
10094     if (KnownZero == 0xfffffffe)
10095       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10096                         DAG.getValueType(MVT::i1));
10097     else if (KnownZero == 0xffffff00)
10098       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10099                         DAG.getValueType(MVT::i8));
10100     else if (KnownZero == 0xffff0000)
10101       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10102                         DAG.getValueType(MVT::i16));
10103   }
10104
10105   return Res;
10106 }
10107
10108 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10109                                              DAGCombinerInfo &DCI) const {
10110   switch (N->getOpcode()) {
10111   default: break;
10112   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10113   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10114   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10115   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10116   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10117   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10118   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10119   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10120   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
10121   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10122   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10123   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
10124   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10125   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10126   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10127   case ISD::FP_TO_SINT:
10128   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10129   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10130   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10131   case ISD::SHL:
10132   case ISD::SRA:
10133   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10134   case ISD::SIGN_EXTEND:
10135   case ISD::ZERO_EXTEND:
10136   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10137   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10138   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10139   case ARMISD::VLD2DUP:
10140   case ARMISD::VLD3DUP:
10141   case ARMISD::VLD4DUP:
10142     return CombineBaseUpdate(N, DCI);
10143   case ARMISD::BUILD_VECTOR:
10144     return PerformARMBUILD_VECTORCombine(N, DCI);
10145   case ISD::INTRINSIC_VOID:
10146   case ISD::INTRINSIC_W_CHAIN:
10147     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10148     case Intrinsic::arm_neon_vld1:
10149     case Intrinsic::arm_neon_vld2:
10150     case Intrinsic::arm_neon_vld3:
10151     case Intrinsic::arm_neon_vld4:
10152     case Intrinsic::arm_neon_vld2lane:
10153     case Intrinsic::arm_neon_vld3lane:
10154     case Intrinsic::arm_neon_vld4lane:
10155     case Intrinsic::arm_neon_vst1:
10156     case Intrinsic::arm_neon_vst2:
10157     case Intrinsic::arm_neon_vst3:
10158     case Intrinsic::arm_neon_vst4:
10159     case Intrinsic::arm_neon_vst2lane:
10160     case Intrinsic::arm_neon_vst3lane:
10161     case Intrinsic::arm_neon_vst4lane:
10162       return CombineBaseUpdate(N, DCI);
10163     default: break;
10164     }
10165     break;
10166   }
10167   return SDValue();
10168 }
10169
10170 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10171                                                           EVT VT) const {
10172   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10173 }
10174
10175 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
10176                                                       bool *Fast) const {
10177   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10178   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10179
10180   switch (VT.getSimpleVT().SimpleTy) {
10181   default:
10182     return false;
10183   case MVT::i8:
10184   case MVT::i16:
10185   case MVT::i32: {
10186     // Unaligned access can use (for example) LRDB, LRDH, LDR
10187     if (AllowsUnaligned) {
10188       if (Fast)
10189         *Fast = Subtarget->hasV7Ops();
10190       return true;
10191     }
10192     return false;
10193   }
10194   case MVT::f64:
10195   case MVT::v2f64: {
10196     // For any little-endian targets with neon, we can support unaligned ld/st
10197     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10198     // A big-endian target may also explicitly support unaligned accesses
10199     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
10200       if (Fast)
10201         *Fast = true;
10202       return true;
10203     }
10204     return false;
10205   }
10206   }
10207 }
10208
10209 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10210                        unsigned AlignCheck) {
10211   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10212           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10213 }
10214
10215 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10216                                            unsigned DstAlign, unsigned SrcAlign,
10217                                            bool IsMemset, bool ZeroMemset,
10218                                            bool MemcpyStrSrc,
10219                                            MachineFunction &MF) const {
10220   const Function *F = MF.getFunction();
10221
10222   // See if we can use NEON instructions for this...
10223   if ((!IsMemset || ZeroMemset) &&
10224       Subtarget->hasNEON() &&
10225       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
10226                                        Attribute::NoImplicitFloat)) {
10227     bool Fast;
10228     if (Size >= 16 &&
10229         (memOpAlign(SrcAlign, DstAlign, 16) ||
10230          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
10231       return MVT::v2f64;
10232     } else if (Size >= 8 &&
10233                (memOpAlign(SrcAlign, DstAlign, 8) ||
10234                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
10235       return MVT::f64;
10236     }
10237   }
10238
10239   // Lowering to i32/i16 if the size permits.
10240   if (Size >= 4)
10241     return MVT::i32;
10242   else if (Size >= 2)
10243     return MVT::i16;
10244
10245   // Let the target-independent logic figure it out.
10246   return MVT::Other;
10247 }
10248
10249 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10250   if (Val.getOpcode() != ISD::LOAD)
10251     return false;
10252
10253   EVT VT1 = Val.getValueType();
10254   if (!VT1.isSimple() || !VT1.isInteger() ||
10255       !VT2.isSimple() || !VT2.isInteger())
10256     return false;
10257
10258   switch (VT1.getSimpleVT().SimpleTy) {
10259   default: break;
10260   case MVT::i1:
10261   case MVT::i8:
10262   case MVT::i16:
10263     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10264     return true;
10265   }
10266
10267   return false;
10268 }
10269
10270 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10271   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10272     return false;
10273
10274   if (!isTypeLegal(EVT::getEVT(Ty1)))
10275     return false;
10276
10277   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10278
10279   // Assuming the caller doesn't have a zeroext or signext return parameter,
10280   // truncation all the way down to i1 is valid.
10281   return true;
10282 }
10283
10284
10285 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10286   if (V < 0)
10287     return false;
10288
10289   unsigned Scale = 1;
10290   switch (VT.getSimpleVT().SimpleTy) {
10291   default: return false;
10292   case MVT::i1:
10293   case MVT::i8:
10294     // Scale == 1;
10295     break;
10296   case MVT::i16:
10297     // Scale == 2;
10298     Scale = 2;
10299     break;
10300   case MVT::i32:
10301     // Scale == 4;
10302     Scale = 4;
10303     break;
10304   }
10305
10306   if ((V & (Scale - 1)) != 0)
10307     return false;
10308   V /= Scale;
10309   return V == (V & ((1LL << 5) - 1));
10310 }
10311
10312 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10313                                       const ARMSubtarget *Subtarget) {
10314   bool isNeg = false;
10315   if (V < 0) {
10316     isNeg = true;
10317     V = - V;
10318   }
10319
10320   switch (VT.getSimpleVT().SimpleTy) {
10321   default: return false;
10322   case MVT::i1:
10323   case MVT::i8:
10324   case MVT::i16:
10325   case MVT::i32:
10326     // + imm12 or - imm8
10327     if (isNeg)
10328       return V == (V & ((1LL << 8) - 1));
10329     return V == (V & ((1LL << 12) - 1));
10330   case MVT::f32:
10331   case MVT::f64:
10332     // Same as ARM mode. FIXME: NEON?
10333     if (!Subtarget->hasVFP2())
10334       return false;
10335     if ((V & 3) != 0)
10336       return false;
10337     V >>= 2;
10338     return V == (V & ((1LL << 8) - 1));
10339   }
10340 }
10341
10342 /// isLegalAddressImmediate - Return true if the integer value can be used
10343 /// as the offset of the target addressing mode for load / store of the
10344 /// given type.
10345 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10346                                     const ARMSubtarget *Subtarget) {
10347   if (V == 0)
10348     return true;
10349
10350   if (!VT.isSimple())
10351     return false;
10352
10353   if (Subtarget->isThumb1Only())
10354     return isLegalT1AddressImmediate(V, VT);
10355   else if (Subtarget->isThumb2())
10356     return isLegalT2AddressImmediate(V, VT, Subtarget);
10357
10358   // ARM mode.
10359   if (V < 0)
10360     V = - V;
10361   switch (VT.getSimpleVT().SimpleTy) {
10362   default: return false;
10363   case MVT::i1:
10364   case MVT::i8:
10365   case MVT::i32:
10366     // +- imm12
10367     return V == (V & ((1LL << 12) - 1));
10368   case MVT::i16:
10369     // +- imm8
10370     return V == (V & ((1LL << 8) - 1));
10371   case MVT::f32:
10372   case MVT::f64:
10373     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10374       return false;
10375     if ((V & 3) != 0)
10376       return false;
10377     V >>= 2;
10378     return V == (V & ((1LL << 8) - 1));
10379   }
10380 }
10381
10382 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10383                                                       EVT VT) const {
10384   int Scale = AM.Scale;
10385   if (Scale < 0)
10386     return false;
10387
10388   switch (VT.getSimpleVT().SimpleTy) {
10389   default: return false;
10390   case MVT::i1:
10391   case MVT::i8:
10392   case MVT::i16:
10393   case MVT::i32:
10394     if (Scale == 1)
10395       return true;
10396     // r + r << imm
10397     Scale = Scale & ~1;
10398     return Scale == 2 || Scale == 4 || Scale == 8;
10399   case MVT::i64:
10400     // r + r
10401     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10402       return true;
10403     return false;
10404   case MVT::isVoid:
10405     // Note, we allow "void" uses (basically, uses that aren't loads or
10406     // stores), because arm allows folding a scale into many arithmetic
10407     // operations.  This should be made more precise and revisited later.
10408
10409     // Allow r << imm, but the imm has to be a multiple of two.
10410     if (Scale & 1) return false;
10411     return isPowerOf2_32(Scale);
10412   }
10413 }
10414
10415 /// isLegalAddressingMode - Return true if the addressing mode represented
10416 /// by AM is legal for this target, for a load/store of the specified type.
10417 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10418                                               Type *Ty) const {
10419   EVT VT = getValueType(Ty, true);
10420   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10421     return false;
10422
10423   // Can never fold addr of global into load/store.
10424   if (AM.BaseGV)
10425     return false;
10426
10427   switch (AM.Scale) {
10428   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10429     break;
10430   case 1:
10431     if (Subtarget->isThumb1Only())
10432       return false;
10433     // FALL THROUGH.
10434   default:
10435     // ARM doesn't support any R+R*scale+imm addr modes.
10436     if (AM.BaseOffs)
10437       return false;
10438
10439     if (!VT.isSimple())
10440       return false;
10441
10442     if (Subtarget->isThumb2())
10443       return isLegalT2ScaledAddressingMode(AM, VT);
10444
10445     int Scale = AM.Scale;
10446     switch (VT.getSimpleVT().SimpleTy) {
10447     default: return false;
10448     case MVT::i1:
10449     case MVT::i8:
10450     case MVT::i32:
10451       if (Scale < 0) Scale = -Scale;
10452       if (Scale == 1)
10453         return true;
10454       // r + r << imm
10455       return isPowerOf2_32(Scale & ~1);
10456     case MVT::i16:
10457     case MVT::i64:
10458       // r + r
10459       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10460         return true;
10461       return false;
10462
10463     case MVT::isVoid:
10464       // Note, we allow "void" uses (basically, uses that aren't loads or
10465       // stores), because arm allows folding a scale into many arithmetic
10466       // operations.  This should be made more precise and revisited later.
10467
10468       // Allow r << imm, but the imm has to be a multiple of two.
10469       if (Scale & 1) return false;
10470       return isPowerOf2_32(Scale);
10471     }
10472   }
10473   return true;
10474 }
10475
10476 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10477 /// icmp immediate, that is the target has icmp instructions which can compare
10478 /// a register against the immediate without having to materialize the
10479 /// immediate into a register.
10480 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10481   // Thumb2 and ARM modes can use cmn for negative immediates.
10482   if (!Subtarget->isThumb())
10483     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10484   if (Subtarget->isThumb2())
10485     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10486   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10487   return Imm >= 0 && Imm <= 255;
10488 }
10489
10490 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10491 /// *or sub* immediate, that is the target has add or sub instructions which can
10492 /// add a register with the immediate without having to materialize the
10493 /// immediate into a register.
10494 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10495   // Same encoding for add/sub, just flip the sign.
10496   int64_t AbsImm = llvm::abs64(Imm);
10497   if (!Subtarget->isThumb())
10498     return ARM_AM::getSOImmVal(AbsImm) != -1;
10499   if (Subtarget->isThumb2())
10500     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10501   // Thumb1 only has 8-bit unsigned immediate.
10502   return AbsImm >= 0 && AbsImm <= 255;
10503 }
10504
10505 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10506                                       bool isSEXTLoad, SDValue &Base,
10507                                       SDValue &Offset, bool &isInc,
10508                                       SelectionDAG &DAG) {
10509   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10510     return false;
10511
10512   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10513     // AddressingMode 3
10514     Base = Ptr->getOperand(0);
10515     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10516       int RHSC = (int)RHS->getZExtValue();
10517       if (RHSC < 0 && RHSC > -256) {
10518         assert(Ptr->getOpcode() == ISD::ADD);
10519         isInc = false;
10520         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10521         return true;
10522       }
10523     }
10524     isInc = (Ptr->getOpcode() == ISD::ADD);
10525     Offset = Ptr->getOperand(1);
10526     return true;
10527   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10528     // AddressingMode 2
10529     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10530       int RHSC = (int)RHS->getZExtValue();
10531       if (RHSC < 0 && RHSC > -0x1000) {
10532         assert(Ptr->getOpcode() == ISD::ADD);
10533         isInc = false;
10534         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10535         Base = Ptr->getOperand(0);
10536         return true;
10537       }
10538     }
10539
10540     if (Ptr->getOpcode() == ISD::ADD) {
10541       isInc = true;
10542       ARM_AM::ShiftOpc ShOpcVal=
10543         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10544       if (ShOpcVal != ARM_AM::no_shift) {
10545         Base = Ptr->getOperand(1);
10546         Offset = Ptr->getOperand(0);
10547       } else {
10548         Base = Ptr->getOperand(0);
10549         Offset = Ptr->getOperand(1);
10550       }
10551       return true;
10552     }
10553
10554     isInc = (Ptr->getOpcode() == ISD::ADD);
10555     Base = Ptr->getOperand(0);
10556     Offset = Ptr->getOperand(1);
10557     return true;
10558   }
10559
10560   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10561   return false;
10562 }
10563
10564 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10565                                      bool isSEXTLoad, SDValue &Base,
10566                                      SDValue &Offset, bool &isInc,
10567                                      SelectionDAG &DAG) {
10568   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10569     return false;
10570
10571   Base = Ptr->getOperand(0);
10572   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10573     int RHSC = (int)RHS->getZExtValue();
10574     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10575       assert(Ptr->getOpcode() == ISD::ADD);
10576       isInc = false;
10577       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10578       return true;
10579     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10580       isInc = Ptr->getOpcode() == ISD::ADD;
10581       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10582       return true;
10583     }
10584   }
10585
10586   return false;
10587 }
10588
10589 /// getPreIndexedAddressParts - returns true by value, base pointer and
10590 /// offset pointer and addressing mode by reference if the node's address
10591 /// can be legally represented as pre-indexed load / store address.
10592 bool
10593 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10594                                              SDValue &Offset,
10595                                              ISD::MemIndexedMode &AM,
10596                                              SelectionDAG &DAG) const {
10597   if (Subtarget->isThumb1Only())
10598     return false;
10599
10600   EVT VT;
10601   SDValue Ptr;
10602   bool isSEXTLoad = false;
10603   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10604     Ptr = LD->getBasePtr();
10605     VT  = LD->getMemoryVT();
10606     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10607   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10608     Ptr = ST->getBasePtr();
10609     VT  = ST->getMemoryVT();
10610   } else
10611     return false;
10612
10613   bool isInc;
10614   bool isLegal = false;
10615   if (Subtarget->isThumb2())
10616     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10617                                        Offset, isInc, DAG);
10618   else
10619     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10620                                         Offset, isInc, DAG);
10621   if (!isLegal)
10622     return false;
10623
10624   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10625   return true;
10626 }
10627
10628 /// getPostIndexedAddressParts - returns true by value, base pointer and
10629 /// offset pointer and addressing mode by reference if this node can be
10630 /// combined with a load / store to form a post-indexed load / store.
10631 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10632                                                    SDValue &Base,
10633                                                    SDValue &Offset,
10634                                                    ISD::MemIndexedMode &AM,
10635                                                    SelectionDAG &DAG) const {
10636   if (Subtarget->isThumb1Only())
10637     return false;
10638
10639   EVT VT;
10640   SDValue Ptr;
10641   bool isSEXTLoad = false;
10642   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10643     VT  = LD->getMemoryVT();
10644     Ptr = LD->getBasePtr();
10645     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10646   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10647     VT  = ST->getMemoryVT();
10648     Ptr = ST->getBasePtr();
10649   } else
10650     return false;
10651
10652   bool isInc;
10653   bool isLegal = false;
10654   if (Subtarget->isThumb2())
10655     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10656                                        isInc, DAG);
10657   else
10658     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10659                                         isInc, DAG);
10660   if (!isLegal)
10661     return false;
10662
10663   if (Ptr != Base) {
10664     // Swap base ptr and offset to catch more post-index load / store when
10665     // it's legal. In Thumb2 mode, offset must be an immediate.
10666     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10667         !Subtarget->isThumb2())
10668       std::swap(Base, Offset);
10669
10670     // Post-indexed load / store update the base pointer.
10671     if (Ptr != Base)
10672       return false;
10673   }
10674
10675   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10676   return true;
10677 }
10678
10679 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10680                                                        APInt &KnownZero,
10681                                                        APInt &KnownOne,
10682                                                        const SelectionDAG &DAG,
10683                                                        unsigned Depth) const {
10684   unsigned BitWidth = KnownOne.getBitWidth();
10685   KnownZero = KnownOne = APInt(BitWidth, 0);
10686   switch (Op.getOpcode()) {
10687   default: break;
10688   case ARMISD::ADDC:
10689   case ARMISD::ADDE:
10690   case ARMISD::SUBC:
10691   case ARMISD::SUBE:
10692     // These nodes' second result is a boolean
10693     if (Op.getResNo() == 0)
10694       break;
10695     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10696     break;
10697   case ARMISD::CMOV: {
10698     // Bits are known zero/one if known on the LHS and RHS.
10699     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10700     if (KnownZero == 0 && KnownOne == 0) return;
10701
10702     APInt KnownZeroRHS, KnownOneRHS;
10703     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10704     KnownZero &= KnownZeroRHS;
10705     KnownOne  &= KnownOneRHS;
10706     return;
10707   }
10708   }
10709 }
10710
10711 //===----------------------------------------------------------------------===//
10712 //                           ARM Inline Assembly Support
10713 //===----------------------------------------------------------------------===//
10714
10715 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10716   // Looking for "rev" which is V6+.
10717   if (!Subtarget->hasV6Ops())
10718     return false;
10719
10720   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10721   std::string AsmStr = IA->getAsmString();
10722   SmallVector<StringRef, 4> AsmPieces;
10723   SplitString(AsmStr, AsmPieces, ";\n");
10724
10725   switch (AsmPieces.size()) {
10726   default: return false;
10727   case 1:
10728     AsmStr = AsmPieces[0];
10729     AsmPieces.clear();
10730     SplitString(AsmStr, AsmPieces, " \t,");
10731
10732     // rev $0, $1
10733     if (AsmPieces.size() == 3 &&
10734         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10735         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10736       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10737       if (Ty && Ty->getBitWidth() == 32)
10738         return IntrinsicLowering::LowerToByteSwap(CI);
10739     }
10740     break;
10741   }
10742
10743   return false;
10744 }
10745
10746 /// getConstraintType - Given a constraint letter, return the type of
10747 /// constraint it is for this target.
10748 ARMTargetLowering::ConstraintType
10749 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10750   if (Constraint.size() == 1) {
10751     switch (Constraint[0]) {
10752     default:  break;
10753     case 'l': return C_RegisterClass;
10754     case 'w': return C_RegisterClass;
10755     case 'h': return C_RegisterClass;
10756     case 'x': return C_RegisterClass;
10757     case 't': return C_RegisterClass;
10758     case 'j': return C_Other; // Constant for movw.
10759       // An address with a single base register. Due to the way we
10760       // currently handle addresses it is the same as an 'r' memory constraint.
10761     case 'Q': return C_Memory;
10762     }
10763   } else if (Constraint.size() == 2) {
10764     switch (Constraint[0]) {
10765     default: break;
10766     // All 'U+' constraints are addresses.
10767     case 'U': return C_Memory;
10768     }
10769   }
10770   return TargetLowering::getConstraintType(Constraint);
10771 }
10772
10773 /// Examine constraint type and operand type and determine a weight value.
10774 /// This object must already have been set up with the operand type
10775 /// and the current alternative constraint selected.
10776 TargetLowering::ConstraintWeight
10777 ARMTargetLowering::getSingleConstraintMatchWeight(
10778     AsmOperandInfo &info, const char *constraint) const {
10779   ConstraintWeight weight = CW_Invalid;
10780   Value *CallOperandVal = info.CallOperandVal;
10781     // If we don't have a value, we can't do a match,
10782     // but allow it at the lowest weight.
10783   if (CallOperandVal == NULL)
10784     return CW_Default;
10785   Type *type = CallOperandVal->getType();
10786   // Look at the constraint type.
10787   switch (*constraint) {
10788   default:
10789     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10790     break;
10791   case 'l':
10792     if (type->isIntegerTy()) {
10793       if (Subtarget->isThumb())
10794         weight = CW_SpecificReg;
10795       else
10796         weight = CW_Register;
10797     }
10798     break;
10799   case 'w':
10800     if (type->isFloatingPointTy())
10801       weight = CW_Register;
10802     break;
10803   }
10804   return weight;
10805 }
10806
10807 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10808 RCPair
10809 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10810                                                 MVT VT) const {
10811   if (Constraint.size() == 1) {
10812     // GCC ARM Constraint Letters
10813     switch (Constraint[0]) {
10814     case 'l': // Low regs or general regs.
10815       if (Subtarget->isThumb())
10816         return RCPair(0U, &ARM::tGPRRegClass);
10817       return RCPair(0U, &ARM::GPRRegClass);
10818     case 'h': // High regs or no regs.
10819       if (Subtarget->isThumb())
10820         return RCPair(0U, &ARM::hGPRRegClass);
10821       break;
10822     case 'r':
10823       return RCPair(0U, &ARM::GPRRegClass);
10824     case 'w':
10825       if (VT == MVT::Other)
10826         break;
10827       if (VT == MVT::f32)
10828         return RCPair(0U, &ARM::SPRRegClass);
10829       if (VT.getSizeInBits() == 64)
10830         return RCPair(0U, &ARM::DPRRegClass);
10831       if (VT.getSizeInBits() == 128)
10832         return RCPair(0U, &ARM::QPRRegClass);
10833       break;
10834     case 'x':
10835       if (VT == MVT::Other)
10836         break;
10837       if (VT == MVT::f32)
10838         return RCPair(0U, &ARM::SPR_8RegClass);
10839       if (VT.getSizeInBits() == 64)
10840         return RCPair(0U, &ARM::DPR_8RegClass);
10841       if (VT.getSizeInBits() == 128)
10842         return RCPair(0U, &ARM::QPR_8RegClass);
10843       break;
10844     case 't':
10845       if (VT == MVT::f32)
10846         return RCPair(0U, &ARM::SPRRegClass);
10847       break;
10848     }
10849   }
10850   if (StringRef("{cc}").equals_lower(Constraint))
10851     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10852
10853   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10854 }
10855
10856 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10857 /// vector.  If it is invalid, don't add anything to Ops.
10858 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10859                                                      std::string &Constraint,
10860                                                      std::vector<SDValue>&Ops,
10861                                                      SelectionDAG &DAG) const {
10862   SDValue Result(0, 0);
10863
10864   // Currently only support length 1 constraints.
10865   if (Constraint.length() != 1) return;
10866
10867   char ConstraintLetter = Constraint[0];
10868   switch (ConstraintLetter) {
10869   default: break;
10870   case 'j':
10871   case 'I': case 'J': case 'K': case 'L':
10872   case 'M': case 'N': case 'O':
10873     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10874     if (!C)
10875       return;
10876
10877     int64_t CVal64 = C->getSExtValue();
10878     int CVal = (int) CVal64;
10879     // None of these constraints allow values larger than 32 bits.  Check
10880     // that the value fits in an int.
10881     if (CVal != CVal64)
10882       return;
10883
10884     switch (ConstraintLetter) {
10885       case 'j':
10886         // Constant suitable for movw, must be between 0 and
10887         // 65535.
10888         if (Subtarget->hasV6T2Ops())
10889           if (CVal >= 0 && CVal <= 65535)
10890             break;
10891         return;
10892       case 'I':
10893         if (Subtarget->isThumb1Only()) {
10894           // This must be a constant between 0 and 255, for ADD
10895           // immediates.
10896           if (CVal >= 0 && CVal <= 255)
10897             break;
10898         } else if (Subtarget->isThumb2()) {
10899           // A constant that can be used as an immediate value in a
10900           // data-processing instruction.
10901           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10902             break;
10903         } else {
10904           // A constant that can be used as an immediate value in a
10905           // data-processing instruction.
10906           if (ARM_AM::getSOImmVal(CVal) != -1)
10907             break;
10908         }
10909         return;
10910
10911       case 'J':
10912         if (Subtarget->isThumb()) {  // FIXME thumb2
10913           // This must be a constant between -255 and -1, for negated ADD
10914           // immediates. This can be used in GCC with an "n" modifier that
10915           // prints the negated value, for use with SUB instructions. It is
10916           // not useful otherwise but is implemented for compatibility.
10917           if (CVal >= -255 && CVal <= -1)
10918             break;
10919         } else {
10920           // This must be a constant between -4095 and 4095. It is not clear
10921           // what this constraint is intended for. Implemented for
10922           // compatibility with GCC.
10923           if (CVal >= -4095 && CVal <= 4095)
10924             break;
10925         }
10926         return;
10927
10928       case 'K':
10929         if (Subtarget->isThumb1Only()) {
10930           // A 32-bit value where only one byte has a nonzero value. Exclude
10931           // zero to match GCC. This constraint is used by GCC internally for
10932           // constants that can be loaded with a move/shift combination.
10933           // It is not useful otherwise but is implemented for compatibility.
10934           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10935             break;
10936         } else if (Subtarget->isThumb2()) {
10937           // A constant whose bitwise inverse can be used as an immediate
10938           // value in a data-processing instruction. This can be used in GCC
10939           // with a "B" modifier that prints the inverted value, for use with
10940           // BIC and MVN instructions. It is not useful otherwise but is
10941           // implemented for compatibility.
10942           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10943             break;
10944         } else {
10945           // A constant whose bitwise inverse can be used as an immediate
10946           // value in a data-processing instruction. This can be used in GCC
10947           // with a "B" modifier that prints the inverted value, for use with
10948           // BIC and MVN instructions. It is not useful otherwise but is
10949           // implemented for compatibility.
10950           if (ARM_AM::getSOImmVal(~CVal) != -1)
10951             break;
10952         }
10953         return;
10954
10955       case 'L':
10956         if (Subtarget->isThumb1Only()) {
10957           // This must be a constant between -7 and 7,
10958           // for 3-operand ADD/SUB immediate instructions.
10959           if (CVal >= -7 && CVal < 7)
10960             break;
10961         } else if (Subtarget->isThumb2()) {
10962           // A constant whose negation can be used as an immediate value in a
10963           // data-processing instruction. This can be used in GCC with an "n"
10964           // modifier that prints the negated value, for use with SUB
10965           // instructions. It is not useful otherwise but is implemented for
10966           // compatibility.
10967           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10968             break;
10969         } else {
10970           // A constant whose negation can be used as an immediate value in a
10971           // data-processing instruction. This can be used in GCC with an "n"
10972           // modifier that prints the negated value, for use with SUB
10973           // instructions. It is not useful otherwise but is implemented for
10974           // compatibility.
10975           if (ARM_AM::getSOImmVal(-CVal) != -1)
10976             break;
10977         }
10978         return;
10979
10980       case 'M':
10981         if (Subtarget->isThumb()) { // FIXME thumb2
10982           // This must be a multiple of 4 between 0 and 1020, for
10983           // ADD sp + immediate.
10984           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10985             break;
10986         } else {
10987           // A power of two or a constant between 0 and 32.  This is used in
10988           // GCC for the shift amount on shifted register operands, but it is
10989           // useful in general for any shift amounts.
10990           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10991             break;
10992         }
10993         return;
10994
10995       case 'N':
10996         if (Subtarget->isThumb()) {  // FIXME thumb2
10997           // This must be a constant between 0 and 31, for shift amounts.
10998           if (CVal >= 0 && CVal <= 31)
10999             break;
11000         }
11001         return;
11002
11003       case 'O':
11004         if (Subtarget->isThumb()) {  // FIXME thumb2
11005           // This must be a multiple of 4 between -508 and 508, for
11006           // ADD/SUB sp = sp + immediate.
11007           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11008             break;
11009         }
11010         return;
11011     }
11012     Result = DAG.getTargetConstant(CVal, Op.getValueType());
11013     break;
11014   }
11015
11016   if (Result.getNode()) {
11017     Ops.push_back(Result);
11018     return;
11019   }
11020   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11021 }
11022
11023 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11024   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
11025   unsigned Opcode = Op->getOpcode();
11026   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11027       "Invalid opcode for Div/Rem lowering");
11028   bool isSigned = (Opcode == ISD::SDIVREM);
11029   EVT VT = Op->getValueType(0);
11030   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11031
11032   RTLIB::Libcall LC;
11033   switch (VT.getSimpleVT().SimpleTy) {
11034   default: llvm_unreachable("Unexpected request for libcall!");
11035   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11036   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11037   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11038   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11039   }
11040
11041   SDValue InChain = DAG.getEntryNode();
11042
11043   TargetLowering::ArgListTy Args;
11044   TargetLowering::ArgListEntry Entry;
11045   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11046     EVT ArgVT = Op->getOperand(i).getValueType();
11047     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11048     Entry.Node = Op->getOperand(i);
11049     Entry.Ty = ArgTy;
11050     Entry.isSExt = isSigned;
11051     Entry.isZExt = !isSigned;
11052     Args.push_back(Entry);
11053   }
11054
11055   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11056                                          getPointerTy());
11057
11058   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
11059
11060   SDLoc dl(Op);
11061   TargetLowering::
11062   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
11063                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
11064                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
11065                     Callee, Args, DAG, dl);
11066   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11067
11068   return CallInfo.first;
11069 }
11070
11071 bool
11072 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11073   // The ARM target isn't yet aware of offsets.
11074   return false;
11075 }
11076
11077 bool ARM::isBitFieldInvertedMask(unsigned v) {
11078   if (v == 0xffffffff)
11079     return false;
11080
11081   // there can be 1's on either or both "outsides", all the "inside"
11082   // bits must be 0's
11083   unsigned TO = CountTrailingOnes_32(v);
11084   unsigned LO = CountLeadingOnes_32(v);
11085   v = (v >> TO) << TO;
11086   v = (v << LO) >> LO;
11087   return v == 0;
11088 }
11089
11090 /// isFPImmLegal - Returns true if the target can instruction select the
11091 /// specified FP immediate natively. If false, the legalizer will
11092 /// materialize the FP immediate as a load from a constant pool.
11093 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11094   if (!Subtarget->hasVFP3())
11095     return false;
11096   if (VT == MVT::f32)
11097     return ARM_AM::getFP32Imm(Imm) != -1;
11098   if (VT == MVT::f64)
11099     return ARM_AM::getFP64Imm(Imm) != -1;
11100   return false;
11101 }
11102
11103 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11104 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11105 /// specified in the intrinsic calls.
11106 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11107                                            const CallInst &I,
11108                                            unsigned Intrinsic) const {
11109   switch (Intrinsic) {
11110   case Intrinsic::arm_neon_vld1:
11111   case Intrinsic::arm_neon_vld2:
11112   case Intrinsic::arm_neon_vld3:
11113   case Intrinsic::arm_neon_vld4:
11114   case Intrinsic::arm_neon_vld2lane:
11115   case Intrinsic::arm_neon_vld3lane:
11116   case Intrinsic::arm_neon_vld4lane: {
11117     Info.opc = ISD::INTRINSIC_W_CHAIN;
11118     // Conservatively set memVT to the entire set of vectors loaded.
11119     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
11120     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11121     Info.ptrVal = I.getArgOperand(0);
11122     Info.offset = 0;
11123     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11124     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11125     Info.vol = false; // volatile loads with NEON intrinsics not supported
11126     Info.readMem = true;
11127     Info.writeMem = false;
11128     return true;
11129   }
11130   case Intrinsic::arm_neon_vst1:
11131   case Intrinsic::arm_neon_vst2:
11132   case Intrinsic::arm_neon_vst3:
11133   case Intrinsic::arm_neon_vst4:
11134   case Intrinsic::arm_neon_vst2lane:
11135   case Intrinsic::arm_neon_vst3lane:
11136   case Intrinsic::arm_neon_vst4lane: {
11137     Info.opc = ISD::INTRINSIC_VOID;
11138     // Conservatively set memVT to the entire set of vectors stored.
11139     unsigned NumElts = 0;
11140     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11141       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11142       if (!ArgTy->isVectorTy())
11143         break;
11144       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
11145     }
11146     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11147     Info.ptrVal = I.getArgOperand(0);
11148     Info.offset = 0;
11149     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11150     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11151     Info.vol = false; // volatile stores with NEON intrinsics not supported
11152     Info.readMem = false;
11153     Info.writeMem = true;
11154     return true;
11155   }
11156   case Intrinsic::arm_ldaex:
11157   case Intrinsic::arm_ldrex: {
11158     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11159     Info.opc = ISD::INTRINSIC_W_CHAIN;
11160     Info.memVT = MVT::getVT(PtrTy->getElementType());
11161     Info.ptrVal = I.getArgOperand(0);
11162     Info.offset = 0;
11163     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11164     Info.vol = true;
11165     Info.readMem = true;
11166     Info.writeMem = false;
11167     return true;
11168   }
11169   case Intrinsic::arm_stlex:
11170   case Intrinsic::arm_strex: {
11171     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11172     Info.opc = ISD::INTRINSIC_W_CHAIN;
11173     Info.memVT = MVT::getVT(PtrTy->getElementType());
11174     Info.ptrVal = I.getArgOperand(1);
11175     Info.offset = 0;
11176     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
11177     Info.vol = true;
11178     Info.readMem = false;
11179     Info.writeMem = true;
11180     return true;
11181   }
11182   case Intrinsic::arm_stlexd:
11183   case Intrinsic::arm_strexd: {
11184     Info.opc = ISD::INTRINSIC_W_CHAIN;
11185     Info.memVT = MVT::i64;
11186     Info.ptrVal = I.getArgOperand(2);
11187     Info.offset = 0;
11188     Info.align = 8;
11189     Info.vol = true;
11190     Info.readMem = false;
11191     Info.writeMem = true;
11192     return true;
11193   }
11194   case Intrinsic::arm_ldaexd:
11195   case Intrinsic::arm_ldrexd: {
11196     Info.opc = ISD::INTRINSIC_W_CHAIN;
11197     Info.memVT = MVT::i64;
11198     Info.ptrVal = I.getArgOperand(0);
11199     Info.offset = 0;
11200     Info.align = 8;
11201     Info.vol = true;
11202     Info.readMem = true;
11203     Info.writeMem = false;
11204     return true;
11205   }
11206   default:
11207     break;
11208   }
11209
11210   return false;
11211 }
11212
11213 /// \brief Returns true if it is beneficial to convert a load of a constant
11214 /// to just the constant itself.
11215 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11216                                                           Type *Ty) const {
11217   assert(Ty->isIntegerTy());
11218
11219   unsigned Bits = Ty->getPrimitiveSizeInBits();
11220   if (Bits == 0 || Bits > 32)
11221     return false;
11222   return true;
11223 }