ARM big endian function argument passing
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.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 #define DEBUG_TYPE "arm-isel"
53
54 STATISTIC(NumTailCalls, "Number of tail calls");
55 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
56 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
57
58 cl::opt<bool>
59 EnableARMLongCalls("arm-long-calls", cl::Hidden,
60   cl::desc("Generate calls via indirect call instructions"),
61   cl::init(false));
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
73                LLVMContext &C, ParmContext PC)
74         : CCState(CC, isVarArg, MF, TM, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145 }
146
147 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
148   addRegisterClass(VT, &ARM::DPRRegClass);
149   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
150 }
151
152 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPairRegClass);
154   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
155 }
156
157 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
158   if (TM.getSubtarget<ARMSubtarget>().isTargetMachO())
159     return new TargetLoweringObjectFileMachO();
160
161   return new ARMElfTargetObjectFile();
162 }
163
164 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
165     : TargetLowering(TM, createTLOF(TM)) {
166   Subtarget = &TM.getSubtarget<ARMSubtarget>();
167   RegInfo = TM.getRegisterInfo();
168   Itins = TM.getInstrItineraryData();
169
170   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
171
172   if (Subtarget->isTargetMachO()) {
173     // Uses VFP for Thumb libfuncs if available.
174     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
175         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
176       // Single-precision floating-point arithmetic.
177       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
178       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
179       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
180       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
181
182       // Double-precision floating-point arithmetic.
183       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
184       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
185       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
186       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
187
188       // Single-precision comparisons.
189       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
190       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
191       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
192       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
193       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
194       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
195       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
196       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
197
198       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
199       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
200       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
205       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
206
207       // Double-precision comparisons.
208       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
209       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
210       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
211       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
212       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
213       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
214       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
215       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
216
217       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
218       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
219       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
224       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
225
226       // Floating-point to integer conversions.
227       // i64 conversions are done via library routines even when generating VFP
228       // instructions, so use the same ones.
229       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
230       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
231       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
233
234       // Conversions between floating types.
235       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
236       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
237
238       // Integer to floating-point conversions.
239       // i64 conversions are done via library routines even when generating VFP
240       // instructions, so use the same ones.
241       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
242       // e.g., __floatunsidf vs. __floatunssidfvfp.
243       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
244       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
245       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
247     }
248   }
249
250   // These libcalls are not available in 32-bit.
251   setLibcallName(RTLIB::SHL_I128, nullptr);
252   setLibcallName(RTLIB::SRL_I128, nullptr);
253   setLibcallName(RTLIB::SRA_I128, nullptr);
254
255   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
256       !Subtarget->isTargetWindows()) {
257     // Double-precision floating-point arithmetic helper functions
258     // RTABI chapter 4.1.2, Table 2
259     setLibcallName(RTLIB::ADD_F64, "__aeabi_dadd");
260     setLibcallName(RTLIB::DIV_F64, "__aeabi_ddiv");
261     setLibcallName(RTLIB::MUL_F64, "__aeabi_dmul");
262     setLibcallName(RTLIB::SUB_F64, "__aeabi_dsub");
263     setLibcallCallingConv(RTLIB::ADD_F64, CallingConv::ARM_AAPCS);
264     setLibcallCallingConv(RTLIB::DIV_F64, CallingConv::ARM_AAPCS);
265     setLibcallCallingConv(RTLIB::MUL_F64, CallingConv::ARM_AAPCS);
266     setLibcallCallingConv(RTLIB::SUB_F64, CallingConv::ARM_AAPCS);
267
268     // Double-precision floating-point comparison helper functions
269     // RTABI chapter 4.1.2, Table 3
270     setLibcallName(RTLIB::OEQ_F64, "__aeabi_dcmpeq");
271     setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
272     setLibcallName(RTLIB::UNE_F64, "__aeabi_dcmpeq");
273     setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETEQ);
274     setLibcallName(RTLIB::OLT_F64, "__aeabi_dcmplt");
275     setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
276     setLibcallName(RTLIB::OLE_F64, "__aeabi_dcmple");
277     setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
278     setLibcallName(RTLIB::OGE_F64, "__aeabi_dcmpge");
279     setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
280     setLibcallName(RTLIB::OGT_F64, "__aeabi_dcmpgt");
281     setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
282     setLibcallName(RTLIB::UO_F64,  "__aeabi_dcmpun");
283     setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
284     setLibcallName(RTLIB::O_F64,   "__aeabi_dcmpun");
285     setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
286     setLibcallCallingConv(RTLIB::OEQ_F64, CallingConv::ARM_AAPCS);
287     setLibcallCallingConv(RTLIB::UNE_F64, CallingConv::ARM_AAPCS);
288     setLibcallCallingConv(RTLIB::OLT_F64, CallingConv::ARM_AAPCS);
289     setLibcallCallingConv(RTLIB::OLE_F64, CallingConv::ARM_AAPCS);
290     setLibcallCallingConv(RTLIB::OGE_F64, CallingConv::ARM_AAPCS);
291     setLibcallCallingConv(RTLIB::OGT_F64, CallingConv::ARM_AAPCS);
292     setLibcallCallingConv(RTLIB::UO_F64, CallingConv::ARM_AAPCS);
293     setLibcallCallingConv(RTLIB::O_F64, CallingConv::ARM_AAPCS);
294
295     // Single-precision floating-point arithmetic helper functions
296     // RTABI chapter 4.1.2, Table 4
297     setLibcallName(RTLIB::ADD_F32, "__aeabi_fadd");
298     setLibcallName(RTLIB::DIV_F32, "__aeabi_fdiv");
299     setLibcallName(RTLIB::MUL_F32, "__aeabi_fmul");
300     setLibcallName(RTLIB::SUB_F32, "__aeabi_fsub");
301     setLibcallCallingConv(RTLIB::ADD_F32, CallingConv::ARM_AAPCS);
302     setLibcallCallingConv(RTLIB::DIV_F32, CallingConv::ARM_AAPCS);
303     setLibcallCallingConv(RTLIB::MUL_F32, CallingConv::ARM_AAPCS);
304     setLibcallCallingConv(RTLIB::SUB_F32, CallingConv::ARM_AAPCS);
305
306     // Single-precision floating-point comparison helper functions
307     // RTABI chapter 4.1.2, Table 5
308     setLibcallName(RTLIB::OEQ_F32, "__aeabi_fcmpeq");
309     setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
310     setLibcallName(RTLIB::UNE_F32, "__aeabi_fcmpeq");
311     setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETEQ);
312     setLibcallName(RTLIB::OLT_F32, "__aeabi_fcmplt");
313     setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
314     setLibcallName(RTLIB::OLE_F32, "__aeabi_fcmple");
315     setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
316     setLibcallName(RTLIB::OGE_F32, "__aeabi_fcmpge");
317     setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
318     setLibcallName(RTLIB::OGT_F32, "__aeabi_fcmpgt");
319     setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
320     setLibcallName(RTLIB::UO_F32,  "__aeabi_fcmpun");
321     setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
322     setLibcallName(RTLIB::O_F32,   "__aeabi_fcmpun");
323     setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
324     setLibcallCallingConv(RTLIB::OEQ_F32, CallingConv::ARM_AAPCS);
325     setLibcallCallingConv(RTLIB::UNE_F32, CallingConv::ARM_AAPCS);
326     setLibcallCallingConv(RTLIB::OLT_F32, CallingConv::ARM_AAPCS);
327     setLibcallCallingConv(RTLIB::OLE_F32, CallingConv::ARM_AAPCS);
328     setLibcallCallingConv(RTLIB::OGE_F32, CallingConv::ARM_AAPCS);
329     setLibcallCallingConv(RTLIB::OGT_F32, CallingConv::ARM_AAPCS);
330     setLibcallCallingConv(RTLIB::UO_F32, CallingConv::ARM_AAPCS);
331     setLibcallCallingConv(RTLIB::O_F32, CallingConv::ARM_AAPCS);
332
333     // Floating-point to integer conversions.
334     // RTABI chapter 4.1.2, Table 6
335     setLibcallName(RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz");
336     setLibcallName(RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz");
337     setLibcallName(RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz");
338     setLibcallName(RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz");
339     setLibcallName(RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz");
340     setLibcallName(RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz");
341     setLibcallName(RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz");
342     setLibcallName(RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz");
343     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I32, CallingConv::ARM_AAPCS);
344     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I32, CallingConv::ARM_AAPCS);
345     setLibcallCallingConv(RTLIB::FPTOSINT_F64_I64, CallingConv::ARM_AAPCS);
346     setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::ARM_AAPCS);
347     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I32, CallingConv::ARM_AAPCS);
348     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I32, CallingConv::ARM_AAPCS);
349     setLibcallCallingConv(RTLIB::FPTOSINT_F32_I64, CallingConv::ARM_AAPCS);
350     setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::ARM_AAPCS);
351
352     // Conversions between floating types.
353     // RTABI chapter 4.1.2, Table 7
354     setLibcallName(RTLIB::FPROUND_F64_F32, "__aeabi_d2f");
355     setLibcallName(RTLIB::FPEXT_F32_F64,   "__aeabi_f2d");
356     setLibcallCallingConv(RTLIB::FPROUND_F64_F32, CallingConv::ARM_AAPCS);
357     setLibcallCallingConv(RTLIB::FPEXT_F32_F64, CallingConv::ARM_AAPCS);
358
359     // Integer to floating-point conversions.
360     // RTABI chapter 4.1.2, Table 8
361     setLibcallName(RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d");
362     setLibcallName(RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d");
363     setLibcallName(RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d");
364     setLibcallName(RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d");
365     setLibcallName(RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f");
366     setLibcallName(RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f");
367     setLibcallName(RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f");
368     setLibcallName(RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f");
369     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
370     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F64, CallingConv::ARM_AAPCS);
371     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
372     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F64, CallingConv::ARM_AAPCS);
373     setLibcallCallingConv(RTLIB::SINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
374     setLibcallCallingConv(RTLIB::UINTTOFP_I32_F32, CallingConv::ARM_AAPCS);
375     setLibcallCallingConv(RTLIB::SINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
376     setLibcallCallingConv(RTLIB::UINTTOFP_I64_F32, CallingConv::ARM_AAPCS);
377
378     // Long long helper functions
379     // RTABI chapter 4.2, Table 9
380     setLibcallName(RTLIB::MUL_I64,  "__aeabi_lmul");
381     setLibcallName(RTLIB::SHL_I64, "__aeabi_llsl");
382     setLibcallName(RTLIB::SRL_I64, "__aeabi_llsr");
383     setLibcallName(RTLIB::SRA_I64, "__aeabi_lasr");
384     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::ARM_AAPCS);
385     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
386     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
387     setLibcallCallingConv(RTLIB::SHL_I64, CallingConv::ARM_AAPCS);
388     setLibcallCallingConv(RTLIB::SRL_I64, CallingConv::ARM_AAPCS);
389     setLibcallCallingConv(RTLIB::SRA_I64, CallingConv::ARM_AAPCS);
390
391     // Integer division functions
392     // RTABI chapter 4.3.1
393     setLibcallName(RTLIB::SDIV_I8,  "__aeabi_idiv");
394     setLibcallName(RTLIB::SDIV_I16, "__aeabi_idiv");
395     setLibcallName(RTLIB::SDIV_I32, "__aeabi_idiv");
396     setLibcallName(RTLIB::SDIV_I64, "__aeabi_ldivmod");
397     setLibcallName(RTLIB::UDIV_I8,  "__aeabi_uidiv");
398     setLibcallName(RTLIB::UDIV_I16, "__aeabi_uidiv");
399     setLibcallName(RTLIB::UDIV_I32, "__aeabi_uidiv");
400     setLibcallName(RTLIB::UDIV_I64, "__aeabi_uldivmod");
401     setLibcallCallingConv(RTLIB::SDIV_I8, CallingConv::ARM_AAPCS);
402     setLibcallCallingConv(RTLIB::SDIV_I16, CallingConv::ARM_AAPCS);
403     setLibcallCallingConv(RTLIB::SDIV_I32, CallingConv::ARM_AAPCS);
404     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::ARM_AAPCS);
405     setLibcallCallingConv(RTLIB::UDIV_I8, CallingConv::ARM_AAPCS);
406     setLibcallCallingConv(RTLIB::UDIV_I16, CallingConv::ARM_AAPCS);
407     setLibcallCallingConv(RTLIB::UDIV_I32, CallingConv::ARM_AAPCS);
408     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::ARM_AAPCS);
409
410     // Memory operations
411     // RTABI chapter 4.3.4
412     setLibcallName(RTLIB::MEMCPY,  "__aeabi_memcpy");
413     setLibcallName(RTLIB::MEMMOVE, "__aeabi_memmove");
414     setLibcallName(RTLIB::MEMSET,  "__aeabi_memset");
415     setLibcallCallingConv(RTLIB::MEMCPY, CallingConv::ARM_AAPCS);
416     setLibcallCallingConv(RTLIB::MEMMOVE, CallingConv::ARM_AAPCS);
417     setLibcallCallingConv(RTLIB::MEMSET, CallingConv::ARM_AAPCS);
418   }
419
420   // Use divmod compiler-rt calls for iOS 5.0 and later.
421   if (Subtarget->getTargetTriple().isiOS() &&
422       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
423     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
424     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
425   }
426
427   if (Subtarget->isThumb1Only())
428     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
429   else
430     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
431   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
432       !Subtarget->isThumb1Only()) {
433     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
434     if (!Subtarget->isFPOnlySP())
435       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
436
437     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
438   }
439
440   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
441        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
442     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
443          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
444       setTruncStoreAction((MVT::SimpleValueType)VT,
445                           (MVT::SimpleValueType)InnerVT, Expand);
446     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
447     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
448     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
449
450     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
451     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
452     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
453     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
454   }
455
456   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
457   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
458
459   if (Subtarget->hasNEON()) {
460     addDRTypeForNEON(MVT::v2f32);
461     addDRTypeForNEON(MVT::v8i8);
462     addDRTypeForNEON(MVT::v4i16);
463     addDRTypeForNEON(MVT::v2i32);
464     addDRTypeForNEON(MVT::v1i64);
465
466     addQRTypeForNEON(MVT::v4f32);
467     addQRTypeForNEON(MVT::v2f64);
468     addQRTypeForNEON(MVT::v16i8);
469     addQRTypeForNEON(MVT::v8i16);
470     addQRTypeForNEON(MVT::v4i32);
471     addQRTypeForNEON(MVT::v2i64);
472
473     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
474     // neither Neon nor VFP support any arithmetic operations on it.
475     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
476     // supported for v4f32.
477     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
478     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
479     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
480     // FIXME: Code duplication: FDIV and FREM are expanded always, see
481     // ARMTargetLowering::addTypeForNEON method for details.
482     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
483     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
484     // FIXME: Create unittest.
485     // In another words, find a way when "copysign" appears in DAG with vector
486     // operands.
487     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
488     // FIXME: Code duplication: SETCC has custom operation action, see
489     // ARMTargetLowering::addTypeForNEON method for details.
490     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
491     // FIXME: Create unittest for FNEG and for FABS.
492     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
493     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
494     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
504     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
505     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
506     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
507     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
508     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
509     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
510     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
511
512     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
513     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
514     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
515     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
516     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
517     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
518     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
519     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
520     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
521     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
522     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
523     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
524     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
525     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
526     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
527
528     // Mark v2f32 intrinsics.
529     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
530     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
531     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
532     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
533     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
534     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
535     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
536     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
537     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
538     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
539     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
540     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
541     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
542     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
543     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
544
545     // Neon does not support some operations on v1i64 and v2i64 types.
546     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
547     // Custom handling for some quad-vector types to detect VMULL.
548     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
549     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
550     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
551     // Custom handling for some vector types to avoid expensive expansions
552     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
553     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
554     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
555     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
556     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
557     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
558     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
559     // a destination type that is wider than the source, and nor does
560     // it have a FP_TO_[SU]INT instruction with a narrower destination than
561     // source.
562     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
563     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
564     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
565     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
566
567     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
568     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
569
570     // NEON does not have single instruction CTPOP for vectors with element
571     // types wider than 8-bits.  However, custom lowering can leverage the
572     // v8i8/v16i8 vcnt instruction.
573     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
574     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
575     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
576     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
577
578     // NEON only has FMA instructions as of VFP4.
579     if (!Subtarget->hasVFP4()) {
580       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
581       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
582     }
583
584     setTargetDAGCombine(ISD::INTRINSIC_VOID);
585     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
586     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
587     setTargetDAGCombine(ISD::SHL);
588     setTargetDAGCombine(ISD::SRL);
589     setTargetDAGCombine(ISD::SRA);
590     setTargetDAGCombine(ISD::SIGN_EXTEND);
591     setTargetDAGCombine(ISD::ZERO_EXTEND);
592     setTargetDAGCombine(ISD::ANY_EXTEND);
593     setTargetDAGCombine(ISD::SELECT_CC);
594     setTargetDAGCombine(ISD::BUILD_VECTOR);
595     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
596     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
597     setTargetDAGCombine(ISD::STORE);
598     setTargetDAGCombine(ISD::FP_TO_SINT);
599     setTargetDAGCombine(ISD::FP_TO_UINT);
600     setTargetDAGCombine(ISD::FDIV);
601
602     // It is legal to extload from v4i8 to v4i16 or v4i32.
603     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
604                   MVT::v4i16, MVT::v2i16,
605                   MVT::v2i32};
606     for (unsigned i = 0; i < 6; ++i) {
607       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
608       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
609       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
610     }
611   }
612
613   // ARM and Thumb2 support UMLAL/SMLAL.
614   if (!Subtarget->isThumb1Only())
615     setTargetDAGCombine(ISD::ADDC);
616
617
618   computeRegisterProperties();
619
620   // ARM does not have f32 extending load.
621   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
622
623   // ARM does not have i1 sign extending load.
624   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
625
626   // ARM supports all 4 flavors of integer indexed load / store.
627   if (!Subtarget->isThumb1Only()) {
628     for (unsigned im = (unsigned)ISD::PRE_INC;
629          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
630       setIndexedLoadAction(im,  MVT::i1,  Legal);
631       setIndexedLoadAction(im,  MVT::i8,  Legal);
632       setIndexedLoadAction(im,  MVT::i16, Legal);
633       setIndexedLoadAction(im,  MVT::i32, Legal);
634       setIndexedStoreAction(im, MVT::i1,  Legal);
635       setIndexedStoreAction(im, MVT::i8,  Legal);
636       setIndexedStoreAction(im, MVT::i16, Legal);
637       setIndexedStoreAction(im, MVT::i32, Legal);
638     }
639   }
640
641   // i64 operation support.
642   setOperationAction(ISD::MUL,     MVT::i64, Expand);
643   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
644   if (Subtarget->isThumb1Only()) {
645     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
646     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
647   }
648   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
649       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
650     setOperationAction(ISD::MULHS, MVT::i32, Expand);
651
652   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
653   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
654   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
655   setOperationAction(ISD::SRL,       MVT::i64, Custom);
656   setOperationAction(ISD::SRA,       MVT::i64, Custom);
657
658   if (!Subtarget->isThumb1Only()) {
659     // FIXME: We should do this for Thumb1 as well.
660     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
661     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
662     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
663     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
664   }
665
666   // ARM does not have ROTL.
667   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
668   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
669   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
670   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
671     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
672
673   // These just redirect to CTTZ and CTLZ on ARM.
674   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
675   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
676
677   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
678
679   // Only ARMv6 has BSWAP.
680   if (!Subtarget->hasV6Ops())
681     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
682
683   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
684       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
685     // These are expanded into libcalls if the cpu doesn't have HW divider.
686     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
687     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
688   }
689
690   // FIXME: Also set divmod for SREM on EABI
691   setOperationAction(ISD::SREM,  MVT::i32, Expand);
692   setOperationAction(ISD::UREM,  MVT::i32, Expand);
693   // Register based DivRem for AEABI (RTABI 4.2)
694   if (Subtarget->isTargetAEABI()) {
695     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
696     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
697     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
698     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
699     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
700     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
701     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
702     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
703
704     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
705     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
706     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
707     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
708     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
709     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
710     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
711     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
712
713     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
714     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
715   } else {
716     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
717     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
718   }
719
720   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
721   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
722   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
723   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
724   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
725
726   setOperationAction(ISD::TRAP, MVT::Other, Legal);
727
728   // Use the default implementation.
729   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
730   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
731   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
732   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
733   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
734   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
735
736   if (!Subtarget->isTargetMachO()) {
737     // Non-MachO platforms may return values in these registers via the
738     // personality function.
739     setExceptionPointerRegister(ARM::R0);
740     setExceptionSelectorRegister(ARM::R1);
741   }
742
743   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
744   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
745   // the default expansion.
746   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
747     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
748     // to ldrex/strex loops already.
749     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
750
751     // On v8, we have particularly efficient implementations of atomic fences
752     // if they can be combined with nearby atomic loads and stores.
753     if (!Subtarget->hasV8Ops()) {
754       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
755       setInsertFencesForAtomic(true);
756     }
757   } else {
758     // If there's anything we can use as a barrier, go through custom lowering
759     // for ATOMIC_FENCE.
760     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
761                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
762
763     // Set them all for expansion, which will force libcalls.
764     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
765     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
766     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
767     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
768     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
769     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
770     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
771     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
772     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
773     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
774     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
775     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
776     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
777     // Unordered/Monotonic case.
778     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
779     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
780   }
781
782   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
783
784   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
785   if (!Subtarget->hasV6Ops()) {
786     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
787     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
788   }
789   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
790
791   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
792       !Subtarget->isThumb1Only()) {
793     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
794     // iff target supports vfp2.
795     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
796     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
797   }
798
799   // We want to custom lower some of our intrinsics.
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
801   if (Subtarget->isTargetDarwin()) {
802     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
803     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
804     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
805   }
806
807   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
808   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
809   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
810   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
811   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
812   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
813   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
814   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
815   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
816
817   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
818   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
819   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
820   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
821   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
822
823   // We don't support sin/cos/fmod/copysign/pow
824   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
825   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
826   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
827   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
828   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
829   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
830   setOperationAction(ISD::FREM,      MVT::f64, Expand);
831   setOperationAction(ISD::FREM,      MVT::f32, Expand);
832   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
833       !Subtarget->isThumb1Only()) {
834     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
835     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
836   }
837   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
838   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
839
840   if (!Subtarget->hasVFP4()) {
841     setOperationAction(ISD::FMA, MVT::f64, Expand);
842     setOperationAction(ISD::FMA, MVT::f32, Expand);
843   }
844
845   // Various VFP goodness
846   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
847     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
848     if (Subtarget->hasVFP2()) {
849       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
850       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
851       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
852       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
853     }
854     // Special handling for half-precision FP.
855     if (!Subtarget->hasFP16()) {
856       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
857       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
858     }
859   }
860
861   // Combine sin / cos into one node or libcall if possible.
862   if (Subtarget->hasSinCos()) {
863     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
864     setLibcallName(RTLIB::SINCOS_F64, "sincos");
865     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
866       // For iOS, we don't want to the normal expansion of a libcall to
867       // sincos. We want to issue a libcall to __sincos_stret.
868       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
869       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
870     }
871   }
872
873   // We have target-specific dag combine patterns for the following nodes:
874   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
875   setTargetDAGCombine(ISD::ADD);
876   setTargetDAGCombine(ISD::SUB);
877   setTargetDAGCombine(ISD::MUL);
878   setTargetDAGCombine(ISD::AND);
879   setTargetDAGCombine(ISD::OR);
880   setTargetDAGCombine(ISD::XOR);
881
882   if (Subtarget->hasV6Ops())
883     setTargetDAGCombine(ISD::SRL);
884
885   setStackPointerRegisterToSaveRestore(ARM::SP);
886
887   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
888       !Subtarget->hasVFP2())
889     setSchedulingPreference(Sched::RegPressure);
890   else
891     setSchedulingPreference(Sched::Hybrid);
892
893   //// temporary - rewrite interface to use type
894   MaxStoresPerMemset = 8;
895   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
896   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
897   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
898   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
899   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
900
901   // On ARM arguments smaller than 4 bytes are extended, so all arguments
902   // are at least 4 bytes aligned.
903   setMinStackArgumentAlignment(4);
904
905   // Prefer likely predicted branches to selects on out-of-order cores.
906   PredictableSelectIsExpensive = Subtarget->isLikeA9();
907
908   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
909 }
910
911 // FIXME: It might make sense to define the representative register class as the
912 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
913 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
914 // SPR's representative would be DPR_VFP2. This should work well if register
915 // pressure tracking were modified such that a register use would increment the
916 // pressure of the register class's representative and all of it's super
917 // classes' representatives transitively. We have not implemented this because
918 // of the difficulty prior to coalescing of modeling operand register classes
919 // due to the common occurrence of cross class copies and subregister insertions
920 // and extractions.
921 std::pair<const TargetRegisterClass*, uint8_t>
922 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
923   const TargetRegisterClass *RRC = nullptr;
924   uint8_t Cost = 1;
925   switch (VT.SimpleTy) {
926   default:
927     return TargetLowering::findRepresentativeClass(VT);
928   // Use DPR as representative register class for all floating point
929   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
930   // the cost is 1 for both f32 and f64.
931   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
932   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
933     RRC = &ARM::DPRRegClass;
934     // When NEON is used for SP, only half of the register file is available
935     // because operations that define both SP and DP results will be constrained
936     // to the VFP2 class (D0-D15). We currently model this constraint prior to
937     // coalescing by double-counting the SP regs. See the FIXME above.
938     if (Subtarget->useNEONForSinglePrecisionFP())
939       Cost = 2;
940     break;
941   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
942   case MVT::v4f32: case MVT::v2f64:
943     RRC = &ARM::DPRRegClass;
944     Cost = 2;
945     break;
946   case MVT::v4i64:
947     RRC = &ARM::DPRRegClass;
948     Cost = 4;
949     break;
950   case MVT::v8i64:
951     RRC = &ARM::DPRRegClass;
952     Cost = 8;
953     break;
954   }
955   return std::make_pair(RRC, Cost);
956 }
957
958 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
959   switch (Opcode) {
960   default: return nullptr;
961   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
962   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
963   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
964   case ARMISD::CALL:          return "ARMISD::CALL";
965   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
966   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
967   case ARMISD::tCALL:         return "ARMISD::tCALL";
968   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
969   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
970   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
971   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
972   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
973   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
974   case ARMISD::CMP:           return "ARMISD::CMP";
975   case ARMISD::CMN:           return "ARMISD::CMN";
976   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
977   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
978   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
979   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
980   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
981
982   case ARMISD::CMOV:          return "ARMISD::CMOV";
983
984   case ARMISD::RBIT:          return "ARMISD::RBIT";
985
986   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
987   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
988   case ARMISD::SITOF:         return "ARMISD::SITOF";
989   case ARMISD::UITOF:         return "ARMISD::UITOF";
990
991   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
992   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
993   case ARMISD::RRX:           return "ARMISD::RRX";
994
995   case ARMISD::ADDC:          return "ARMISD::ADDC";
996   case ARMISD::ADDE:          return "ARMISD::ADDE";
997   case ARMISD::SUBC:          return "ARMISD::SUBC";
998   case ARMISD::SUBE:          return "ARMISD::SUBE";
999
1000   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1001   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1002
1003   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1004   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1005
1006   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1007
1008   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1009
1010   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1011
1012   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1013
1014   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1015
1016   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1017   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1018   case ARMISD::VCGE:          return "ARMISD::VCGE";
1019   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1020   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1021   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1022   case ARMISD::VCGT:          return "ARMISD::VCGT";
1023   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1024   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1025   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1026   case ARMISD::VTST:          return "ARMISD::VTST";
1027
1028   case ARMISD::VSHL:          return "ARMISD::VSHL";
1029   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1030   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1031   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1032   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1033   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1034   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1035   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1036   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1037   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1038   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1039   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1040   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1041   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1042   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1043   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1044   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1045   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1046   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1047   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1048   case ARMISD::VDUP:          return "ARMISD::VDUP";
1049   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1050   case ARMISD::VEXT:          return "ARMISD::VEXT";
1051   case ARMISD::VREV64:        return "ARMISD::VREV64";
1052   case ARMISD::VREV32:        return "ARMISD::VREV32";
1053   case ARMISD::VREV16:        return "ARMISD::VREV16";
1054   case ARMISD::VZIP:          return "ARMISD::VZIP";
1055   case ARMISD::VUZP:          return "ARMISD::VUZP";
1056   case ARMISD::VTRN:          return "ARMISD::VTRN";
1057   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1058   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1059   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1060   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1061   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1062   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1063   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1064   case ARMISD::FMAX:          return "ARMISD::FMAX";
1065   case ARMISD::FMIN:          return "ARMISD::FMIN";
1066   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1067   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1068   case ARMISD::BFI:           return "ARMISD::BFI";
1069   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1070   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1071   case ARMISD::VBSL:          return "ARMISD::VBSL";
1072   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1073   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1074   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1075   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1076   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1077   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1078   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1079   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1080   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1081   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1082   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1083   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1084   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1085   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1086   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1087   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1088   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1089   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1090   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1091   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1092   }
1093 }
1094
1095 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1096   if (!VT.isVector()) return getPointerTy();
1097   return VT.changeVectorElementTypeToInteger();
1098 }
1099
1100 /// getRegClassFor - Return the register class that should be used for the
1101 /// specified value type.
1102 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1103   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1104   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1105   // load / store 4 to 8 consecutive D registers.
1106   if (Subtarget->hasNEON()) {
1107     if (VT == MVT::v4i64)
1108       return &ARM::QQPRRegClass;
1109     if (VT == MVT::v8i64)
1110       return &ARM::QQQQPRRegClass;
1111   }
1112   return TargetLowering::getRegClassFor(VT);
1113 }
1114
1115 // Create a fast isel object.
1116 FastISel *
1117 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1118                                   const TargetLibraryInfo *libInfo) const {
1119   return ARM::createFastISel(funcInfo, libInfo);
1120 }
1121
1122 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1123 /// be used for loads / stores from the global.
1124 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1125   return (Subtarget->isThumb1Only() ? 127 : 4095);
1126 }
1127
1128 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1129   unsigned NumVals = N->getNumValues();
1130   if (!NumVals)
1131     return Sched::RegPressure;
1132
1133   for (unsigned i = 0; i != NumVals; ++i) {
1134     EVT VT = N->getValueType(i);
1135     if (VT == MVT::Glue || VT == MVT::Other)
1136       continue;
1137     if (VT.isFloatingPoint() || VT.isVector())
1138       return Sched::ILP;
1139   }
1140
1141   if (!N->isMachineOpcode())
1142     return Sched::RegPressure;
1143
1144   // Load are scheduled for latency even if there instruction itinerary
1145   // is not available.
1146   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1147   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1148
1149   if (MCID.getNumDefs() == 0)
1150     return Sched::RegPressure;
1151   if (!Itins->isEmpty() &&
1152       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1153     return Sched::ILP;
1154
1155   return Sched::RegPressure;
1156 }
1157
1158 //===----------------------------------------------------------------------===//
1159 // Lowering Code
1160 //===----------------------------------------------------------------------===//
1161
1162 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1163 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1164   switch (CC) {
1165   default: llvm_unreachable("Unknown condition code!");
1166   case ISD::SETNE:  return ARMCC::NE;
1167   case ISD::SETEQ:  return ARMCC::EQ;
1168   case ISD::SETGT:  return ARMCC::GT;
1169   case ISD::SETGE:  return ARMCC::GE;
1170   case ISD::SETLT:  return ARMCC::LT;
1171   case ISD::SETLE:  return ARMCC::LE;
1172   case ISD::SETUGT: return ARMCC::HI;
1173   case ISD::SETUGE: return ARMCC::HS;
1174   case ISD::SETULT: return ARMCC::LO;
1175   case ISD::SETULE: return ARMCC::LS;
1176   }
1177 }
1178
1179 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1180 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1181                         ARMCC::CondCodes &CondCode2) {
1182   CondCode2 = ARMCC::AL;
1183   switch (CC) {
1184   default: llvm_unreachable("Unknown FP condition!");
1185   case ISD::SETEQ:
1186   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1187   case ISD::SETGT:
1188   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1189   case ISD::SETGE:
1190   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1191   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1192   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1193   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1194   case ISD::SETO:   CondCode = ARMCC::VC; break;
1195   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1196   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1197   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1198   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1199   case ISD::SETLT:
1200   case ISD::SETULT: CondCode = ARMCC::LT; break;
1201   case ISD::SETLE:
1202   case ISD::SETULE: CondCode = ARMCC::LE; break;
1203   case ISD::SETNE:
1204   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1205   }
1206 }
1207
1208 //===----------------------------------------------------------------------===//
1209 //                      Calling Convention Implementation
1210 //===----------------------------------------------------------------------===//
1211
1212 #include "ARMGenCallingConv.inc"
1213
1214 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1215 /// given CallingConvention value.
1216 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1217                                                  bool Return,
1218                                                  bool isVarArg) const {
1219   switch (CC) {
1220   default:
1221     llvm_unreachable("Unsupported calling convention");
1222   case CallingConv::Fast:
1223     if (Subtarget->hasVFP2() && !isVarArg) {
1224       if (!Subtarget->isAAPCS_ABI())
1225         return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1226       // For AAPCS ABI targets, just use VFP variant of the calling convention.
1227       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1228     }
1229     // Fallthrough
1230   case CallingConv::C: {
1231     // Use target triple & subtarget features to do actual dispatch.
1232     if (!Subtarget->isAAPCS_ABI())
1233       return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1234     else if (Subtarget->hasVFP2() &&
1235              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1236              !isVarArg)
1237       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1238     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1239   }
1240   case CallingConv::ARM_AAPCS_VFP:
1241     if (!isVarArg)
1242       return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1243     // Fallthrough
1244   case CallingConv::ARM_AAPCS:
1245     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1246   case CallingConv::ARM_APCS:
1247     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1248   case CallingConv::GHC:
1249     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1250   }
1251 }
1252
1253 /// LowerCallResult - Lower the result values of a call into the
1254 /// appropriate copies out of appropriate physical registers.
1255 SDValue
1256 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1257                                    CallingConv::ID CallConv, bool isVarArg,
1258                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1259                                    SDLoc dl, SelectionDAG &DAG,
1260                                    SmallVectorImpl<SDValue> &InVals,
1261                                    bool isThisReturn, SDValue ThisVal) const {
1262
1263   // Assign locations to each value returned by this call.
1264   SmallVector<CCValAssign, 16> RVLocs;
1265   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1266                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1267   CCInfo.AnalyzeCallResult(Ins,
1268                            CCAssignFnForNode(CallConv, /* Return*/ true,
1269                                              isVarArg));
1270
1271   // Copy all of the result registers out of their specified physreg.
1272   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1273     CCValAssign VA = RVLocs[i];
1274
1275     // Pass 'this' value directly from the argument to return value, to avoid
1276     // reg unit interference
1277     if (i == 0 && isThisReturn) {
1278       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1279              "unexpected return calling convention register assignment");
1280       InVals.push_back(ThisVal);
1281       continue;
1282     }
1283
1284     SDValue Val;
1285     if (VA.needsCustom()) {
1286       // Handle f64 or half of a v2f64.
1287       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1288                                       InFlag);
1289       Chain = Lo.getValue(1);
1290       InFlag = Lo.getValue(2);
1291       VA = RVLocs[++i]; // skip ahead to next loc
1292       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1293                                       InFlag);
1294       Chain = Hi.getValue(1);
1295       InFlag = Hi.getValue(2);
1296       if (!Subtarget->isLittle())
1297         std::swap (Lo, Hi);
1298       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1299
1300       if (VA.getLocVT() == MVT::v2f64) {
1301         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1302         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1303                           DAG.getConstant(0, MVT::i32));
1304
1305         VA = RVLocs[++i]; // skip ahead to next loc
1306         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1307         Chain = Lo.getValue(1);
1308         InFlag = Lo.getValue(2);
1309         VA = RVLocs[++i]; // skip ahead to next loc
1310         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1311         Chain = Hi.getValue(1);
1312         InFlag = Hi.getValue(2);
1313         if (!Subtarget->isLittle())
1314           std::swap (Lo, Hi);
1315         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1316         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1317                           DAG.getConstant(1, MVT::i32));
1318       }
1319     } else {
1320       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1321                                InFlag);
1322       Chain = Val.getValue(1);
1323       InFlag = Val.getValue(2);
1324     }
1325
1326     switch (VA.getLocInfo()) {
1327     default: llvm_unreachable("Unknown loc info!");
1328     case CCValAssign::Full: break;
1329     case CCValAssign::BCvt:
1330       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1331       break;
1332     }
1333
1334     InVals.push_back(Val);
1335   }
1336
1337   return Chain;
1338 }
1339
1340 /// LowerMemOpCallTo - Store the argument to the stack.
1341 SDValue
1342 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1343                                     SDValue StackPtr, SDValue Arg,
1344                                     SDLoc dl, SelectionDAG &DAG,
1345                                     const CCValAssign &VA,
1346                                     ISD::ArgFlagsTy Flags) const {
1347   unsigned LocMemOffset = VA.getLocMemOffset();
1348   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1349   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1350   return DAG.getStore(Chain, dl, Arg, PtrOff,
1351                       MachinePointerInfo::getStack(LocMemOffset),
1352                       false, false, 0);
1353 }
1354
1355 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1356                                          SDValue Chain, SDValue &Arg,
1357                                          RegsToPassVector &RegsToPass,
1358                                          CCValAssign &VA, CCValAssign &NextVA,
1359                                          SDValue &StackPtr,
1360                                          SmallVectorImpl<SDValue> &MemOpChains,
1361                                          ISD::ArgFlagsTy Flags) const {
1362
1363   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1364                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1365   unsigned id = Subtarget->isLittle() ? 0 : 1;
1366   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1367
1368   if (NextVA.isRegLoc())
1369     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1370   else {
1371     assert(NextVA.isMemLoc());
1372     if (!StackPtr.getNode())
1373       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1374
1375     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1376                                            dl, DAG, NextVA,
1377                                            Flags));
1378   }
1379 }
1380
1381 /// LowerCall - Lowering a call into a callseq_start <-
1382 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1383 /// nodes.
1384 SDValue
1385 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1386                              SmallVectorImpl<SDValue> &InVals) const {
1387   SelectionDAG &DAG                     = CLI.DAG;
1388   SDLoc &dl                          = CLI.DL;
1389   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1390   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1391   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1392   SDValue Chain                         = CLI.Chain;
1393   SDValue Callee                        = CLI.Callee;
1394   bool &isTailCall                      = CLI.IsTailCall;
1395   CallingConv::ID CallConv              = CLI.CallConv;
1396   bool doesNotRet                       = CLI.DoesNotReturn;
1397   bool isVarArg                         = CLI.IsVarArg;
1398
1399   MachineFunction &MF = DAG.getMachineFunction();
1400   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1401   bool isThisReturn   = false;
1402   bool isSibCall      = false;
1403
1404   // Disable tail calls if they're not supported.
1405   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1406     isTailCall = false;
1407
1408   if (isTailCall) {
1409     // Check if it's really possible to do a tail call.
1410     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1411                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1412                                                    Outs, OutVals, Ins, DAG);
1413     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1414       report_fatal_error("failed to perform tail call elimination on a call "
1415                          "site marked musttail");
1416     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1417     // detected sibcalls.
1418     if (isTailCall) {
1419       ++NumTailCalls;
1420       isSibCall = true;
1421     }
1422   }
1423
1424   // Analyze operands of the call, assigning locations to each operand.
1425   SmallVector<CCValAssign, 16> ArgLocs;
1426   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1427                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1428   CCInfo.AnalyzeCallOperands(Outs,
1429                              CCAssignFnForNode(CallConv, /* Return*/ false,
1430                                                isVarArg));
1431
1432   // Get a count of how many bytes are to be pushed on the stack.
1433   unsigned NumBytes = CCInfo.getNextStackOffset();
1434
1435   // For tail calls, memory operands are available in our caller's stack.
1436   if (isSibCall)
1437     NumBytes = 0;
1438
1439   // Adjust the stack pointer for the new arguments...
1440   // These operations are automatically eliminated by the prolog/epilog pass
1441   if (!isSibCall)
1442     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1443                                  dl);
1444
1445   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1446
1447   RegsToPassVector RegsToPass;
1448   SmallVector<SDValue, 8> MemOpChains;
1449
1450   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1451   // of tail call optimization, arguments are handled later.
1452   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1453        i != e;
1454        ++i, ++realArgIdx) {
1455     CCValAssign &VA = ArgLocs[i];
1456     SDValue Arg = OutVals[realArgIdx];
1457     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1458     bool isByVal = Flags.isByVal();
1459
1460     // Promote the value if needed.
1461     switch (VA.getLocInfo()) {
1462     default: llvm_unreachable("Unknown loc info!");
1463     case CCValAssign::Full: break;
1464     case CCValAssign::SExt:
1465       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1466       break;
1467     case CCValAssign::ZExt:
1468       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1469       break;
1470     case CCValAssign::AExt:
1471       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1472       break;
1473     case CCValAssign::BCvt:
1474       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1475       break;
1476     }
1477
1478     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1479     if (VA.needsCustom()) {
1480       if (VA.getLocVT() == MVT::v2f64) {
1481         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1482                                   DAG.getConstant(0, MVT::i32));
1483         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1484                                   DAG.getConstant(1, MVT::i32));
1485
1486         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1487                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1488
1489         VA = ArgLocs[++i]; // skip ahead to next loc
1490         if (VA.isRegLoc()) {
1491           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1492                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1493         } else {
1494           assert(VA.isMemLoc());
1495
1496           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1497                                                  dl, DAG, VA, Flags));
1498         }
1499       } else {
1500         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1501                          StackPtr, MemOpChains, Flags);
1502       }
1503     } else if (VA.isRegLoc()) {
1504       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1505         assert(VA.getLocVT() == MVT::i32 &&
1506                "unexpected calling convention register assignment");
1507         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1508                "unexpected use of 'returned'");
1509         isThisReturn = true;
1510       }
1511       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1512     } else if (isByVal) {
1513       assert(VA.isMemLoc());
1514       unsigned offset = 0;
1515
1516       // True if this byval aggregate will be split between registers
1517       // and memory.
1518       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1519       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1520
1521       if (CurByValIdx < ByValArgsCount) {
1522
1523         unsigned RegBegin, RegEnd;
1524         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1525
1526         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1527         unsigned int i, j;
1528         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1529           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1530           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1531           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1532                                      MachinePointerInfo(),
1533                                      false, false, false,
1534                                      DAG.InferPtrAlignment(AddArg));
1535           MemOpChains.push_back(Load.getValue(1));
1536           RegsToPass.push_back(std::make_pair(j, Load));
1537         }
1538
1539         // If parameter size outsides register area, "offset" value
1540         // helps us to calculate stack slot for remained part properly.
1541         offset = RegEnd - RegBegin;
1542
1543         CCInfo.nextInRegsParam();
1544       }
1545
1546       if (Flags.getByValSize() > 4*offset) {
1547         unsigned LocMemOffset = VA.getLocMemOffset();
1548         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1549         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1550                                   StkPtrOff);
1551         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1552         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1553         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1554                                            MVT::i32);
1555         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1556
1557         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1558         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1559         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1560                                           Ops));
1561       }
1562     } else if (!isSibCall) {
1563       assert(VA.isMemLoc());
1564
1565       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1566                                              dl, DAG, VA, Flags));
1567     }
1568   }
1569
1570   if (!MemOpChains.empty())
1571     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1572
1573   // Build a sequence of copy-to-reg nodes chained together with token chain
1574   // and flag operands which copy the outgoing args into the appropriate regs.
1575   SDValue InFlag;
1576   // Tail call byval lowering might overwrite argument registers so in case of
1577   // tail call optimization the copies to registers are lowered later.
1578   if (!isTailCall)
1579     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1580       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1581                                RegsToPass[i].second, InFlag);
1582       InFlag = Chain.getValue(1);
1583     }
1584
1585   // For tail calls lower the arguments to the 'real' stack slot.
1586   if (isTailCall) {
1587     // Force all the incoming stack arguments to be loaded from the stack
1588     // before any new outgoing arguments are stored to the stack, because the
1589     // outgoing stack slots may alias the incoming argument stack slots, and
1590     // the alias isn't otherwise explicit. This is slightly more conservative
1591     // than necessary, because it means that each store effectively depends
1592     // on every argument instead of just those arguments it would clobber.
1593
1594     // Do not flag preceding copytoreg stuff together with the following stuff.
1595     InFlag = SDValue();
1596     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1597       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1598                                RegsToPass[i].second, InFlag);
1599       InFlag = Chain.getValue(1);
1600     }
1601     InFlag = SDValue();
1602   }
1603
1604   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1605   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1606   // node so that legalize doesn't hack it.
1607   bool isDirect = false;
1608   bool isARMFunc = false;
1609   bool isLocalARMFunc = false;
1610   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1611
1612   if (EnableARMLongCalls) {
1613     assert (getTargetMachine().getRelocationModel() == Reloc::Static
1614             && "long-calls with non-static relocation model!");
1615     // Handle a global address or an external symbol. If it's not one of
1616     // those, the target's already in a register, so we don't need to do
1617     // anything extra.
1618     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1619       const GlobalValue *GV = G->getGlobal();
1620       // Create a constant pool entry for the callee address
1621       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1622       ARMConstantPoolValue *CPV =
1623         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1624
1625       // Get the address of the callee into a register
1626       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1627       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1628       Callee = DAG.getLoad(getPointerTy(), dl,
1629                            DAG.getEntryNode(), CPAddr,
1630                            MachinePointerInfo::getConstantPool(),
1631                            false, false, false, 0);
1632     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1633       const char *Sym = S->getSymbol();
1634
1635       // Create a constant pool entry for the callee address
1636       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1637       ARMConstantPoolValue *CPV =
1638         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1639                                       ARMPCLabelIndex, 0);
1640       // Get the address of the callee into a register
1641       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1642       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1643       Callee = DAG.getLoad(getPointerTy(), dl,
1644                            DAG.getEntryNode(), CPAddr,
1645                            MachinePointerInfo::getConstantPool(),
1646                            false, false, false, 0);
1647     }
1648   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1649     const GlobalValue *GV = G->getGlobal();
1650     isDirect = true;
1651     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1652     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1653                    getTargetMachine().getRelocationModel() != Reloc::Static;
1654     isARMFunc = !Subtarget->isThumb() || isStub;
1655     // ARM call to a local ARM function is predicable.
1656     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1657     // tBX takes a register source operand.
1658     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1659       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1660       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1661                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1662     } else {
1663       // On ELF targets for PIC code, direct calls should go through the PLT
1664       unsigned OpFlags = 0;
1665       if (Subtarget->isTargetELF() &&
1666           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1667         OpFlags = ARMII::MO_PLT;
1668       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1669     }
1670   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1671     isDirect = true;
1672     bool isStub = Subtarget->isTargetMachO() &&
1673                   getTargetMachine().getRelocationModel() != Reloc::Static;
1674     isARMFunc = !Subtarget->isThumb() || isStub;
1675     // tBX takes a register source operand.
1676     const char *Sym = S->getSymbol();
1677     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1678       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1679       ARMConstantPoolValue *CPV =
1680         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1681                                       ARMPCLabelIndex, 4);
1682       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1683       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1684       Callee = DAG.getLoad(getPointerTy(), dl,
1685                            DAG.getEntryNode(), CPAddr,
1686                            MachinePointerInfo::getConstantPool(),
1687                            false, false, false, 0);
1688       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1689       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1690                            getPointerTy(), Callee, PICLabel);
1691     } else {
1692       unsigned OpFlags = 0;
1693       // On ELF targets for PIC code, direct calls should go through the PLT
1694       if (Subtarget->isTargetELF() &&
1695                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1696         OpFlags = ARMII::MO_PLT;
1697       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1698     }
1699   }
1700
1701   // FIXME: handle tail calls differently.
1702   unsigned CallOpc;
1703   bool HasMinSizeAttr = Subtarget->isMinSize();
1704   if (Subtarget->isThumb()) {
1705     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1706       CallOpc = ARMISD::CALL_NOLINK;
1707     else
1708       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1709   } else {
1710     if (!isDirect && !Subtarget->hasV5TOps())
1711       CallOpc = ARMISD::CALL_NOLINK;
1712     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1713                // Emit regular call when code size is the priority
1714                !HasMinSizeAttr)
1715       // "mov lr, pc; b _foo" to avoid confusing the RSP
1716       CallOpc = ARMISD::CALL_NOLINK;
1717     else
1718       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1719   }
1720
1721   std::vector<SDValue> Ops;
1722   Ops.push_back(Chain);
1723   Ops.push_back(Callee);
1724
1725   // Add argument registers to the end of the list so that they are known live
1726   // into the call.
1727   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1728     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1729                                   RegsToPass[i].second.getValueType()));
1730
1731   // Add a register mask operand representing the call-preserved registers.
1732   if (!isTailCall) {
1733     const uint32_t *Mask;
1734     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1735     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1736     if (isThisReturn) {
1737       // For 'this' returns, use the R0-preserving mask if applicable
1738       Mask = ARI->getThisReturnPreservedMask(CallConv);
1739       if (!Mask) {
1740         // Set isThisReturn to false if the calling convention is not one that
1741         // allows 'returned' to be modeled in this way, so LowerCallResult does
1742         // not try to pass 'this' straight through
1743         isThisReturn = false;
1744         Mask = ARI->getCallPreservedMask(CallConv);
1745       }
1746     } else
1747       Mask = ARI->getCallPreservedMask(CallConv);
1748
1749     assert(Mask && "Missing call preserved mask for calling convention");
1750     Ops.push_back(DAG.getRegisterMask(Mask));
1751   }
1752
1753   if (InFlag.getNode())
1754     Ops.push_back(InFlag);
1755
1756   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1757   if (isTailCall)
1758     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1759
1760   // Returns a chain and a flag for retval copy to use.
1761   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1762   InFlag = Chain.getValue(1);
1763
1764   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1765                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1766   if (!Ins.empty())
1767     InFlag = Chain.getValue(1);
1768
1769   // Handle result values, copying them out of physregs into vregs that we
1770   // return.
1771   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1772                          InVals, isThisReturn,
1773                          isThisReturn ? OutVals[0] : SDValue());
1774 }
1775
1776 /// HandleByVal - Every parameter *after* a byval parameter is passed
1777 /// on the stack.  Remember the next parameter register to allocate,
1778 /// and then confiscate the rest of the parameter registers to insure
1779 /// this.
1780 void
1781 ARMTargetLowering::HandleByVal(
1782     CCState *State, unsigned &size, unsigned Align) const {
1783   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1784   assert((State->getCallOrPrologue() == Prologue ||
1785           State->getCallOrPrologue() == Call) &&
1786          "unhandled ParmContext");
1787
1788   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1789     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1790       unsigned AlignInRegs = Align / 4;
1791       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1792       for (unsigned i = 0; i < Waste; ++i)
1793         reg = State->AllocateReg(GPRArgRegs, 4);
1794     }
1795     if (reg != 0) {
1796       unsigned excess = 4 * (ARM::R4 - reg);
1797
1798       // Special case when NSAA != SP and parameter size greater than size of
1799       // all remained GPR regs. In that case we can't split parameter, we must
1800       // send it to stack. We also must set NCRN to R4, so waste all
1801       // remained registers.
1802       const unsigned NSAAOffset = State->getNextStackOffset();
1803       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1804         while (State->AllocateReg(GPRArgRegs, 4))
1805           ;
1806         return;
1807       }
1808
1809       // First register for byval parameter is the first register that wasn't
1810       // allocated before this method call, so it would be "reg".
1811       // If parameter is small enough to be saved in range [reg, r4), then
1812       // the end (first after last) register would be reg + param-size-in-regs,
1813       // else parameter would be splitted between registers and stack,
1814       // end register would be r4 in this case.
1815       unsigned ByValRegBegin = reg;
1816       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1817       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1818       // Note, first register is allocated in the beginning of function already,
1819       // allocate remained amount of registers we need.
1820       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1821         State->AllocateReg(GPRArgRegs, 4);
1822       // A byval parameter that is split between registers and memory needs its
1823       // size truncated here.
1824       // In the case where the entire structure fits in registers, we set the
1825       // size in memory to zero.
1826       if (size < excess)
1827         size = 0;
1828       else
1829         size -= excess;
1830     }
1831   }
1832 }
1833
1834 /// MatchingStackOffset - Return true if the given stack call argument is
1835 /// already available in the same position (relatively) of the caller's
1836 /// incoming argument stack.
1837 static
1838 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1839                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1840                          const TargetInstrInfo *TII) {
1841   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1842   int FI = INT_MAX;
1843   if (Arg.getOpcode() == ISD::CopyFromReg) {
1844     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1845     if (!TargetRegisterInfo::isVirtualRegister(VR))
1846       return false;
1847     MachineInstr *Def = MRI->getVRegDef(VR);
1848     if (!Def)
1849       return false;
1850     if (!Flags.isByVal()) {
1851       if (!TII->isLoadFromStackSlot(Def, FI))
1852         return false;
1853     } else {
1854       return false;
1855     }
1856   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1857     if (Flags.isByVal())
1858       // ByVal argument is passed in as a pointer but it's now being
1859       // dereferenced. e.g.
1860       // define @foo(%struct.X* %A) {
1861       //   tail call @bar(%struct.X* byval %A)
1862       // }
1863       return false;
1864     SDValue Ptr = Ld->getBasePtr();
1865     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1866     if (!FINode)
1867       return false;
1868     FI = FINode->getIndex();
1869   } else
1870     return false;
1871
1872   assert(FI != INT_MAX);
1873   if (!MFI->isFixedObjectIndex(FI))
1874     return false;
1875   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1876 }
1877
1878 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1879 /// for tail call optimization. Targets which want to do tail call
1880 /// optimization should implement this function.
1881 bool
1882 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1883                                                      CallingConv::ID CalleeCC,
1884                                                      bool isVarArg,
1885                                                      bool isCalleeStructRet,
1886                                                      bool isCallerStructRet,
1887                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1888                                     const SmallVectorImpl<SDValue> &OutVals,
1889                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1890                                                      SelectionDAG& DAG) const {
1891   const Function *CallerF = DAG.getMachineFunction().getFunction();
1892   CallingConv::ID CallerCC = CallerF->getCallingConv();
1893   bool CCMatch = CallerCC == CalleeCC;
1894
1895   // Look for obvious safe cases to perform tail call optimization that do not
1896   // require ABI changes. This is what gcc calls sibcall.
1897
1898   // Do not sibcall optimize vararg calls unless the call site is not passing
1899   // any arguments.
1900   if (isVarArg && !Outs.empty())
1901     return false;
1902
1903   // Exception-handling functions need a special set of instructions to indicate
1904   // a return to the hardware. Tail-calling another function would probably
1905   // break this.
1906   if (CallerF->hasFnAttribute("interrupt"))
1907     return false;
1908
1909   // Also avoid sibcall optimization if either caller or callee uses struct
1910   // return semantics.
1911   if (isCalleeStructRet || isCallerStructRet)
1912     return false;
1913
1914   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1915   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1916   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1917   // support in the assembler and linker to be used. This would need to be
1918   // fixed to fully support tail calls in Thumb1.
1919   //
1920   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1921   // LR.  This means if we need to reload LR, it takes an extra instructions,
1922   // which outweighs the value of the tail call; but here we don't know yet
1923   // whether LR is going to be used.  Probably the right approach is to
1924   // generate the tail call here and turn it back into CALL/RET in
1925   // emitEpilogue if LR is used.
1926
1927   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1928   // but we need to make sure there are enough registers; the only valid
1929   // registers are the 4 used for parameters.  We don't currently do this
1930   // case.
1931   if (Subtarget->isThumb1Only())
1932     return false;
1933
1934   // If the calling conventions do not match, then we'd better make sure the
1935   // results are returned in the same way as what the caller expects.
1936   if (!CCMatch) {
1937     SmallVector<CCValAssign, 16> RVLocs1;
1938     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1939                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1940     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1941
1942     SmallVector<CCValAssign, 16> RVLocs2;
1943     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1944                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1945     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1946
1947     if (RVLocs1.size() != RVLocs2.size())
1948       return false;
1949     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1950       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1951         return false;
1952       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1953         return false;
1954       if (RVLocs1[i].isRegLoc()) {
1955         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1956           return false;
1957       } else {
1958         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1959           return false;
1960       }
1961     }
1962   }
1963
1964   // If Caller's vararg or byval argument has been split between registers and
1965   // stack, do not perform tail call, since part of the argument is in caller's
1966   // local frame.
1967   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1968                                       getInfo<ARMFunctionInfo>();
1969   if (AFI_Caller->getArgRegsSaveSize())
1970     return false;
1971
1972   // If the callee takes no arguments then go on to check the results of the
1973   // call.
1974   if (!Outs.empty()) {
1975     // Check if stack adjustment is needed. For now, do not do this if any
1976     // argument is passed on the stack.
1977     SmallVector<CCValAssign, 16> ArgLocs;
1978     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1979                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1980     CCInfo.AnalyzeCallOperands(Outs,
1981                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1982     if (CCInfo.getNextStackOffset()) {
1983       MachineFunction &MF = DAG.getMachineFunction();
1984
1985       // Check if the arguments are already laid out in the right way as
1986       // the caller's fixed stack objects.
1987       MachineFrameInfo *MFI = MF.getFrameInfo();
1988       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1989       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1990       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1991            i != e;
1992            ++i, ++realArgIdx) {
1993         CCValAssign &VA = ArgLocs[i];
1994         EVT RegVT = VA.getLocVT();
1995         SDValue Arg = OutVals[realArgIdx];
1996         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1997         if (VA.getLocInfo() == CCValAssign::Indirect)
1998           return false;
1999         if (VA.needsCustom()) {
2000           // f64 and vector types are split into multiple registers or
2001           // register/stack-slot combinations.  The types will not match
2002           // the registers; give up on memory f64 refs until we figure
2003           // out what to do about this.
2004           if (!VA.isRegLoc())
2005             return false;
2006           if (!ArgLocs[++i].isRegLoc())
2007             return false;
2008           if (RegVT == MVT::v2f64) {
2009             if (!ArgLocs[++i].isRegLoc())
2010               return false;
2011             if (!ArgLocs[++i].isRegLoc())
2012               return false;
2013           }
2014         } else if (!VA.isRegLoc()) {
2015           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2016                                    MFI, MRI, TII))
2017             return false;
2018         }
2019       }
2020     }
2021   }
2022
2023   return true;
2024 }
2025
2026 bool
2027 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2028                                   MachineFunction &MF, bool isVarArg,
2029                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2030                                   LLVMContext &Context) const {
2031   SmallVector<CCValAssign, 16> RVLocs;
2032   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2033   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2034                                                     isVarArg));
2035 }
2036
2037 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2038                                     SDLoc DL, SelectionDAG &DAG) {
2039   const MachineFunction &MF = DAG.getMachineFunction();
2040   const Function *F = MF.getFunction();
2041
2042   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2043
2044   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2045   // version of the "preferred return address". These offsets affect the return
2046   // instruction if this is a return from PL1 without hypervisor extensions.
2047   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2048   //    SWI:     0      "subs pc, lr, #0"
2049   //    ABORT:   +4     "subs pc, lr, #4"
2050   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2051   // UNDEF varies depending on where the exception came from ARM or Thumb
2052   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2053
2054   int64_t LROffset;
2055   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2056       IntKind == "ABORT")
2057     LROffset = 4;
2058   else if (IntKind == "SWI" || IntKind == "UNDEF")
2059     LROffset = 0;
2060   else
2061     report_fatal_error("Unsupported interrupt attribute. If present, value "
2062                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2063
2064   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2065
2066   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2067 }
2068
2069 SDValue
2070 ARMTargetLowering::LowerReturn(SDValue Chain,
2071                                CallingConv::ID CallConv, bool isVarArg,
2072                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2073                                const SmallVectorImpl<SDValue> &OutVals,
2074                                SDLoc dl, SelectionDAG &DAG) const {
2075
2076   // CCValAssign - represent the assignment of the return value to a location.
2077   SmallVector<CCValAssign, 16> RVLocs;
2078
2079   // CCState - Info about the registers and stack slots.
2080   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2081                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2082
2083   // Analyze outgoing return values.
2084   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2085                                                isVarArg));
2086
2087   SDValue Flag;
2088   SmallVector<SDValue, 4> RetOps;
2089   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2090   bool isLittleEndian = Subtarget->isLittle();
2091
2092   // Copy the result values into the output registers.
2093   for (unsigned i = 0, realRVLocIdx = 0;
2094        i != RVLocs.size();
2095        ++i, ++realRVLocIdx) {
2096     CCValAssign &VA = RVLocs[i];
2097     assert(VA.isRegLoc() && "Can only return in registers!");
2098
2099     SDValue Arg = OutVals[realRVLocIdx];
2100
2101     switch (VA.getLocInfo()) {
2102     default: llvm_unreachable("Unknown loc info!");
2103     case CCValAssign::Full: break;
2104     case CCValAssign::BCvt:
2105       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2106       break;
2107     }
2108
2109     if (VA.needsCustom()) {
2110       if (VA.getLocVT() == MVT::v2f64) {
2111         // Extract the first half and return it in two registers.
2112         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2113                                    DAG.getConstant(0, MVT::i32));
2114         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2115                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2116
2117         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2118                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2119                                  Flag);
2120         Flag = Chain.getValue(1);
2121         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2122         VA = RVLocs[++i]; // skip ahead to next loc
2123         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2124                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2125                                  Flag);
2126         Flag = Chain.getValue(1);
2127         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2128         VA = RVLocs[++i]; // skip ahead to next loc
2129
2130         // Extract the 2nd half and fall through to handle it as an f64 value.
2131         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2132                           DAG.getConstant(1, MVT::i32));
2133       }
2134       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2135       // available.
2136       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2137                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2138       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2139                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2140                                Flag);
2141       Flag = Chain.getValue(1);
2142       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2143       VA = RVLocs[++i]; // skip ahead to next loc
2144       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2145                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2146                                Flag);
2147     } else
2148       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2149
2150     // Guarantee that all emitted copies are
2151     // stuck together, avoiding something bad.
2152     Flag = Chain.getValue(1);
2153     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2154   }
2155
2156   // Update chain and glue.
2157   RetOps[0] = Chain;
2158   if (Flag.getNode())
2159     RetOps.push_back(Flag);
2160
2161   // CPUs which aren't M-class use a special sequence to return from
2162   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2163   // though we use "subs pc, lr, #N").
2164   //
2165   // M-class CPUs actually use a normal return sequence with a special
2166   // (hardware-provided) value in LR, so the normal code path works.
2167   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2168       !Subtarget->isMClass()) {
2169     if (Subtarget->isThumb1Only())
2170       report_fatal_error("interrupt attribute is not supported in Thumb1");
2171     return LowerInterruptReturn(RetOps, dl, DAG);
2172   }
2173
2174   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2175 }
2176
2177 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2178   if (N->getNumValues() != 1)
2179     return false;
2180   if (!N->hasNUsesOfValue(1, 0))
2181     return false;
2182
2183   SDValue TCChain = Chain;
2184   SDNode *Copy = *N->use_begin();
2185   if (Copy->getOpcode() == ISD::CopyToReg) {
2186     // If the copy has a glue operand, we conservatively assume it isn't safe to
2187     // perform a tail call.
2188     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2189       return false;
2190     TCChain = Copy->getOperand(0);
2191   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2192     SDNode *VMov = Copy;
2193     // f64 returned in a pair of GPRs.
2194     SmallPtrSet<SDNode*, 2> Copies;
2195     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2196          UI != UE; ++UI) {
2197       if (UI->getOpcode() != ISD::CopyToReg)
2198         return false;
2199       Copies.insert(*UI);
2200     }
2201     if (Copies.size() > 2)
2202       return false;
2203
2204     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2205          UI != UE; ++UI) {
2206       SDValue UseChain = UI->getOperand(0);
2207       if (Copies.count(UseChain.getNode()))
2208         // Second CopyToReg
2209         Copy = *UI;
2210       else
2211         // First CopyToReg
2212         TCChain = UseChain;
2213     }
2214   } else if (Copy->getOpcode() == ISD::BITCAST) {
2215     // f32 returned in a single GPR.
2216     if (!Copy->hasOneUse())
2217       return false;
2218     Copy = *Copy->use_begin();
2219     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2220       return false;
2221     TCChain = Copy->getOperand(0);
2222   } else {
2223     return false;
2224   }
2225
2226   bool HasRet = false;
2227   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2228        UI != UE; ++UI) {
2229     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2230         UI->getOpcode() != ARMISD::INTRET_FLAG)
2231       return false;
2232     HasRet = true;
2233   }
2234
2235   if (!HasRet)
2236     return false;
2237
2238   Chain = TCChain;
2239   return true;
2240 }
2241
2242 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2243   if (!Subtarget->supportsTailCall())
2244     return false;
2245
2246   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2247     return false;
2248
2249   return !Subtarget->isThumb1Only();
2250 }
2251
2252 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2253 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2254 // one of the above mentioned nodes. It has to be wrapped because otherwise
2255 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2256 // be used to form addressing mode. These wrapped nodes will be selected
2257 // into MOVi.
2258 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2259   EVT PtrVT = Op.getValueType();
2260   // FIXME there is no actual debug info here
2261   SDLoc dl(Op);
2262   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2263   SDValue Res;
2264   if (CP->isMachineConstantPoolEntry())
2265     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2266                                     CP->getAlignment());
2267   else
2268     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2269                                     CP->getAlignment());
2270   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2271 }
2272
2273 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2274   return MachineJumpTableInfo::EK_Inline;
2275 }
2276
2277 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2278                                              SelectionDAG &DAG) const {
2279   MachineFunction &MF = DAG.getMachineFunction();
2280   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2281   unsigned ARMPCLabelIndex = 0;
2282   SDLoc DL(Op);
2283   EVT PtrVT = getPointerTy();
2284   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2285   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2286   SDValue CPAddr;
2287   if (RelocM == Reloc::Static) {
2288     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2289   } else {
2290     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2291     ARMPCLabelIndex = AFI->createPICLabelUId();
2292     ARMConstantPoolValue *CPV =
2293       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2294                                       ARMCP::CPBlockAddress, PCAdj);
2295     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2296   }
2297   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2298   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2299                                MachinePointerInfo::getConstantPool(),
2300                                false, false, false, 0);
2301   if (RelocM == Reloc::Static)
2302     return Result;
2303   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2304   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2305 }
2306
2307 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2308 SDValue
2309 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2310                                                  SelectionDAG &DAG) const {
2311   SDLoc dl(GA);
2312   EVT PtrVT = getPointerTy();
2313   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2314   MachineFunction &MF = DAG.getMachineFunction();
2315   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2316   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2317   ARMConstantPoolValue *CPV =
2318     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2319                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2320   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2321   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2322   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2323                          MachinePointerInfo::getConstantPool(),
2324                          false, false, false, 0);
2325   SDValue Chain = Argument.getValue(1);
2326
2327   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2328   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2329
2330   // call __tls_get_addr.
2331   ArgListTy Args;
2332   ArgListEntry Entry;
2333   Entry.Node = Argument;
2334   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2335   Args.push_back(Entry);
2336   // FIXME: is there useful debug info available here?
2337   TargetLowering::CallLoweringInfo CLI(Chain,
2338                 (Type *) Type::getInt32Ty(*DAG.getContext()),
2339                 false, false, false, false,
2340                 0, CallingConv::C, /*isTailCall=*/false,
2341                 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
2342                 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG, dl);
2343   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2344   return CallResult.first;
2345 }
2346
2347 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2348 // "local exec" model.
2349 SDValue
2350 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2351                                         SelectionDAG &DAG,
2352                                         TLSModel::Model model) const {
2353   const GlobalValue *GV = GA->getGlobal();
2354   SDLoc dl(GA);
2355   SDValue Offset;
2356   SDValue Chain = DAG.getEntryNode();
2357   EVT PtrVT = getPointerTy();
2358   // Get the Thread Pointer
2359   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2360
2361   if (model == TLSModel::InitialExec) {
2362     MachineFunction &MF = DAG.getMachineFunction();
2363     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2364     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2365     // Initial exec model.
2366     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2367     ARMConstantPoolValue *CPV =
2368       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2369                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2370                                       true);
2371     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2372     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2373     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2374                          MachinePointerInfo::getConstantPool(),
2375                          false, false, false, 0);
2376     Chain = Offset.getValue(1);
2377
2378     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2379     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2380
2381     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2382                          MachinePointerInfo::getConstantPool(),
2383                          false, false, false, 0);
2384   } else {
2385     // local exec model
2386     assert(model == TLSModel::LocalExec);
2387     ARMConstantPoolValue *CPV =
2388       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2389     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2390     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2391     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2392                          MachinePointerInfo::getConstantPool(),
2393                          false, false, false, 0);
2394   }
2395
2396   // The address of the thread local variable is the add of the thread
2397   // pointer with the offset of the variable.
2398   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2399 }
2400
2401 SDValue
2402 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2403   // TODO: implement the "local dynamic" model
2404   assert(Subtarget->isTargetELF() &&
2405          "TLS not implemented for non-ELF targets");
2406   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2407
2408   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2409
2410   switch (model) {
2411     case TLSModel::GeneralDynamic:
2412     case TLSModel::LocalDynamic:
2413       return LowerToTLSGeneralDynamicModel(GA, DAG);
2414     case TLSModel::InitialExec:
2415     case TLSModel::LocalExec:
2416       return LowerToTLSExecModels(GA, DAG, model);
2417   }
2418   llvm_unreachable("bogus TLS model");
2419 }
2420
2421 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2422                                                  SelectionDAG &DAG) const {
2423   EVT PtrVT = getPointerTy();
2424   SDLoc dl(Op);
2425   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2426   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2427     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2428     ARMConstantPoolValue *CPV =
2429       ARMConstantPoolConstant::Create(GV,
2430                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2431     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2432     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2433     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2434                                  CPAddr,
2435                                  MachinePointerInfo::getConstantPool(),
2436                                  false, false, false, 0);
2437     SDValue Chain = Result.getValue(1);
2438     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2439     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2440     if (!UseGOTOFF)
2441       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2442                            MachinePointerInfo::getGOT(),
2443                            false, false, false, 0);
2444     return Result;
2445   }
2446
2447   // If we have T2 ops, we can materialize the address directly via movt/movw
2448   // pair. This is always cheaper.
2449   if (Subtarget->useMovt()) {
2450     ++NumMovwMovt;
2451     // FIXME: Once remat is capable of dealing with instructions with register
2452     // operands, expand this into two nodes.
2453     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2454                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2455   } else {
2456     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2457     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2458     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2459                        MachinePointerInfo::getConstantPool(),
2460                        false, false, false, 0);
2461   }
2462 }
2463
2464 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2465                                                     SelectionDAG &DAG) const {
2466   EVT PtrVT = getPointerTy();
2467   SDLoc dl(Op);
2468   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2469   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2470
2471   if (Subtarget->useMovt())
2472     ++NumMovwMovt;
2473
2474   // FIXME: Once remat is capable of dealing with instructions with register
2475   // operands, expand this into multiple nodes
2476   unsigned Wrapper =
2477       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2478
2479   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2480   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2481
2482   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2483     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2484                          MachinePointerInfo::getGOT(), false, false, false, 0);
2485   return Result;
2486 }
2487
2488 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2489                                                     SelectionDAG &DAG) const {
2490   assert(Subtarget->isTargetELF() &&
2491          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2492   MachineFunction &MF = DAG.getMachineFunction();
2493   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2494   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2495   EVT PtrVT = getPointerTy();
2496   SDLoc dl(Op);
2497   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2498   ARMConstantPoolValue *CPV =
2499     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2500                                   ARMPCLabelIndex, PCAdj);
2501   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2502   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2503   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2504                                MachinePointerInfo::getConstantPool(),
2505                                false, false, false, 0);
2506   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2507   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2508 }
2509
2510 SDValue
2511 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2512   SDLoc dl(Op);
2513   SDValue Val = DAG.getConstant(0, MVT::i32);
2514   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2515                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2516                      Op.getOperand(1), Val);
2517 }
2518
2519 SDValue
2520 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2521   SDLoc dl(Op);
2522   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2523                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2524 }
2525
2526 SDValue
2527 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2528                                           const ARMSubtarget *Subtarget) const {
2529   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2530   SDLoc dl(Op);
2531   switch (IntNo) {
2532   default: return SDValue();    // Don't custom lower most intrinsics.
2533   case Intrinsic::arm_thread_pointer: {
2534     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2535     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2536   }
2537   case Intrinsic::eh_sjlj_lsda: {
2538     MachineFunction &MF = DAG.getMachineFunction();
2539     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2540     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2541     EVT PtrVT = getPointerTy();
2542     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2543     SDValue CPAddr;
2544     unsigned PCAdj = (RelocM != Reloc::PIC_)
2545       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2546     ARMConstantPoolValue *CPV =
2547       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2548                                       ARMCP::CPLSDA, PCAdj);
2549     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2550     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2551     SDValue Result =
2552       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2553                   MachinePointerInfo::getConstantPool(),
2554                   false, false, false, 0);
2555
2556     if (RelocM == Reloc::PIC_) {
2557       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2558       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2559     }
2560     return Result;
2561   }
2562   case Intrinsic::arm_neon_vmulls:
2563   case Intrinsic::arm_neon_vmullu: {
2564     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2565       ? ARMISD::VMULLs : ARMISD::VMULLu;
2566     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2567                        Op.getOperand(1), Op.getOperand(2));
2568   }
2569   }
2570 }
2571
2572 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2573                                  const ARMSubtarget *Subtarget) {
2574   // FIXME: handle "fence singlethread" more efficiently.
2575   SDLoc dl(Op);
2576   if (!Subtarget->hasDataBarrier()) {
2577     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2578     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2579     // here.
2580     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2581            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2582     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2583                        DAG.getConstant(0, MVT::i32));
2584   }
2585
2586   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2587   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2588   unsigned Domain = ARM_MB::ISH;
2589   if (Subtarget->isMClass()) {
2590     // Only a full system barrier exists in the M-class architectures.
2591     Domain = ARM_MB::SY;
2592   } else if (Subtarget->isSwift() && Ord == Release) {
2593     // Swift happens to implement ISHST barriers in a way that's compatible with
2594     // Release semantics but weaker than ISH so we'd be fools not to use
2595     // it. Beware: other processors probably don't!
2596     Domain = ARM_MB::ISHST;
2597   }
2598
2599   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2600                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2601                      DAG.getConstant(Domain, MVT::i32));
2602 }
2603
2604 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2605                              const ARMSubtarget *Subtarget) {
2606   // ARM pre v5TE and Thumb1 does not have preload instructions.
2607   if (!(Subtarget->isThumb2() ||
2608         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2609     // Just preserve the chain.
2610     return Op.getOperand(0);
2611
2612   SDLoc dl(Op);
2613   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2614   if (!isRead &&
2615       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2616     // ARMv7 with MP extension has PLDW.
2617     return Op.getOperand(0);
2618
2619   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2620   if (Subtarget->isThumb()) {
2621     // Invert the bits.
2622     isRead = ~isRead & 1;
2623     isData = ~isData & 1;
2624   }
2625
2626   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2627                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2628                      DAG.getConstant(isData, MVT::i32));
2629 }
2630
2631 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2632   MachineFunction &MF = DAG.getMachineFunction();
2633   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2634
2635   // vastart just stores the address of the VarArgsFrameIndex slot into the
2636   // memory location argument.
2637   SDLoc dl(Op);
2638   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2639   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2640   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2641   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2642                       MachinePointerInfo(SV), false, false, 0);
2643 }
2644
2645 SDValue
2646 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2647                                         SDValue &Root, SelectionDAG &DAG,
2648                                         SDLoc dl) const {
2649   MachineFunction &MF = DAG.getMachineFunction();
2650   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2651
2652   const TargetRegisterClass *RC;
2653   if (AFI->isThumb1OnlyFunction())
2654     RC = &ARM::tGPRRegClass;
2655   else
2656     RC = &ARM::GPRRegClass;
2657
2658   // Transform the arguments stored in physical registers into virtual ones.
2659   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2660   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2661
2662   SDValue ArgValue2;
2663   if (NextVA.isMemLoc()) {
2664     MachineFrameInfo *MFI = MF.getFrameInfo();
2665     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2666
2667     // Create load node to retrieve arguments from the stack.
2668     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2669     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2670                             MachinePointerInfo::getFixedStack(FI),
2671                             false, false, false, 0);
2672   } else {
2673     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2674     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2675   }
2676   if (!Subtarget->isLittle())
2677     std::swap (ArgValue, ArgValue2);
2678   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2679 }
2680
2681 void
2682 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2683                                   unsigned InRegsParamRecordIdx,
2684                                   unsigned ArgSize,
2685                                   unsigned &ArgRegsSize,
2686                                   unsigned &ArgRegsSaveSize)
2687   const {
2688   unsigned NumGPRs;
2689   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2690     unsigned RBegin, REnd;
2691     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2692     NumGPRs = REnd - RBegin;
2693   } else {
2694     unsigned int firstUnalloced;
2695     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2696                                                 sizeof(GPRArgRegs) /
2697                                                 sizeof(GPRArgRegs[0]));
2698     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2699   }
2700
2701   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2702   ArgRegsSize = NumGPRs * 4;
2703
2704   // If parameter is split between stack and GPRs...
2705   if (NumGPRs && Align > 4 &&
2706       (ArgRegsSize < ArgSize ||
2707         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2708     // Add padding for part of param recovered from GPRs.  For example,
2709     // if Align == 8, its last byte must be at address K*8 - 1.
2710     // We need to do it, since remained (stack) part of parameter has
2711     // stack alignment, and we need to "attach" "GPRs head" without gaps
2712     // to it:
2713     // Stack:
2714     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2715     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2716     //
2717     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2718     unsigned Padding =
2719         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2720     ArgRegsSaveSize = ArgRegsSize + Padding;
2721   } else
2722     // We don't need to extend regs save size for byval parameters if they
2723     // are passed via GPRs only.
2724     ArgRegsSaveSize = ArgRegsSize;
2725 }
2726
2727 // The remaining GPRs hold either the beginning of variable-argument
2728 // data, or the beginning of an aggregate passed by value (usually
2729 // byval).  Either way, we allocate stack slots adjacent to the data
2730 // provided by our caller, and store the unallocated registers there.
2731 // If this is a variadic function, the va_list pointer will begin with
2732 // these values; otherwise, this reassembles a (byval) structure that
2733 // was split between registers and memory.
2734 // Return: The frame index registers were stored into.
2735 int
2736 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2737                                   SDLoc dl, SDValue &Chain,
2738                                   const Value *OrigArg,
2739                                   unsigned InRegsParamRecordIdx,
2740                                   unsigned OffsetFromOrigArg,
2741                                   unsigned ArgOffset,
2742                                   unsigned ArgSize,
2743                                   bool ForceMutable,
2744                                   unsigned ByValStoreOffset,
2745                                   unsigned TotalArgRegsSaveSize) const {
2746
2747   // Currently, two use-cases possible:
2748   // Case #1. Non-var-args function, and we meet first byval parameter.
2749   //          Setup first unallocated register as first byval register;
2750   //          eat all remained registers
2751   //          (these two actions are performed by HandleByVal method).
2752   //          Then, here, we initialize stack frame with
2753   //          "store-reg" instructions.
2754   // Case #2. Var-args function, that doesn't contain byval parameters.
2755   //          The same: eat all remained unallocated registers,
2756   //          initialize stack frame.
2757
2758   MachineFunction &MF = DAG.getMachineFunction();
2759   MachineFrameInfo *MFI = MF.getFrameInfo();
2760   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2761   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2762   unsigned RBegin, REnd;
2763   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2764     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2765     firstRegToSaveIndex = RBegin - ARM::R0;
2766     lastRegToSaveIndex = REnd - ARM::R0;
2767   } else {
2768     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2769       (GPRArgRegs, array_lengthof(GPRArgRegs));
2770     lastRegToSaveIndex = 4;
2771   }
2772
2773   unsigned ArgRegsSize, ArgRegsSaveSize;
2774   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2775                  ArgRegsSize, ArgRegsSaveSize);
2776
2777   // Store any by-val regs to their spots on the stack so that they may be
2778   // loaded by deferencing the result of formal parameter pointer or va_next.
2779   // Note: once stack area for byval/varargs registers
2780   // was initialized, it can't be initialized again.
2781   if (ArgRegsSaveSize) {
2782     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2783
2784     if (Padding) {
2785       assert(AFI->getStoredByValParamsPadding() == 0 &&
2786              "The only parameter may be padded.");
2787       AFI->setStoredByValParamsPadding(Padding);
2788     }
2789
2790     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2791                                             Padding +
2792                                               ByValStoreOffset -
2793                                               (int64_t)TotalArgRegsSaveSize,
2794                                             false);
2795     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2796     if (Padding) {
2797        MFI->CreateFixedObject(Padding,
2798                               ArgOffset + ByValStoreOffset -
2799                                 (int64_t)ArgRegsSaveSize,
2800                               false);
2801     }
2802
2803     SmallVector<SDValue, 4> MemOps;
2804     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2805          ++firstRegToSaveIndex, ++i) {
2806       const TargetRegisterClass *RC;
2807       if (AFI->isThumb1OnlyFunction())
2808         RC = &ARM::tGPRRegClass;
2809       else
2810         RC = &ARM::GPRRegClass;
2811
2812       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2813       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2814       SDValue Store =
2815         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2816                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2817                      false, false, 0);
2818       MemOps.push_back(Store);
2819       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2820                         DAG.getConstant(4, getPointerTy()));
2821     }
2822
2823     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2824
2825     if (!MemOps.empty())
2826       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2827     return FrameIndex;
2828   } else {
2829     if (ArgSize == 0) {
2830       // We cannot allocate a zero-byte object for the first variadic argument,
2831       // so just make up a size.
2832       ArgSize = 4;
2833     }
2834     // This will point to the next argument passed via stack.
2835     return MFI->CreateFixedObject(
2836       ArgSize, ArgOffset, !ForceMutable);
2837   }
2838 }
2839
2840 // Setup stack frame, the va_list pointer will start from.
2841 void
2842 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2843                                         SDLoc dl, SDValue &Chain,
2844                                         unsigned ArgOffset,
2845                                         unsigned TotalArgRegsSaveSize,
2846                                         bool ForceMutable) const {
2847   MachineFunction &MF = DAG.getMachineFunction();
2848   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2849
2850   // Try to store any remaining integer argument regs
2851   // to their spots on the stack so that they may be loaded by deferencing
2852   // the result of va_next.
2853   // If there is no regs to be stored, just point address after last
2854   // argument passed via stack.
2855   int FrameIndex =
2856     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2857                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2858                    0, TotalArgRegsSaveSize);
2859
2860   AFI->setVarArgsFrameIndex(FrameIndex);
2861 }
2862
2863 SDValue
2864 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2865                                         CallingConv::ID CallConv, bool isVarArg,
2866                                         const SmallVectorImpl<ISD::InputArg>
2867                                           &Ins,
2868                                         SDLoc dl, SelectionDAG &DAG,
2869                                         SmallVectorImpl<SDValue> &InVals)
2870                                           const {
2871   MachineFunction &MF = DAG.getMachineFunction();
2872   MachineFrameInfo *MFI = MF.getFrameInfo();
2873
2874   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2875
2876   // Assign locations to all of the incoming arguments.
2877   SmallVector<CCValAssign, 16> ArgLocs;
2878   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2879                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2880   CCInfo.AnalyzeFormalArguments(Ins,
2881                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2882                                                   isVarArg));
2883
2884   SmallVector<SDValue, 16> ArgValues;
2885   int lastInsIndex = -1;
2886   SDValue ArgValue;
2887   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2888   unsigned CurArgIdx = 0;
2889
2890   // Initially ArgRegsSaveSize is zero.
2891   // Then we increase this value each time we meet byval parameter.
2892   // We also increase this value in case of varargs function.
2893   AFI->setArgRegsSaveSize(0);
2894
2895   unsigned ByValStoreOffset = 0;
2896   unsigned TotalArgRegsSaveSize = 0;
2897   unsigned ArgRegsSaveSizeMaxAlign = 4;
2898
2899   // Calculate the amount of stack space that we need to allocate to store
2900   // byval and variadic arguments that are passed in registers.
2901   // We need to know this before we allocate the first byval or variadic
2902   // argument, as they will be allocated a stack slot below the CFA (Canonical
2903   // Frame Address, the stack pointer at entry to the function).
2904   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2905     CCValAssign &VA = ArgLocs[i];
2906     if (VA.isMemLoc()) {
2907       int index = VA.getValNo();
2908       if (index != lastInsIndex) {
2909         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2910         if (Flags.isByVal()) {
2911           unsigned ExtraArgRegsSize;
2912           unsigned ExtraArgRegsSaveSize;
2913           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2914                          Flags.getByValSize(),
2915                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2916
2917           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2918           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2919               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2920           CCInfo.nextInRegsParam();
2921         }
2922         lastInsIndex = index;
2923       }
2924     }
2925   }
2926   CCInfo.rewindByValRegsInfo();
2927   lastInsIndex = -1;
2928   if (isVarArg) {
2929     unsigned ExtraArgRegsSize;
2930     unsigned ExtraArgRegsSaveSize;
2931     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2932                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2933     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2934   }
2935   // If the arg regs save area contains N-byte aligned values, the
2936   // bottom of it must be at least N-byte aligned.
2937   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2938   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2939
2940   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2941     CCValAssign &VA = ArgLocs[i];
2942     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2943     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2944     // Arguments stored in registers.
2945     if (VA.isRegLoc()) {
2946       EVT RegVT = VA.getLocVT();
2947
2948       if (VA.needsCustom()) {
2949         // f64 and vector types are split up into multiple registers or
2950         // combinations of registers and stack slots.
2951         if (VA.getLocVT() == MVT::v2f64) {
2952           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2953                                                    Chain, DAG, dl);
2954           VA = ArgLocs[++i]; // skip ahead to next loc
2955           SDValue ArgValue2;
2956           if (VA.isMemLoc()) {
2957             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2958             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2959             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2960                                     MachinePointerInfo::getFixedStack(FI),
2961                                     false, false, false, 0);
2962           } else {
2963             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2964                                              Chain, DAG, dl);
2965           }
2966           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2967           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2968                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2969           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2970                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2971         } else
2972           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2973
2974       } else {
2975         const TargetRegisterClass *RC;
2976
2977         if (RegVT == MVT::f32)
2978           RC = &ARM::SPRRegClass;
2979         else if (RegVT == MVT::f64)
2980           RC = &ARM::DPRRegClass;
2981         else if (RegVT == MVT::v2f64)
2982           RC = &ARM::QPRRegClass;
2983         else if (RegVT == MVT::i32)
2984           RC = AFI->isThumb1OnlyFunction() ?
2985             (const TargetRegisterClass*)&ARM::tGPRRegClass :
2986             (const TargetRegisterClass*)&ARM::GPRRegClass;
2987         else
2988           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2989
2990         // Transform the arguments in physical registers into virtual ones.
2991         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2992         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2993       }
2994
2995       // If this is an 8 or 16-bit value, it is really passed promoted
2996       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2997       // truncate to the right size.
2998       switch (VA.getLocInfo()) {
2999       default: llvm_unreachable("Unknown loc info!");
3000       case CCValAssign::Full: break;
3001       case CCValAssign::BCvt:
3002         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3003         break;
3004       case CCValAssign::SExt:
3005         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3006                                DAG.getValueType(VA.getValVT()));
3007         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3008         break;
3009       case CCValAssign::ZExt:
3010         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3011                                DAG.getValueType(VA.getValVT()));
3012         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3013         break;
3014       }
3015
3016       InVals.push_back(ArgValue);
3017
3018     } else { // VA.isRegLoc()
3019
3020       // sanity check
3021       assert(VA.isMemLoc());
3022       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3023
3024       int index = ArgLocs[i].getValNo();
3025
3026       // Some Ins[] entries become multiple ArgLoc[] entries.
3027       // Process them only once.
3028       if (index != lastInsIndex)
3029         {
3030           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3031           // FIXME: For now, all byval parameter objects are marked mutable.
3032           // This can be changed with more analysis.
3033           // In case of tail call optimization mark all arguments mutable.
3034           // Since they could be overwritten by lowering of arguments in case of
3035           // a tail call.
3036           if (Flags.isByVal()) {
3037             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3038
3039             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3040             int FrameIndex = StoreByValRegs(
3041                 CCInfo, DAG, dl, Chain, CurOrigArg,
3042                 CurByValIndex,
3043                 Ins[VA.getValNo()].PartOffset,
3044                 VA.getLocMemOffset(),
3045                 Flags.getByValSize(),
3046                 true /*force mutable frames*/,
3047                 ByValStoreOffset,
3048                 TotalArgRegsSaveSize);
3049             ByValStoreOffset += Flags.getByValSize();
3050             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3051             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3052             CCInfo.nextInRegsParam();
3053           } else {
3054             unsigned FIOffset = VA.getLocMemOffset();
3055             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3056                                             FIOffset, true);
3057
3058             // Create load nodes to retrieve arguments from the stack.
3059             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3060             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3061                                          MachinePointerInfo::getFixedStack(FI),
3062                                          false, false, false, 0));
3063           }
3064           lastInsIndex = index;
3065         }
3066     }
3067   }
3068
3069   // varargs
3070   if (isVarArg)
3071     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3072                          CCInfo.getNextStackOffset(),
3073                          TotalArgRegsSaveSize);
3074
3075   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3076
3077   return Chain;
3078 }
3079
3080 /// isFloatingPointZero - Return true if this is +0.0.
3081 static bool isFloatingPointZero(SDValue Op) {
3082   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3083     return CFP->getValueAPF().isPosZero();
3084   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3085     // Maybe this has already been legalized into the constant pool?
3086     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3087       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3088       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3089         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3090           return CFP->getValueAPF().isPosZero();
3091     }
3092   }
3093   return false;
3094 }
3095
3096 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3097 /// the given operands.
3098 SDValue
3099 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3100                              SDValue &ARMcc, SelectionDAG &DAG,
3101                              SDLoc dl) const {
3102   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3103     unsigned C = RHSC->getZExtValue();
3104     if (!isLegalICmpImmediate(C)) {
3105       // Constant does not fit, try adjusting it by one?
3106       switch (CC) {
3107       default: break;
3108       case ISD::SETLT:
3109       case ISD::SETGE:
3110         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3111           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3112           RHS = DAG.getConstant(C-1, MVT::i32);
3113         }
3114         break;
3115       case ISD::SETULT:
3116       case ISD::SETUGE:
3117         if (C != 0 && isLegalICmpImmediate(C-1)) {
3118           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3119           RHS = DAG.getConstant(C-1, MVT::i32);
3120         }
3121         break;
3122       case ISD::SETLE:
3123       case ISD::SETGT:
3124         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3125           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3126           RHS = DAG.getConstant(C+1, MVT::i32);
3127         }
3128         break;
3129       case ISD::SETULE:
3130       case ISD::SETUGT:
3131         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3132           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3133           RHS = DAG.getConstant(C+1, MVT::i32);
3134         }
3135         break;
3136       }
3137     }
3138   }
3139
3140   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3141   ARMISD::NodeType CompareType;
3142   switch (CondCode) {
3143   default:
3144     CompareType = ARMISD::CMP;
3145     break;
3146   case ARMCC::EQ:
3147   case ARMCC::NE:
3148     // Uses only Z Flag
3149     CompareType = ARMISD::CMPZ;
3150     break;
3151   }
3152   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3153   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3154 }
3155
3156 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3157 SDValue
3158 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3159                              SDLoc dl) const {
3160   SDValue Cmp;
3161   if (!isFloatingPointZero(RHS))
3162     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3163   else
3164     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3165   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3166 }
3167
3168 /// duplicateCmp - Glue values can have only one use, so this function
3169 /// duplicates a comparison node.
3170 SDValue
3171 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3172   unsigned Opc = Cmp.getOpcode();
3173   SDLoc DL(Cmp);
3174   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3175     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3176
3177   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3178   Cmp = Cmp.getOperand(0);
3179   Opc = Cmp.getOpcode();
3180   if (Opc == ARMISD::CMPFP)
3181     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3182   else {
3183     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3184     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3185   }
3186   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3187 }
3188
3189 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3190   SDValue Cond = Op.getOperand(0);
3191   SDValue SelectTrue = Op.getOperand(1);
3192   SDValue SelectFalse = Op.getOperand(2);
3193   SDLoc dl(Op);
3194
3195   // Convert:
3196   //
3197   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3198   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3199   //
3200   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3201     const ConstantSDNode *CMOVTrue =
3202       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3203     const ConstantSDNode *CMOVFalse =
3204       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3205
3206     if (CMOVTrue && CMOVFalse) {
3207       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3208       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3209
3210       SDValue True;
3211       SDValue False;
3212       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3213         True = SelectTrue;
3214         False = SelectFalse;
3215       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3216         True = SelectFalse;
3217         False = SelectTrue;
3218       }
3219
3220       if (True.getNode() && False.getNode()) {
3221         EVT VT = Op.getValueType();
3222         SDValue ARMcc = Cond.getOperand(2);
3223         SDValue CCR = Cond.getOperand(3);
3224         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3225         assert(True.getValueType() == VT);
3226         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3227       }
3228     }
3229   }
3230
3231   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3232   // undefined bits before doing a full-word comparison with zero.
3233   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3234                      DAG.getConstant(1, Cond.getValueType()));
3235
3236   return DAG.getSelectCC(dl, Cond,
3237                          DAG.getConstant(0, Cond.getValueType()),
3238                          SelectTrue, SelectFalse, ISD::SETNE);
3239 }
3240
3241 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3242   if (CC == ISD::SETNE)
3243     return ISD::SETEQ;
3244   return ISD::getSetCCInverse(CC, true);
3245 }
3246
3247 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3248                                  bool &swpCmpOps, bool &swpVselOps) {
3249   // Start by selecting the GE condition code for opcodes that return true for
3250   // 'equality'
3251   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3252       CC == ISD::SETULE)
3253     CondCode = ARMCC::GE;
3254
3255   // and GT for opcodes that return false for 'equality'.
3256   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3257            CC == ISD::SETULT)
3258     CondCode = ARMCC::GT;
3259
3260   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3261   // to swap the compare operands.
3262   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3263       CC == ISD::SETULT)
3264     swpCmpOps = true;
3265
3266   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3267   // If we have an unordered opcode, we need to swap the operands to the VSEL
3268   // instruction (effectively negating the condition).
3269   //
3270   // This also has the effect of swapping which one of 'less' or 'greater'
3271   // returns true, so we also swap the compare operands. It also switches
3272   // whether we return true for 'equality', so we compensate by picking the
3273   // opposite condition code to our original choice.
3274   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3275       CC == ISD::SETUGT) {
3276     swpCmpOps = !swpCmpOps;
3277     swpVselOps = !swpVselOps;
3278     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3279   }
3280
3281   // 'ordered' is 'anything but unordered', so use the VS condition code and
3282   // swap the VSEL operands.
3283   if (CC == ISD::SETO) {
3284     CondCode = ARMCC::VS;
3285     swpVselOps = true;
3286   }
3287
3288   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3289   // code and swap the VSEL operands.
3290   if (CC == ISD::SETUNE) {
3291     CondCode = ARMCC::EQ;
3292     swpVselOps = true;
3293   }
3294 }
3295
3296 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3297   EVT VT = Op.getValueType();
3298   SDValue LHS = Op.getOperand(0);
3299   SDValue RHS = Op.getOperand(1);
3300   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3301   SDValue TrueVal = Op.getOperand(2);
3302   SDValue FalseVal = Op.getOperand(3);
3303   SDLoc dl(Op);
3304
3305   if (LHS.getValueType() == MVT::i32) {
3306     // Try to generate VSEL on ARMv8.
3307     // The VSEL instruction can't use all the usual ARM condition
3308     // codes: it only has two bits to select the condition code, so it's
3309     // constrained to use only GE, GT, VS and EQ.
3310     //
3311     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3312     // swap the operands of the previous compare instruction (effectively
3313     // inverting the compare condition, swapping 'less' and 'greater') and
3314     // sometimes need to swap the operands to the VSEL (which inverts the
3315     // condition in the sense of firing whenever the previous condition didn't)
3316     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3317                                       TrueVal.getValueType() == MVT::f64)) {
3318       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3319       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3320           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3321         CC = getInverseCCForVSEL(CC);
3322         std::swap(TrueVal, FalseVal);
3323       }
3324     }
3325
3326     SDValue ARMcc;
3327     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3328     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3329     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3330                        Cmp);
3331   }
3332
3333   ARMCC::CondCodes CondCode, CondCode2;
3334   FPCCToARMCC(CC, CondCode, CondCode2);
3335
3336   // Try to generate VSEL on ARMv8.
3337   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3338                                     TrueVal.getValueType() == MVT::f64)) {
3339     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3340     // same operands, as follows:
3341     //   c = fcmp [ogt, olt, ugt, ult] a, b
3342     //   select c, a, b
3343     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3344     // handled differently than the original code sequence.
3345     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3346         RHS == FalseVal) {
3347       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3348         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3349       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3350         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3351     }
3352
3353     bool swpCmpOps = false;
3354     bool swpVselOps = false;
3355     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3356
3357     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3358         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3359       if (swpCmpOps)
3360         std::swap(LHS, RHS);
3361       if (swpVselOps)
3362         std::swap(TrueVal, FalseVal);
3363     }
3364   }
3365
3366   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3367   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3368   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3369   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3370                                ARMcc, CCR, Cmp);
3371   if (CondCode2 != ARMCC::AL) {
3372     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3373     // FIXME: Needs another CMP because flag can have but one use.
3374     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3375     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3376                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3377   }
3378   return Result;
3379 }
3380
3381 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3382 /// to morph to an integer compare sequence.
3383 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3384                            const ARMSubtarget *Subtarget) {
3385   SDNode *N = Op.getNode();
3386   if (!N->hasOneUse())
3387     // Otherwise it requires moving the value from fp to integer registers.
3388     return false;
3389   if (!N->getNumValues())
3390     return false;
3391   EVT VT = Op.getValueType();
3392   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3393     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3394     // vmrs are very slow, e.g. cortex-a8.
3395     return false;
3396
3397   if (isFloatingPointZero(Op)) {
3398     SeenZero = true;
3399     return true;
3400   }
3401   return ISD::isNormalLoad(N);
3402 }
3403
3404 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3405   if (isFloatingPointZero(Op))
3406     return DAG.getConstant(0, MVT::i32);
3407
3408   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3409     return DAG.getLoad(MVT::i32, SDLoc(Op),
3410                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3411                        Ld->isVolatile(), Ld->isNonTemporal(),
3412                        Ld->isInvariant(), Ld->getAlignment());
3413
3414   llvm_unreachable("Unknown VFP cmp argument!");
3415 }
3416
3417 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3418                            SDValue &RetVal1, SDValue &RetVal2) {
3419   if (isFloatingPointZero(Op)) {
3420     RetVal1 = DAG.getConstant(0, MVT::i32);
3421     RetVal2 = DAG.getConstant(0, MVT::i32);
3422     return;
3423   }
3424
3425   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3426     SDValue Ptr = Ld->getBasePtr();
3427     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3428                           Ld->getChain(), Ptr,
3429                           Ld->getPointerInfo(),
3430                           Ld->isVolatile(), Ld->isNonTemporal(),
3431                           Ld->isInvariant(), Ld->getAlignment());
3432
3433     EVT PtrType = Ptr.getValueType();
3434     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3435     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3436                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3437     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3438                           Ld->getChain(), NewPtr,
3439                           Ld->getPointerInfo().getWithOffset(4),
3440                           Ld->isVolatile(), Ld->isNonTemporal(),
3441                           Ld->isInvariant(), NewAlign);
3442     return;
3443   }
3444
3445   llvm_unreachable("Unknown VFP cmp argument!");
3446 }
3447
3448 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3449 /// f32 and even f64 comparisons to integer ones.
3450 SDValue
3451 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3452   SDValue Chain = Op.getOperand(0);
3453   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3454   SDValue LHS = Op.getOperand(2);
3455   SDValue RHS = Op.getOperand(3);
3456   SDValue Dest = Op.getOperand(4);
3457   SDLoc dl(Op);
3458
3459   bool LHSSeenZero = false;
3460   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3461   bool RHSSeenZero = false;
3462   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3463   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3464     // If unsafe fp math optimization is enabled and there are no other uses of
3465     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3466     // to an integer comparison.
3467     if (CC == ISD::SETOEQ)
3468       CC = ISD::SETEQ;
3469     else if (CC == ISD::SETUNE)
3470       CC = ISD::SETNE;
3471
3472     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3473     SDValue ARMcc;
3474     if (LHS.getValueType() == MVT::f32) {
3475       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3476                         bitcastf32Toi32(LHS, DAG), Mask);
3477       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3478                         bitcastf32Toi32(RHS, DAG), Mask);
3479       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3480       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3481       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3482                          Chain, Dest, ARMcc, CCR, Cmp);
3483     }
3484
3485     SDValue LHS1, LHS2;
3486     SDValue RHS1, RHS2;
3487     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3488     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3489     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3490     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3491     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3492     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3493     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3494     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3495     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3496   }
3497
3498   return SDValue();
3499 }
3500
3501 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3502   SDValue Chain = Op.getOperand(0);
3503   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3504   SDValue LHS = Op.getOperand(2);
3505   SDValue RHS = Op.getOperand(3);
3506   SDValue Dest = Op.getOperand(4);
3507   SDLoc dl(Op);
3508
3509   if (LHS.getValueType() == MVT::i32) {
3510     SDValue ARMcc;
3511     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3512     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3513     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3514                        Chain, Dest, ARMcc, CCR, Cmp);
3515   }
3516
3517   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3518
3519   if (getTargetMachine().Options.UnsafeFPMath &&
3520       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3521        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3522     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3523     if (Result.getNode())
3524       return Result;
3525   }
3526
3527   ARMCC::CondCodes CondCode, CondCode2;
3528   FPCCToARMCC(CC, CondCode, CondCode2);
3529
3530   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3531   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3532   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3533   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3534   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3535   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3536   if (CondCode2 != ARMCC::AL) {
3537     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3538     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3539     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3540   }
3541   return Res;
3542 }
3543
3544 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3545   SDValue Chain = Op.getOperand(0);
3546   SDValue Table = Op.getOperand(1);
3547   SDValue Index = Op.getOperand(2);
3548   SDLoc dl(Op);
3549
3550   EVT PTy = getPointerTy();
3551   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3552   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3553   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3554   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3555   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3556   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3557   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3558   if (Subtarget->isThumb2()) {
3559     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3560     // which does another jump to the destination. This also makes it easier
3561     // to translate it to TBB / TBH later.
3562     // FIXME: This might not work if the function is extremely large.
3563     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3564                        Addr, Op.getOperand(2), JTI, UId);
3565   }
3566   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3567     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3568                        MachinePointerInfo::getJumpTable(),
3569                        false, false, false, 0);
3570     Chain = Addr.getValue(1);
3571     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3572     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3573   } else {
3574     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3575                        MachinePointerInfo::getJumpTable(),
3576                        false, false, false, 0);
3577     Chain = Addr.getValue(1);
3578     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3579   }
3580 }
3581
3582 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3583   EVT VT = Op.getValueType();
3584   SDLoc dl(Op);
3585
3586   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3587     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3588       return Op;
3589     return DAG.UnrollVectorOp(Op.getNode());
3590   }
3591
3592   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3593          "Invalid type for custom lowering!");
3594   if (VT != MVT::v4i16)
3595     return DAG.UnrollVectorOp(Op.getNode());
3596
3597   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3598   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3599 }
3600
3601 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3602   EVT VT = Op.getValueType();
3603   if (VT.isVector())
3604     return LowerVectorFP_TO_INT(Op, DAG);
3605
3606   SDLoc dl(Op);
3607   unsigned Opc;
3608
3609   switch (Op.getOpcode()) {
3610   default: llvm_unreachable("Invalid opcode!");
3611   case ISD::FP_TO_SINT:
3612     Opc = ARMISD::FTOSI;
3613     break;
3614   case ISD::FP_TO_UINT:
3615     Opc = ARMISD::FTOUI;
3616     break;
3617   }
3618   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3619   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3620 }
3621
3622 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3623   EVT VT = Op.getValueType();
3624   SDLoc dl(Op);
3625
3626   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3627     if (VT.getVectorElementType() == MVT::f32)
3628       return Op;
3629     return DAG.UnrollVectorOp(Op.getNode());
3630   }
3631
3632   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3633          "Invalid type for custom lowering!");
3634   if (VT != MVT::v4f32)
3635     return DAG.UnrollVectorOp(Op.getNode());
3636
3637   unsigned CastOpc;
3638   unsigned Opc;
3639   switch (Op.getOpcode()) {
3640   default: llvm_unreachable("Invalid opcode!");
3641   case ISD::SINT_TO_FP:
3642     CastOpc = ISD::SIGN_EXTEND;
3643     Opc = ISD::SINT_TO_FP;
3644     break;
3645   case ISD::UINT_TO_FP:
3646     CastOpc = ISD::ZERO_EXTEND;
3647     Opc = ISD::UINT_TO_FP;
3648     break;
3649   }
3650
3651   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3652   return DAG.getNode(Opc, dl, VT, Op);
3653 }
3654
3655 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3656   EVT VT = Op.getValueType();
3657   if (VT.isVector())
3658     return LowerVectorINT_TO_FP(Op, DAG);
3659
3660   SDLoc dl(Op);
3661   unsigned Opc;
3662
3663   switch (Op.getOpcode()) {
3664   default: llvm_unreachable("Invalid opcode!");
3665   case ISD::SINT_TO_FP:
3666     Opc = ARMISD::SITOF;
3667     break;
3668   case ISD::UINT_TO_FP:
3669     Opc = ARMISD::UITOF;
3670     break;
3671   }
3672
3673   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3674   return DAG.getNode(Opc, dl, VT, Op);
3675 }
3676
3677 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3678   // Implement fcopysign with a fabs and a conditional fneg.
3679   SDValue Tmp0 = Op.getOperand(0);
3680   SDValue Tmp1 = Op.getOperand(1);
3681   SDLoc dl(Op);
3682   EVT VT = Op.getValueType();
3683   EVT SrcVT = Tmp1.getValueType();
3684   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3685     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3686   bool UseNEON = !InGPR && Subtarget->hasNEON();
3687
3688   if (UseNEON) {
3689     // Use VBSL to copy the sign bit.
3690     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3691     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3692                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3693     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3694     if (VT == MVT::f64)
3695       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3696                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3697                          DAG.getConstant(32, MVT::i32));
3698     else /*if (VT == MVT::f32)*/
3699       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3700     if (SrcVT == MVT::f32) {
3701       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3702       if (VT == MVT::f64)
3703         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3704                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3705                            DAG.getConstant(32, MVT::i32));
3706     } else if (VT == MVT::f32)
3707       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3708                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3709                          DAG.getConstant(32, MVT::i32));
3710     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3711     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3712
3713     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3714                                             MVT::i32);
3715     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3716     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3717                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3718
3719     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3720                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3721                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3722     if (VT == MVT::f32) {
3723       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3724       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3725                         DAG.getConstant(0, MVT::i32));
3726     } else {
3727       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3728     }
3729
3730     return Res;
3731   }
3732
3733   // Bitcast operand 1 to i32.
3734   if (SrcVT == MVT::f64)
3735     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3736                        Tmp1).getValue(1);
3737   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3738
3739   // Or in the signbit with integer operations.
3740   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3741   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3742   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3743   if (VT == MVT::f32) {
3744     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3745                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3746     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3747                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3748   }
3749
3750   // f64: Or the high part with signbit and then combine two parts.
3751   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3752                      Tmp0);
3753   SDValue Lo = Tmp0.getValue(0);
3754   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3755   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3756   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3757 }
3758
3759 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3760   MachineFunction &MF = DAG.getMachineFunction();
3761   MachineFrameInfo *MFI = MF.getFrameInfo();
3762   MFI->setReturnAddressIsTaken(true);
3763
3764   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3765     return SDValue();
3766
3767   EVT VT = Op.getValueType();
3768   SDLoc dl(Op);
3769   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3770   if (Depth) {
3771     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3772     SDValue Offset = DAG.getConstant(4, MVT::i32);
3773     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3774                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3775                        MachinePointerInfo(), false, false, false, 0);
3776   }
3777
3778   // Return LR, which contains the return address. Mark it an implicit live-in.
3779   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3780   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3781 }
3782
3783 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3784   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3785   MFI->setFrameAddressIsTaken(true);
3786
3787   EVT VT = Op.getValueType();
3788   SDLoc dl(Op);  // FIXME probably not meaningful
3789   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3790   unsigned FrameReg = (Subtarget->isThumb() || Subtarget->isTargetMachO())
3791     ? ARM::R7 : ARM::R11;
3792   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3793   while (Depth--)
3794     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3795                             MachinePointerInfo(),
3796                             false, false, false, 0);
3797   return FrameAddr;
3798 }
3799
3800 // FIXME? Maybe this could be a TableGen attribute on some registers and
3801 // this table could be generated automatically from RegInfo.
3802 unsigned ARMTargetLowering::getRegisterByName(const char* RegName) const {
3803   unsigned Reg = StringSwitch<unsigned>(RegName)
3804                        .Case("sp", ARM::SP)
3805                        .Default(0);
3806   if (Reg)
3807     return Reg;
3808   report_fatal_error("Invalid register name global variable");
3809 }
3810
3811 /// ExpandBITCAST - If the target supports VFP, this function is called to
3812 /// expand a bit convert where either the source or destination type is i64 to
3813 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3814 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3815 /// vectors), since the legalizer won't know what to do with that.
3816 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3817   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3818   SDLoc dl(N);
3819   SDValue Op = N->getOperand(0);
3820
3821   // This function is only supposed to be called for i64 types, either as the
3822   // source or destination of the bit convert.
3823   EVT SrcVT = Op.getValueType();
3824   EVT DstVT = N->getValueType(0);
3825   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3826          "ExpandBITCAST called for non-i64 type");
3827
3828   // Turn i64->f64 into VMOVDRR.
3829   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3830     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3831                              DAG.getConstant(0, MVT::i32));
3832     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3833                              DAG.getConstant(1, MVT::i32));
3834     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3835                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3836   }
3837
3838   // Turn f64->i64 into VMOVRRD.
3839   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3840     SDValue Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3841                               DAG.getVTList(MVT::i32, MVT::i32), Op);
3842     // Merge the pieces into a single i64 value.
3843     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3844   }
3845
3846   return SDValue();
3847 }
3848
3849 /// getZeroVector - Returns a vector of specified type with all zero elements.
3850 /// Zero vectors are used to represent vector negation and in those cases
3851 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3852 /// not support i64 elements, so sometimes the zero vectors will need to be
3853 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3854 /// zero vector.
3855 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3856   assert(VT.isVector() && "Expected a vector type");
3857   // The canonical modified immediate encoding of a zero vector is....0!
3858   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3859   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3860   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3861   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3862 }
3863
3864 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3865 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3866 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3867                                                 SelectionDAG &DAG) const {
3868   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3869   EVT VT = Op.getValueType();
3870   unsigned VTBits = VT.getSizeInBits();
3871   SDLoc dl(Op);
3872   SDValue ShOpLo = Op.getOperand(0);
3873   SDValue ShOpHi = Op.getOperand(1);
3874   SDValue ShAmt  = Op.getOperand(2);
3875   SDValue ARMcc;
3876   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3877
3878   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3879
3880   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3881                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3882   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3883   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3884                                    DAG.getConstant(VTBits, MVT::i32));
3885   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3886   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3887   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3888
3889   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3890   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3891                           ARMcc, DAG, dl);
3892   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3893   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
3894                            CCR, Cmp);
3895
3896   SDValue Ops[2] = { Lo, Hi };
3897   return DAG.getMergeValues(Ops, dl);
3898 }
3899
3900 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3901 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3902 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
3903                                                SelectionDAG &DAG) const {
3904   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3905   EVT VT = Op.getValueType();
3906   unsigned VTBits = VT.getSizeInBits();
3907   SDLoc dl(Op);
3908   SDValue ShOpLo = Op.getOperand(0);
3909   SDValue ShOpHi = Op.getOperand(1);
3910   SDValue ShAmt  = Op.getOperand(2);
3911   SDValue ARMcc;
3912
3913   assert(Op.getOpcode() == ISD::SHL_PARTS);
3914   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3915                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3916   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3917   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3918                                    DAG.getConstant(VTBits, MVT::i32));
3919   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3920   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3921
3922   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3923   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3924   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
3925                           ARMcc, DAG, dl);
3926   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3927   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
3928                            CCR, Cmp);
3929
3930   SDValue Ops[2] = { Lo, Hi };
3931   return DAG.getMergeValues(Ops, dl);
3932 }
3933
3934 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3935                                             SelectionDAG &DAG) const {
3936   // The rounding mode is in bits 23:22 of the FPSCR.
3937   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
3938   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
3939   // so that the shift + and get folded into a bitfield extract.
3940   SDLoc dl(Op);
3941   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
3942                               DAG.getConstant(Intrinsic::arm_get_fpscr,
3943                                               MVT::i32));
3944   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
3945                                   DAG.getConstant(1U << 22, MVT::i32));
3946   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
3947                               DAG.getConstant(22, MVT::i32));
3948   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
3949                      DAG.getConstant(3, MVT::i32));
3950 }
3951
3952 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
3953                          const ARMSubtarget *ST) {
3954   EVT VT = N->getValueType(0);
3955   SDLoc dl(N);
3956
3957   if (!ST->hasV6T2Ops())
3958     return SDValue();
3959
3960   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
3961   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
3962 }
3963
3964 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
3965 /// for each 16-bit element from operand, repeated.  The basic idea is to
3966 /// leverage vcnt to get the 8-bit counts, gather and add the results.
3967 ///
3968 /// Trace for v4i16:
3969 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
3970 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
3971 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
3972 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
3973 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
3974 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
3975 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
3976 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
3977 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
3978   EVT VT = N->getValueType(0);
3979   SDLoc DL(N);
3980
3981   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
3982   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
3983   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
3984   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
3985   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
3986   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
3987 }
3988
3989 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
3990 /// bit-count for each 16-bit element from the operand.  We need slightly
3991 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
3992 /// 64/128-bit registers.
3993 ///
3994 /// Trace for v4i16:
3995 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
3996 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
3997 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
3998 /// v4i16:Extracted = [k0    k1    k2    k3    ]
3999 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4000   EVT VT = N->getValueType(0);
4001   SDLoc DL(N);
4002
4003   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4004   if (VT.is64BitVector()) {
4005     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4006     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4007                        DAG.getIntPtrConstant(0));
4008   } else {
4009     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4010                                     BitCounts, DAG.getIntPtrConstant(0));
4011     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4012   }
4013 }
4014
4015 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4016 /// bit-count for each 32-bit element from the operand.  The idea here is
4017 /// to split the vector into 16-bit elements, leverage the 16-bit count
4018 /// routine, and then combine the results.
4019 ///
4020 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4021 /// input    = [v0    v1    ] (vi: 32-bit elements)
4022 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4023 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4024 /// vrev: N0 = [k1 k0 k3 k2 ]
4025 ///            [k0 k1 k2 k3 ]
4026 ///       N1 =+[k1 k0 k3 k2 ]
4027 ///            [k0 k2 k1 k3 ]
4028 ///       N2 =+[k1 k3 k0 k2 ]
4029 ///            [k0    k2    k1    k3    ]
4030 /// Extended =+[k1    k3    k0    k2    ]
4031 ///            [k0    k2    ]
4032 /// Extracted=+[k1    k3    ]
4033 ///
4034 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4035   EVT VT = N->getValueType(0);
4036   SDLoc DL(N);
4037
4038   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4039
4040   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4041   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4042   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4043   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4044   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4045
4046   if (VT.is64BitVector()) {
4047     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4048     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4049                        DAG.getIntPtrConstant(0));
4050   } else {
4051     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4052                                     DAG.getIntPtrConstant(0));
4053     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4054   }
4055 }
4056
4057 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4058                           const ARMSubtarget *ST) {
4059   EVT VT = N->getValueType(0);
4060
4061   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4062   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4063           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4064          "Unexpected type for custom ctpop lowering");
4065
4066   if (VT.getVectorElementType() == MVT::i32)
4067     return lowerCTPOP32BitElements(N, DAG);
4068   else
4069     return lowerCTPOP16BitElements(N, DAG);
4070 }
4071
4072 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4073                           const ARMSubtarget *ST) {
4074   EVT VT = N->getValueType(0);
4075   SDLoc dl(N);
4076
4077   if (!VT.isVector())
4078     return SDValue();
4079
4080   // Lower vector shifts on NEON to use VSHL.
4081   assert(ST->hasNEON() && "unexpected vector shift");
4082
4083   // Left shifts translate directly to the vshiftu intrinsic.
4084   if (N->getOpcode() == ISD::SHL)
4085     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4086                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4087                        N->getOperand(0), N->getOperand(1));
4088
4089   assert((N->getOpcode() == ISD::SRA ||
4090           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4091
4092   // NEON uses the same intrinsics for both left and right shifts.  For
4093   // right shifts, the shift amounts are negative, so negate the vector of
4094   // shift amounts.
4095   EVT ShiftVT = N->getOperand(1).getValueType();
4096   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4097                                      getZeroVector(ShiftVT, DAG, dl),
4098                                      N->getOperand(1));
4099   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4100                              Intrinsic::arm_neon_vshifts :
4101                              Intrinsic::arm_neon_vshiftu);
4102   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4103                      DAG.getConstant(vshiftInt, MVT::i32),
4104                      N->getOperand(0), NegatedCount);
4105 }
4106
4107 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4108                                 const ARMSubtarget *ST) {
4109   EVT VT = N->getValueType(0);
4110   SDLoc dl(N);
4111
4112   // We can get here for a node like i32 = ISD::SHL i32, i64
4113   if (VT != MVT::i64)
4114     return SDValue();
4115
4116   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4117          "Unknown shift to lower!");
4118
4119   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4120   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4121       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4122     return SDValue();
4123
4124   // If we are in thumb mode, we don't have RRX.
4125   if (ST->isThumb1Only()) return SDValue();
4126
4127   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4128   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4129                            DAG.getConstant(0, MVT::i32));
4130   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4131                            DAG.getConstant(1, MVT::i32));
4132
4133   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4134   // captures the result into a carry flag.
4135   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4136   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4137
4138   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4139   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4140
4141   // Merge the pieces into a single i64 value.
4142  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4143 }
4144
4145 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4146   SDValue TmpOp0, TmpOp1;
4147   bool Invert = false;
4148   bool Swap = false;
4149   unsigned Opc = 0;
4150
4151   SDValue Op0 = Op.getOperand(0);
4152   SDValue Op1 = Op.getOperand(1);
4153   SDValue CC = Op.getOperand(2);
4154   EVT VT = Op.getValueType();
4155   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4156   SDLoc dl(Op);
4157
4158   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4159     switch (SetCCOpcode) {
4160     default: llvm_unreachable("Illegal FP comparison");
4161     case ISD::SETUNE:
4162     case ISD::SETNE:  Invert = true; // Fallthrough
4163     case ISD::SETOEQ:
4164     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4165     case ISD::SETOLT:
4166     case ISD::SETLT: Swap = true; // Fallthrough
4167     case ISD::SETOGT:
4168     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4169     case ISD::SETOLE:
4170     case ISD::SETLE:  Swap = true; // Fallthrough
4171     case ISD::SETOGE:
4172     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4173     case ISD::SETUGE: Swap = true; // Fallthrough
4174     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4175     case ISD::SETUGT: Swap = true; // Fallthrough
4176     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4177     case ISD::SETUEQ: Invert = true; // Fallthrough
4178     case ISD::SETONE:
4179       // Expand this to (OLT | OGT).
4180       TmpOp0 = Op0;
4181       TmpOp1 = Op1;
4182       Opc = ISD::OR;
4183       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4184       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4185       break;
4186     case ISD::SETUO: Invert = true; // Fallthrough
4187     case ISD::SETO:
4188       // Expand this to (OLT | OGE).
4189       TmpOp0 = Op0;
4190       TmpOp1 = Op1;
4191       Opc = ISD::OR;
4192       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4193       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4194       break;
4195     }
4196   } else {
4197     // Integer comparisons.
4198     switch (SetCCOpcode) {
4199     default: llvm_unreachable("Illegal integer comparison");
4200     case ISD::SETNE:  Invert = true;
4201     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4202     case ISD::SETLT:  Swap = true;
4203     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4204     case ISD::SETLE:  Swap = true;
4205     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4206     case ISD::SETULT: Swap = true;
4207     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4208     case ISD::SETULE: Swap = true;
4209     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4210     }
4211
4212     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4213     if (Opc == ARMISD::VCEQ) {
4214
4215       SDValue AndOp;
4216       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4217         AndOp = Op0;
4218       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4219         AndOp = Op1;
4220
4221       // Ignore bitconvert.
4222       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4223         AndOp = AndOp.getOperand(0);
4224
4225       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4226         Opc = ARMISD::VTST;
4227         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4228         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4229         Invert = !Invert;
4230       }
4231     }
4232   }
4233
4234   if (Swap)
4235     std::swap(Op0, Op1);
4236
4237   // If one of the operands is a constant vector zero, attempt to fold the
4238   // comparison to a specialized compare-against-zero form.
4239   SDValue SingleOp;
4240   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4241     SingleOp = Op0;
4242   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4243     if (Opc == ARMISD::VCGE)
4244       Opc = ARMISD::VCLEZ;
4245     else if (Opc == ARMISD::VCGT)
4246       Opc = ARMISD::VCLTZ;
4247     SingleOp = Op1;
4248   }
4249
4250   SDValue Result;
4251   if (SingleOp.getNode()) {
4252     switch (Opc) {
4253     case ARMISD::VCEQ:
4254       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4255     case ARMISD::VCGE:
4256       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4257     case ARMISD::VCLEZ:
4258       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4259     case ARMISD::VCGT:
4260       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4261     case ARMISD::VCLTZ:
4262       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4263     default:
4264       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4265     }
4266   } else {
4267      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4268   }
4269
4270   if (Invert)
4271     Result = DAG.getNOT(dl, Result, VT);
4272
4273   return Result;
4274 }
4275
4276 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4277 /// valid vector constant for a NEON instruction with a "modified immediate"
4278 /// operand (e.g., VMOV).  If so, return the encoded value.
4279 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4280                                  unsigned SplatBitSize, SelectionDAG &DAG,
4281                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4282   unsigned OpCmode, Imm;
4283
4284   // SplatBitSize is set to the smallest size that splats the vector, so a
4285   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4286   // immediate instructions others than VMOV do not support the 8-bit encoding
4287   // of a zero vector, and the default encoding of zero is supposed to be the
4288   // 32-bit version.
4289   if (SplatBits == 0)
4290     SplatBitSize = 32;
4291
4292   switch (SplatBitSize) {
4293   case 8:
4294     if (type != VMOVModImm)
4295       return SDValue();
4296     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4297     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4298     OpCmode = 0xe;
4299     Imm = SplatBits;
4300     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4301     break;
4302
4303   case 16:
4304     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4305     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4306     if ((SplatBits & ~0xff) == 0) {
4307       // Value = 0x00nn: Op=x, Cmode=100x.
4308       OpCmode = 0x8;
4309       Imm = SplatBits;
4310       break;
4311     }
4312     if ((SplatBits & ~0xff00) == 0) {
4313       // Value = 0xnn00: Op=x, Cmode=101x.
4314       OpCmode = 0xa;
4315       Imm = SplatBits >> 8;
4316       break;
4317     }
4318     return SDValue();
4319
4320   case 32:
4321     // NEON's 32-bit VMOV supports splat values where:
4322     // * only one byte is nonzero, or
4323     // * the least significant byte is 0xff and the second byte is nonzero, or
4324     // * the least significant 2 bytes are 0xff and the third is nonzero.
4325     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4326     if ((SplatBits & ~0xff) == 0) {
4327       // Value = 0x000000nn: Op=x, Cmode=000x.
4328       OpCmode = 0;
4329       Imm = SplatBits;
4330       break;
4331     }
4332     if ((SplatBits & ~0xff00) == 0) {
4333       // Value = 0x0000nn00: Op=x, Cmode=001x.
4334       OpCmode = 0x2;
4335       Imm = SplatBits >> 8;
4336       break;
4337     }
4338     if ((SplatBits & ~0xff0000) == 0) {
4339       // Value = 0x00nn0000: Op=x, Cmode=010x.
4340       OpCmode = 0x4;
4341       Imm = SplatBits >> 16;
4342       break;
4343     }
4344     if ((SplatBits & ~0xff000000) == 0) {
4345       // Value = 0xnn000000: Op=x, Cmode=011x.
4346       OpCmode = 0x6;
4347       Imm = SplatBits >> 24;
4348       break;
4349     }
4350
4351     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4352     if (type == OtherModImm) return SDValue();
4353
4354     if ((SplatBits & ~0xffff) == 0 &&
4355         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4356       // Value = 0x0000nnff: Op=x, Cmode=1100.
4357       OpCmode = 0xc;
4358       Imm = SplatBits >> 8;
4359       break;
4360     }
4361
4362     if ((SplatBits & ~0xffffff) == 0 &&
4363         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4364       // Value = 0x00nnffff: Op=x, Cmode=1101.
4365       OpCmode = 0xd;
4366       Imm = SplatBits >> 16;
4367       break;
4368     }
4369
4370     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4371     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4372     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4373     // and fall through here to test for a valid 64-bit splat.  But, then the
4374     // caller would also need to check and handle the change in size.
4375     return SDValue();
4376
4377   case 64: {
4378     if (type != VMOVModImm)
4379       return SDValue();
4380     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4381     uint64_t BitMask = 0xff;
4382     uint64_t Val = 0;
4383     unsigned ImmMask = 1;
4384     Imm = 0;
4385     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4386       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4387         Val |= BitMask;
4388         Imm |= ImmMask;
4389       } else if ((SplatBits & BitMask) != 0) {
4390         return SDValue();
4391       }
4392       BitMask <<= 8;
4393       ImmMask <<= 1;
4394     }
4395     // Op=1, Cmode=1110.
4396     OpCmode = 0x1e;
4397     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4398     break;
4399   }
4400
4401   default:
4402     llvm_unreachable("unexpected size for isNEONModifiedImm");
4403   }
4404
4405   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4406   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4407 }
4408
4409 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4410                                            const ARMSubtarget *ST) const {
4411   if (!ST->hasVFP3())
4412     return SDValue();
4413
4414   bool IsDouble = Op.getValueType() == MVT::f64;
4415   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4416
4417   // Try splatting with a VMOV.f32...
4418   APFloat FPVal = CFP->getValueAPF();
4419   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4420
4421   if (ImmVal != -1) {
4422     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4423       // We have code in place to select a valid ConstantFP already, no need to
4424       // do any mangling.
4425       return Op;
4426     }
4427
4428     // It's a float and we are trying to use NEON operations where
4429     // possible. Lower it to a splat followed by an extract.
4430     SDLoc DL(Op);
4431     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4432     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4433                                       NewVal);
4434     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4435                        DAG.getConstant(0, MVT::i32));
4436   }
4437
4438   // The rest of our options are NEON only, make sure that's allowed before
4439   // proceeding..
4440   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4441     return SDValue();
4442
4443   EVT VMovVT;
4444   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4445
4446   // It wouldn't really be worth bothering for doubles except for one very
4447   // important value, which does happen to match: 0.0. So make sure we don't do
4448   // anything stupid.
4449   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4450     return SDValue();
4451
4452   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4453   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4454                                      false, VMOVModImm);
4455   if (NewVal != SDValue()) {
4456     SDLoc DL(Op);
4457     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4458                                       NewVal);
4459     if (IsDouble)
4460       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4461
4462     // It's a float: cast and extract a vector element.
4463     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4464                                        VecConstant);
4465     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4466                        DAG.getConstant(0, MVT::i32));
4467   }
4468
4469   // Finally, try a VMVN.i32
4470   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4471                              false, VMVNModImm);
4472   if (NewVal != SDValue()) {
4473     SDLoc DL(Op);
4474     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4475
4476     if (IsDouble)
4477       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4478
4479     // It's a float: cast and extract a vector element.
4480     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4481                                        VecConstant);
4482     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4483                        DAG.getConstant(0, MVT::i32));
4484   }
4485
4486   return SDValue();
4487 }
4488
4489 // check if an VEXT instruction can handle the shuffle mask when the
4490 // vector sources of the shuffle are the same.
4491 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4492   unsigned NumElts = VT.getVectorNumElements();
4493
4494   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4495   if (M[0] < 0)
4496     return false;
4497
4498   Imm = M[0];
4499
4500   // If this is a VEXT shuffle, the immediate value is the index of the first
4501   // element.  The other shuffle indices must be the successive elements after
4502   // the first one.
4503   unsigned ExpectedElt = Imm;
4504   for (unsigned i = 1; i < NumElts; ++i) {
4505     // Increment the expected index.  If it wraps around, just follow it
4506     // back to index zero and keep going.
4507     ++ExpectedElt;
4508     if (ExpectedElt == NumElts)
4509       ExpectedElt = 0;
4510
4511     if (M[i] < 0) continue; // ignore UNDEF indices
4512     if (ExpectedElt != static_cast<unsigned>(M[i]))
4513       return false;
4514   }
4515
4516   return true;
4517 }
4518
4519
4520 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4521                        bool &ReverseVEXT, unsigned &Imm) {
4522   unsigned NumElts = VT.getVectorNumElements();
4523   ReverseVEXT = false;
4524
4525   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4526   if (M[0] < 0)
4527     return false;
4528
4529   Imm = M[0];
4530
4531   // If this is a VEXT shuffle, the immediate value is the index of the first
4532   // element.  The other shuffle indices must be the successive elements after
4533   // the first one.
4534   unsigned ExpectedElt = Imm;
4535   for (unsigned i = 1; i < NumElts; ++i) {
4536     // Increment the expected index.  If it wraps around, it may still be
4537     // a VEXT but the source vectors must be swapped.
4538     ExpectedElt += 1;
4539     if (ExpectedElt == NumElts * 2) {
4540       ExpectedElt = 0;
4541       ReverseVEXT = true;
4542     }
4543
4544     if (M[i] < 0) continue; // ignore UNDEF indices
4545     if (ExpectedElt != static_cast<unsigned>(M[i]))
4546       return false;
4547   }
4548
4549   // Adjust the index value if the source operands will be swapped.
4550   if (ReverseVEXT)
4551     Imm -= NumElts;
4552
4553   return true;
4554 }
4555
4556 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4557 /// instruction with the specified blocksize.  (The order of the elements
4558 /// within each block of the vector is reversed.)
4559 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4560   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4561          "Only possible block sizes for VREV are: 16, 32, 64");
4562
4563   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4564   if (EltSz == 64)
4565     return false;
4566
4567   unsigned NumElts = VT.getVectorNumElements();
4568   unsigned BlockElts = M[0] + 1;
4569   // If the first shuffle index is UNDEF, be optimistic.
4570   if (M[0] < 0)
4571     BlockElts = BlockSize / EltSz;
4572
4573   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4574     return false;
4575
4576   for (unsigned i = 0; i < NumElts; ++i) {
4577     if (M[i] < 0) continue; // ignore UNDEF indices
4578     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4579       return false;
4580   }
4581
4582   return true;
4583 }
4584
4585 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4586   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4587   // range, then 0 is placed into the resulting vector. So pretty much any mask
4588   // of 8 elements can work here.
4589   return VT == MVT::v8i8 && M.size() == 8;
4590 }
4591
4592 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4593   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4594   if (EltSz == 64)
4595     return false;
4596
4597   unsigned NumElts = VT.getVectorNumElements();
4598   WhichResult = (M[0] == 0 ? 0 : 1);
4599   for (unsigned i = 0; i < NumElts; i += 2) {
4600     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4601         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4602       return false;
4603   }
4604   return true;
4605 }
4606
4607 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4608 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4609 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4610 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4611   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4612   if (EltSz == 64)
4613     return false;
4614
4615   unsigned NumElts = VT.getVectorNumElements();
4616   WhichResult = (M[0] == 0 ? 0 : 1);
4617   for (unsigned i = 0; i < NumElts; i += 2) {
4618     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4619         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4620       return false;
4621   }
4622   return true;
4623 }
4624
4625 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4626   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4627   if (EltSz == 64)
4628     return false;
4629
4630   unsigned NumElts = VT.getVectorNumElements();
4631   WhichResult = (M[0] == 0 ? 0 : 1);
4632   for (unsigned i = 0; i != NumElts; ++i) {
4633     if (M[i] < 0) continue; // ignore UNDEF indices
4634     if ((unsigned) M[i] != 2 * i + WhichResult)
4635       return false;
4636   }
4637
4638   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4639   if (VT.is64BitVector() && EltSz == 32)
4640     return false;
4641
4642   return true;
4643 }
4644
4645 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4646 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4647 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4648 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4649   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4650   if (EltSz == 64)
4651     return false;
4652
4653   unsigned Half = VT.getVectorNumElements() / 2;
4654   WhichResult = (M[0] == 0 ? 0 : 1);
4655   for (unsigned j = 0; j != 2; ++j) {
4656     unsigned Idx = WhichResult;
4657     for (unsigned i = 0; i != Half; ++i) {
4658       int MIdx = M[i + j * Half];
4659       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4660         return false;
4661       Idx += 2;
4662     }
4663   }
4664
4665   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4666   if (VT.is64BitVector() && EltSz == 32)
4667     return false;
4668
4669   return true;
4670 }
4671
4672 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4673   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4674   if (EltSz == 64)
4675     return false;
4676
4677   unsigned NumElts = VT.getVectorNumElements();
4678   WhichResult = (M[0] == 0 ? 0 : 1);
4679   unsigned Idx = WhichResult * NumElts / 2;
4680   for (unsigned i = 0; i != NumElts; i += 2) {
4681     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4682         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4683       return false;
4684     Idx += 1;
4685   }
4686
4687   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4688   if (VT.is64BitVector() && EltSz == 32)
4689     return false;
4690
4691   return true;
4692 }
4693
4694 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4695 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4696 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4697 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4698   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4699   if (EltSz == 64)
4700     return false;
4701
4702   unsigned NumElts = VT.getVectorNumElements();
4703   WhichResult = (M[0] == 0 ? 0 : 1);
4704   unsigned Idx = WhichResult * NumElts / 2;
4705   for (unsigned i = 0; i != NumElts; i += 2) {
4706     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4707         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4708       return false;
4709     Idx += 1;
4710   }
4711
4712   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4713   if (VT.is64BitVector() && EltSz == 32)
4714     return false;
4715
4716   return true;
4717 }
4718
4719 /// \return true if this is a reverse operation on an vector.
4720 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4721   unsigned NumElts = VT.getVectorNumElements();
4722   // Make sure the mask has the right size.
4723   if (NumElts != M.size())
4724       return false;
4725
4726   // Look for <15, ..., 3, -1, 1, 0>.
4727   for (unsigned i = 0; i != NumElts; ++i)
4728     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4729       return false;
4730
4731   return true;
4732 }
4733
4734 // If N is an integer constant that can be moved into a register in one
4735 // instruction, return an SDValue of such a constant (will become a MOV
4736 // instruction).  Otherwise return null.
4737 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4738                                      const ARMSubtarget *ST, SDLoc dl) {
4739   uint64_t Val;
4740   if (!isa<ConstantSDNode>(N))
4741     return SDValue();
4742   Val = cast<ConstantSDNode>(N)->getZExtValue();
4743
4744   if (ST->isThumb1Only()) {
4745     if (Val <= 255 || ~Val <= 255)
4746       return DAG.getConstant(Val, MVT::i32);
4747   } else {
4748     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4749       return DAG.getConstant(Val, MVT::i32);
4750   }
4751   return SDValue();
4752 }
4753
4754 // If this is a case we can't handle, return null and let the default
4755 // expansion code take care of it.
4756 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4757                                              const ARMSubtarget *ST) const {
4758   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4759   SDLoc dl(Op);
4760   EVT VT = Op.getValueType();
4761
4762   APInt SplatBits, SplatUndef;
4763   unsigned SplatBitSize;
4764   bool HasAnyUndefs;
4765   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4766     if (SplatBitSize <= 64) {
4767       // Check if an immediate VMOV works.
4768       EVT VmovVT;
4769       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4770                                       SplatUndef.getZExtValue(), SplatBitSize,
4771                                       DAG, VmovVT, VT.is128BitVector(),
4772                                       VMOVModImm);
4773       if (Val.getNode()) {
4774         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4775         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4776       }
4777
4778       // Try an immediate VMVN.
4779       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4780       Val = isNEONModifiedImm(NegatedImm,
4781                                       SplatUndef.getZExtValue(), SplatBitSize,
4782                                       DAG, VmovVT, VT.is128BitVector(),
4783                                       VMVNModImm);
4784       if (Val.getNode()) {
4785         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4786         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4787       }
4788
4789       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4790       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4791         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4792         if (ImmVal != -1) {
4793           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4794           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4795         }
4796       }
4797     }
4798   }
4799
4800   // Scan through the operands to see if only one value is used.
4801   //
4802   // As an optimisation, even if more than one value is used it may be more
4803   // profitable to splat with one value then change some lanes.
4804   //
4805   // Heuristically we decide to do this if the vector has a "dominant" value,
4806   // defined as splatted to more than half of the lanes.
4807   unsigned NumElts = VT.getVectorNumElements();
4808   bool isOnlyLowElement = true;
4809   bool usesOnlyOneValue = true;
4810   bool hasDominantValue = false;
4811   bool isConstant = true;
4812
4813   // Map of the number of times a particular SDValue appears in the
4814   // element list.
4815   DenseMap<SDValue, unsigned> ValueCounts;
4816   SDValue Value;
4817   for (unsigned i = 0; i < NumElts; ++i) {
4818     SDValue V = Op.getOperand(i);
4819     if (V.getOpcode() == ISD::UNDEF)
4820       continue;
4821     if (i > 0)
4822       isOnlyLowElement = false;
4823     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4824       isConstant = false;
4825
4826     ValueCounts.insert(std::make_pair(V, 0));
4827     unsigned &Count = ValueCounts[V];
4828
4829     // Is this value dominant? (takes up more than half of the lanes)
4830     if (++Count > (NumElts / 2)) {
4831       hasDominantValue = true;
4832       Value = V;
4833     }
4834   }
4835   if (ValueCounts.size() != 1)
4836     usesOnlyOneValue = false;
4837   if (!Value.getNode() && ValueCounts.size() > 0)
4838     Value = ValueCounts.begin()->first;
4839
4840   if (ValueCounts.size() == 0)
4841     return DAG.getUNDEF(VT);
4842
4843   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4844   // Keep going if we are hitting this case.
4845   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4846     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4847
4848   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4849
4850   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4851   // i32 and try again.
4852   if (hasDominantValue && EltSize <= 32) {
4853     if (!isConstant) {
4854       SDValue N;
4855
4856       // If we are VDUPing a value that comes directly from a vector, that will
4857       // cause an unnecessary move to and from a GPR, where instead we could
4858       // just use VDUPLANE. We can only do this if the lane being extracted
4859       // is at a constant index, as the VDUP from lane instructions only have
4860       // constant-index forms.
4861       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4862           isa<ConstantSDNode>(Value->getOperand(1))) {
4863         // We need to create a new undef vector to use for the VDUPLANE if the
4864         // size of the vector from which we get the value is different than the
4865         // size of the vector that we need to create. We will insert the element
4866         // such that the register coalescer will remove unnecessary copies.
4867         if (VT != Value->getOperand(0).getValueType()) {
4868           ConstantSDNode *constIndex;
4869           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4870           assert(constIndex && "The index is not a constant!");
4871           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4872                              VT.getVectorNumElements();
4873           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4874                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4875                         Value, DAG.getConstant(index, MVT::i32)),
4876                            DAG.getConstant(index, MVT::i32));
4877         } else
4878           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4879                         Value->getOperand(0), Value->getOperand(1));
4880       } else
4881         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4882
4883       if (!usesOnlyOneValue) {
4884         // The dominant value was splatted as 'N', but we now have to insert
4885         // all differing elements.
4886         for (unsigned I = 0; I < NumElts; ++I) {
4887           if (Op.getOperand(I) == Value)
4888             continue;
4889           SmallVector<SDValue, 3> Ops;
4890           Ops.push_back(N);
4891           Ops.push_back(Op.getOperand(I));
4892           Ops.push_back(DAG.getConstant(I, MVT::i32));
4893           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
4894         }
4895       }
4896       return N;
4897     }
4898     if (VT.getVectorElementType().isFloatingPoint()) {
4899       SmallVector<SDValue, 8> Ops;
4900       for (unsigned i = 0; i < NumElts; ++i)
4901         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4902                                   Op.getOperand(i)));
4903       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
4904       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
4905       Val = LowerBUILD_VECTOR(Val, DAG, ST);
4906       if (Val.getNode())
4907         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4908     }
4909     if (usesOnlyOneValue) {
4910       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
4911       if (isConstant && Val.getNode())
4912         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
4913     }
4914   }
4915
4916   // If all elements are constants and the case above didn't get hit, fall back
4917   // to the default expansion, which will generate a load from the constant
4918   // pool.
4919   if (isConstant)
4920     return SDValue();
4921
4922   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
4923   if (NumElts >= 4) {
4924     SDValue shuffle = ReconstructShuffle(Op, DAG);
4925     if (shuffle != SDValue())
4926       return shuffle;
4927   }
4928
4929   // Vectors with 32- or 64-bit elements can be built by directly assigning
4930   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
4931   // will be legalized.
4932   if (EltSize >= 32) {
4933     // Do the expansion with floating-point types, since that is what the VFP
4934     // registers are defined to use, and since i64 is not legal.
4935     EVT EltVT = EVT::getFloatingPointVT(EltSize);
4936     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
4937     SmallVector<SDValue, 8> Ops;
4938     for (unsigned i = 0; i < NumElts; ++i)
4939       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
4940     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
4941     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
4942   }
4943
4944   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
4945   // know the default expansion would otherwise fall back on something even
4946   // worse. For a vector with one or two non-undef values, that's
4947   // scalar_to_vector for the elements followed by a shuffle (provided the
4948   // shuffle is valid for the target) and materialization element by element
4949   // on the stack followed by a load for everything else.
4950   if (!isConstant && !usesOnlyOneValue) {
4951     SDValue Vec = DAG.getUNDEF(VT);
4952     for (unsigned i = 0 ; i < NumElts; ++i) {
4953       SDValue V = Op.getOperand(i);
4954       if (V.getOpcode() == ISD::UNDEF)
4955         continue;
4956       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
4957       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
4958     }
4959     return Vec;
4960   }
4961
4962   return SDValue();
4963 }
4964
4965 // Gather data to see if the operation can be modelled as a
4966 // shuffle in combination with VEXTs.
4967 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
4968                                               SelectionDAG &DAG) const {
4969   SDLoc dl(Op);
4970   EVT VT = Op.getValueType();
4971   unsigned NumElts = VT.getVectorNumElements();
4972
4973   SmallVector<SDValue, 2> SourceVecs;
4974   SmallVector<unsigned, 2> MinElts;
4975   SmallVector<unsigned, 2> MaxElts;
4976
4977   for (unsigned i = 0; i < NumElts; ++i) {
4978     SDValue V = Op.getOperand(i);
4979     if (V.getOpcode() == ISD::UNDEF)
4980       continue;
4981     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4982       // A shuffle can only come from building a vector from various
4983       // elements of other vectors.
4984       return SDValue();
4985     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
4986                VT.getVectorElementType()) {
4987       // This code doesn't know how to handle shuffles where the vector
4988       // element types do not match (this happens because type legalization
4989       // promotes the return type of EXTRACT_VECTOR_ELT).
4990       // FIXME: It might be appropriate to extend this code to handle
4991       // mismatched types.
4992       return SDValue();
4993     }
4994
4995     // Record this extraction against the appropriate vector if possible...
4996     SDValue SourceVec = V.getOperand(0);
4997     // If the element number isn't a constant, we can't effectively
4998     // analyze what's going on.
4999     if (!isa<ConstantSDNode>(V.getOperand(1)))
5000       return SDValue();
5001     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5002     bool FoundSource = false;
5003     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5004       if (SourceVecs[j] == SourceVec) {
5005         if (MinElts[j] > EltNo)
5006           MinElts[j] = EltNo;
5007         if (MaxElts[j] < EltNo)
5008           MaxElts[j] = EltNo;
5009         FoundSource = true;
5010         break;
5011       }
5012     }
5013
5014     // Or record a new source if not...
5015     if (!FoundSource) {
5016       SourceVecs.push_back(SourceVec);
5017       MinElts.push_back(EltNo);
5018       MaxElts.push_back(EltNo);
5019     }
5020   }
5021
5022   // Currently only do something sane when at most two source vectors
5023   // involved.
5024   if (SourceVecs.size() > 2)
5025     return SDValue();
5026
5027   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5028   int VEXTOffsets[2] = {0, 0};
5029
5030   // This loop extracts the usage patterns of the source vectors
5031   // and prepares appropriate SDValues for a shuffle if possible.
5032   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5033     if (SourceVecs[i].getValueType() == VT) {
5034       // No VEXT necessary
5035       ShuffleSrcs[i] = SourceVecs[i];
5036       VEXTOffsets[i] = 0;
5037       continue;
5038     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5039       // It probably isn't worth padding out a smaller vector just to
5040       // break it down again in a shuffle.
5041       return SDValue();
5042     }
5043
5044     // Since only 64-bit and 128-bit vectors are legal on ARM and
5045     // we've eliminated the other cases...
5046     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5047            "unexpected vector sizes in ReconstructShuffle");
5048
5049     if (MaxElts[i] - MinElts[i] >= NumElts) {
5050       // Span too large for a VEXT to cope
5051       return SDValue();
5052     }
5053
5054     if (MinElts[i] >= NumElts) {
5055       // The extraction can just take the second half
5056       VEXTOffsets[i] = NumElts;
5057       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5058                                    SourceVecs[i],
5059                                    DAG.getIntPtrConstant(NumElts));
5060     } else if (MaxElts[i] < NumElts) {
5061       // The extraction can just take the first half
5062       VEXTOffsets[i] = 0;
5063       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5064                                    SourceVecs[i],
5065                                    DAG.getIntPtrConstant(0));
5066     } else {
5067       // An actual VEXT is needed
5068       VEXTOffsets[i] = MinElts[i];
5069       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5070                                      SourceVecs[i],
5071                                      DAG.getIntPtrConstant(0));
5072       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5073                                      SourceVecs[i],
5074                                      DAG.getIntPtrConstant(NumElts));
5075       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5076                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5077     }
5078   }
5079
5080   SmallVector<int, 8> Mask;
5081
5082   for (unsigned i = 0; i < NumElts; ++i) {
5083     SDValue Entry = Op.getOperand(i);
5084     if (Entry.getOpcode() == ISD::UNDEF) {
5085       Mask.push_back(-1);
5086       continue;
5087     }
5088
5089     SDValue ExtractVec = Entry.getOperand(0);
5090     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5091                                           .getOperand(1))->getSExtValue();
5092     if (ExtractVec == SourceVecs[0]) {
5093       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5094     } else {
5095       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5096     }
5097   }
5098
5099   // Final check before we try to produce nonsense...
5100   if (isShuffleMaskLegal(Mask, VT))
5101     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5102                                 &Mask[0]);
5103
5104   return SDValue();
5105 }
5106
5107 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5108 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5109 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5110 /// are assumed to be legal.
5111 bool
5112 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5113                                       EVT VT) const {
5114   if (VT.getVectorNumElements() == 4 &&
5115       (VT.is128BitVector() || VT.is64BitVector())) {
5116     unsigned PFIndexes[4];
5117     for (unsigned i = 0; i != 4; ++i) {
5118       if (M[i] < 0)
5119         PFIndexes[i] = 8;
5120       else
5121         PFIndexes[i] = M[i];
5122     }
5123
5124     // Compute the index in the perfect shuffle table.
5125     unsigned PFTableIndex =
5126       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5127     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5128     unsigned Cost = (PFEntry >> 30);
5129
5130     if (Cost <= 4)
5131       return true;
5132   }
5133
5134   bool ReverseVEXT;
5135   unsigned Imm, WhichResult;
5136
5137   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5138   return (EltSize >= 32 ||
5139           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5140           isVREVMask(M, VT, 64) ||
5141           isVREVMask(M, VT, 32) ||
5142           isVREVMask(M, VT, 16) ||
5143           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5144           isVTBLMask(M, VT) ||
5145           isVTRNMask(M, VT, WhichResult) ||
5146           isVUZPMask(M, VT, WhichResult) ||
5147           isVZIPMask(M, VT, WhichResult) ||
5148           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5149           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5150           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5151           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5152 }
5153
5154 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5155 /// the specified operations to build the shuffle.
5156 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5157                                       SDValue RHS, SelectionDAG &DAG,
5158                                       SDLoc dl) {
5159   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5160   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5161   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5162
5163   enum {
5164     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5165     OP_VREV,
5166     OP_VDUP0,
5167     OP_VDUP1,
5168     OP_VDUP2,
5169     OP_VDUP3,
5170     OP_VEXT1,
5171     OP_VEXT2,
5172     OP_VEXT3,
5173     OP_VUZPL, // VUZP, left result
5174     OP_VUZPR, // VUZP, right result
5175     OP_VZIPL, // VZIP, left result
5176     OP_VZIPR, // VZIP, right result
5177     OP_VTRNL, // VTRN, left result
5178     OP_VTRNR  // VTRN, right result
5179   };
5180
5181   if (OpNum == OP_COPY) {
5182     if (LHSID == (1*9+2)*9+3) return LHS;
5183     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5184     return RHS;
5185   }
5186
5187   SDValue OpLHS, OpRHS;
5188   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5189   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5190   EVT VT = OpLHS.getValueType();
5191
5192   switch (OpNum) {
5193   default: llvm_unreachable("Unknown shuffle opcode!");
5194   case OP_VREV:
5195     // VREV divides the vector in half and swaps within the half.
5196     if (VT.getVectorElementType() == MVT::i32 ||
5197         VT.getVectorElementType() == MVT::f32)
5198       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5199     // vrev <4 x i16> -> VREV32
5200     if (VT.getVectorElementType() == MVT::i16)
5201       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5202     // vrev <4 x i8> -> VREV16
5203     assert(VT.getVectorElementType() == MVT::i8);
5204     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5205   case OP_VDUP0:
5206   case OP_VDUP1:
5207   case OP_VDUP2:
5208   case OP_VDUP3:
5209     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5210                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5211   case OP_VEXT1:
5212   case OP_VEXT2:
5213   case OP_VEXT3:
5214     return DAG.getNode(ARMISD::VEXT, dl, VT,
5215                        OpLHS, OpRHS,
5216                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5217   case OP_VUZPL:
5218   case OP_VUZPR:
5219     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5220                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5221   case OP_VZIPL:
5222   case OP_VZIPR:
5223     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5224                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5225   case OP_VTRNL:
5226   case OP_VTRNR:
5227     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5228                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5229   }
5230 }
5231
5232 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5233                                        ArrayRef<int> ShuffleMask,
5234                                        SelectionDAG &DAG) {
5235   // Check to see if we can use the VTBL instruction.
5236   SDValue V1 = Op.getOperand(0);
5237   SDValue V2 = Op.getOperand(1);
5238   SDLoc DL(Op);
5239
5240   SmallVector<SDValue, 8> VTBLMask;
5241   for (ArrayRef<int>::iterator
5242          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5243     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5244
5245   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5246     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5247                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5248
5249   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5250                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5251 }
5252
5253 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5254                                                       SelectionDAG &DAG) {
5255   SDLoc DL(Op);
5256   SDValue OpLHS = Op.getOperand(0);
5257   EVT VT = OpLHS.getValueType();
5258
5259   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5260          "Expect an v8i16/v16i8 type");
5261   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5262   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5263   // extract the first 8 bytes into the top double word and the last 8 bytes
5264   // into the bottom double word. The v8i16 case is similar.
5265   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5266   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5267                      DAG.getConstant(ExtractNum, MVT::i32));
5268 }
5269
5270 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5271   SDValue V1 = Op.getOperand(0);
5272   SDValue V2 = Op.getOperand(1);
5273   SDLoc dl(Op);
5274   EVT VT = Op.getValueType();
5275   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5276
5277   // Convert shuffles that are directly supported on NEON to target-specific
5278   // DAG nodes, instead of keeping them as shuffles and matching them again
5279   // during code selection.  This is more efficient and avoids the possibility
5280   // of inconsistencies between legalization and selection.
5281   // FIXME: floating-point vectors should be canonicalized to integer vectors
5282   // of the same time so that they get CSEd properly.
5283   ArrayRef<int> ShuffleMask = SVN->getMask();
5284
5285   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5286   if (EltSize <= 32) {
5287     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5288       int Lane = SVN->getSplatIndex();
5289       // If this is undef splat, generate it via "just" vdup, if possible.
5290       if (Lane == -1) Lane = 0;
5291
5292       // Test if V1 is a SCALAR_TO_VECTOR.
5293       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5294         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5295       }
5296       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5297       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5298       // reaches it).
5299       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5300           !isa<ConstantSDNode>(V1.getOperand(0))) {
5301         bool IsScalarToVector = true;
5302         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5303           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5304             IsScalarToVector = false;
5305             break;
5306           }
5307         if (IsScalarToVector)
5308           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5309       }
5310       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5311                          DAG.getConstant(Lane, MVT::i32));
5312     }
5313
5314     bool ReverseVEXT;
5315     unsigned Imm;
5316     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5317       if (ReverseVEXT)
5318         std::swap(V1, V2);
5319       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5320                          DAG.getConstant(Imm, MVT::i32));
5321     }
5322
5323     if (isVREVMask(ShuffleMask, VT, 64))
5324       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5325     if (isVREVMask(ShuffleMask, VT, 32))
5326       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5327     if (isVREVMask(ShuffleMask, VT, 16))
5328       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5329
5330     if (V2->getOpcode() == ISD::UNDEF &&
5331         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5332       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5333                          DAG.getConstant(Imm, MVT::i32));
5334     }
5335
5336     // Check for Neon shuffles that modify both input vectors in place.
5337     // If both results are used, i.e., if there are two shuffles with the same
5338     // source operands and with masks corresponding to both results of one of
5339     // these operations, DAG memoization will ensure that a single node is
5340     // used for both shuffles.
5341     unsigned WhichResult;
5342     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5343       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5344                          V1, V2).getValue(WhichResult);
5345     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5346       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5347                          V1, V2).getValue(WhichResult);
5348     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5349       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5350                          V1, V2).getValue(WhichResult);
5351
5352     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5353       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5354                          V1, V1).getValue(WhichResult);
5355     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5356       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5357                          V1, V1).getValue(WhichResult);
5358     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5359       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5360                          V1, V1).getValue(WhichResult);
5361   }
5362
5363   // If the shuffle is not directly supported and it has 4 elements, use
5364   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5365   unsigned NumElts = VT.getVectorNumElements();
5366   if (NumElts == 4) {
5367     unsigned PFIndexes[4];
5368     for (unsigned i = 0; i != 4; ++i) {
5369       if (ShuffleMask[i] < 0)
5370         PFIndexes[i] = 8;
5371       else
5372         PFIndexes[i] = ShuffleMask[i];
5373     }
5374
5375     // Compute the index in the perfect shuffle table.
5376     unsigned PFTableIndex =
5377       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5378     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5379     unsigned Cost = (PFEntry >> 30);
5380
5381     if (Cost <= 4)
5382       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5383   }
5384
5385   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5386   if (EltSize >= 32) {
5387     // Do the expansion with floating-point types, since that is what the VFP
5388     // registers are defined to use, and since i64 is not legal.
5389     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5390     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5391     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5392     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5393     SmallVector<SDValue, 8> Ops;
5394     for (unsigned i = 0; i < NumElts; ++i) {
5395       if (ShuffleMask[i] < 0)
5396         Ops.push_back(DAG.getUNDEF(EltVT));
5397       else
5398         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5399                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5400                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5401                                                   MVT::i32)));
5402     }
5403     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5404     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5405   }
5406
5407   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5408     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5409
5410   if (VT == MVT::v8i8) {
5411     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5412     if (NewOp.getNode())
5413       return NewOp;
5414   }
5415
5416   return SDValue();
5417 }
5418
5419 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5420   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5421   SDValue Lane = Op.getOperand(2);
5422   if (!isa<ConstantSDNode>(Lane))
5423     return SDValue();
5424
5425   return Op;
5426 }
5427
5428 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5429   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5430   SDValue Lane = Op.getOperand(1);
5431   if (!isa<ConstantSDNode>(Lane))
5432     return SDValue();
5433
5434   SDValue Vec = Op.getOperand(0);
5435   if (Op.getValueType() == MVT::i32 &&
5436       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5437     SDLoc dl(Op);
5438     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5439   }
5440
5441   return Op;
5442 }
5443
5444 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5445   // The only time a CONCAT_VECTORS operation can have legal types is when
5446   // two 64-bit vectors are concatenated to a 128-bit vector.
5447   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5448          "unexpected CONCAT_VECTORS");
5449   SDLoc dl(Op);
5450   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5451   SDValue Op0 = Op.getOperand(0);
5452   SDValue Op1 = Op.getOperand(1);
5453   if (Op0.getOpcode() != ISD::UNDEF)
5454     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5455                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5456                       DAG.getIntPtrConstant(0));
5457   if (Op1.getOpcode() != ISD::UNDEF)
5458     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5459                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5460                       DAG.getIntPtrConstant(1));
5461   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5462 }
5463
5464 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5465 /// element has been zero/sign-extended, depending on the isSigned parameter,
5466 /// from an integer type half its size.
5467 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5468                                    bool isSigned) {
5469   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5470   EVT VT = N->getValueType(0);
5471   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5472     SDNode *BVN = N->getOperand(0).getNode();
5473     if (BVN->getValueType(0) != MVT::v4i32 ||
5474         BVN->getOpcode() != ISD::BUILD_VECTOR)
5475       return false;
5476     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5477     unsigned HiElt = 1 - LoElt;
5478     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5479     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5480     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5481     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5482     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5483       return false;
5484     if (isSigned) {
5485       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5486           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5487         return true;
5488     } else {
5489       if (Hi0->isNullValue() && Hi1->isNullValue())
5490         return true;
5491     }
5492     return false;
5493   }
5494
5495   if (N->getOpcode() != ISD::BUILD_VECTOR)
5496     return false;
5497
5498   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5499     SDNode *Elt = N->getOperand(i).getNode();
5500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5501       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5502       unsigned HalfSize = EltSize / 2;
5503       if (isSigned) {
5504         if (!isIntN(HalfSize, C->getSExtValue()))
5505           return false;
5506       } else {
5507         if (!isUIntN(HalfSize, C->getZExtValue()))
5508           return false;
5509       }
5510       continue;
5511     }
5512     return false;
5513   }
5514
5515   return true;
5516 }
5517
5518 /// isSignExtended - Check if a node is a vector value that is sign-extended
5519 /// or a constant BUILD_VECTOR with sign-extended elements.
5520 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5521   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5522     return true;
5523   if (isExtendedBUILD_VECTOR(N, DAG, true))
5524     return true;
5525   return false;
5526 }
5527
5528 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5529 /// or a constant BUILD_VECTOR with zero-extended elements.
5530 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5531   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5532     return true;
5533   if (isExtendedBUILD_VECTOR(N, DAG, false))
5534     return true;
5535   return false;
5536 }
5537
5538 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5539   if (OrigVT.getSizeInBits() >= 64)
5540     return OrigVT;
5541
5542   assert(OrigVT.isSimple() && "Expecting a simple value type");
5543
5544   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5545   switch (OrigSimpleTy) {
5546   default: llvm_unreachable("Unexpected Vector Type");
5547   case MVT::v2i8:
5548   case MVT::v2i16:
5549      return MVT::v2i32;
5550   case MVT::v4i8:
5551     return  MVT::v4i16;
5552   }
5553 }
5554
5555 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5556 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5557 /// We insert the required extension here to get the vector to fill a D register.
5558 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5559                                             const EVT &OrigTy,
5560                                             const EVT &ExtTy,
5561                                             unsigned ExtOpcode) {
5562   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5563   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5564   // 64-bits we need to insert a new extension so that it will be 64-bits.
5565   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5566   if (OrigTy.getSizeInBits() >= 64)
5567     return N;
5568
5569   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5570   EVT NewVT = getExtensionTo64Bits(OrigTy);
5571
5572   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5573 }
5574
5575 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5576 /// does not do any sign/zero extension. If the original vector is less
5577 /// than 64 bits, an appropriate extension will be added after the load to
5578 /// reach a total size of 64 bits. We have to add the extension separately
5579 /// because ARM does not have a sign/zero extending load for vectors.
5580 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5581   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5582
5583   // The load already has the right type.
5584   if (ExtendedTy == LD->getMemoryVT())
5585     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5586                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5587                 LD->isNonTemporal(), LD->isInvariant(),
5588                 LD->getAlignment());
5589
5590   // We need to create a zextload/sextload. We cannot just create a load
5591   // followed by a zext/zext node because LowerMUL is also run during normal
5592   // operation legalization where we can't create illegal types.
5593   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5594                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5595                         LD->getMemoryVT(), LD->isVolatile(),
5596                         LD->isNonTemporal(), LD->getAlignment());
5597 }
5598
5599 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5600 /// extending load, or BUILD_VECTOR with extended elements, return the
5601 /// unextended value. The unextended vector should be 64 bits so that it can
5602 /// be used as an operand to a VMULL instruction. If the original vector size
5603 /// before extension is less than 64 bits we add a an extension to resize
5604 /// the vector to 64 bits.
5605 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5606   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5607     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5608                                         N->getOperand(0)->getValueType(0),
5609                                         N->getValueType(0),
5610                                         N->getOpcode());
5611
5612   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5613     return SkipLoadExtensionForVMULL(LD, DAG);
5614
5615   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5616   // have been legalized as a BITCAST from v4i32.
5617   if (N->getOpcode() == ISD::BITCAST) {
5618     SDNode *BVN = N->getOperand(0).getNode();
5619     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5620            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5621     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5622     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5623                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5624   }
5625   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5626   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5627   EVT VT = N->getValueType(0);
5628   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5629   unsigned NumElts = VT.getVectorNumElements();
5630   MVT TruncVT = MVT::getIntegerVT(EltSize);
5631   SmallVector<SDValue, 8> Ops;
5632   for (unsigned i = 0; i != NumElts; ++i) {
5633     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5634     const APInt &CInt = C->getAPIntValue();
5635     // Element types smaller than 32 bits are not legal, so use i32 elements.
5636     // The values are implicitly truncated so sext vs. zext doesn't matter.
5637     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5638   }
5639   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5640                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5641 }
5642
5643 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5644   unsigned Opcode = N->getOpcode();
5645   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5646     SDNode *N0 = N->getOperand(0).getNode();
5647     SDNode *N1 = N->getOperand(1).getNode();
5648     return N0->hasOneUse() && N1->hasOneUse() &&
5649       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5650   }
5651   return false;
5652 }
5653
5654 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5655   unsigned Opcode = N->getOpcode();
5656   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5657     SDNode *N0 = N->getOperand(0).getNode();
5658     SDNode *N1 = N->getOperand(1).getNode();
5659     return N0->hasOneUse() && N1->hasOneUse() &&
5660       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5661   }
5662   return false;
5663 }
5664
5665 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5666   // Multiplications are only custom-lowered for 128-bit vectors so that
5667   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5668   EVT VT = Op.getValueType();
5669   assert(VT.is128BitVector() && VT.isInteger() &&
5670          "unexpected type for custom-lowering ISD::MUL");
5671   SDNode *N0 = Op.getOperand(0).getNode();
5672   SDNode *N1 = Op.getOperand(1).getNode();
5673   unsigned NewOpc = 0;
5674   bool isMLA = false;
5675   bool isN0SExt = isSignExtended(N0, DAG);
5676   bool isN1SExt = isSignExtended(N1, DAG);
5677   if (isN0SExt && isN1SExt)
5678     NewOpc = ARMISD::VMULLs;
5679   else {
5680     bool isN0ZExt = isZeroExtended(N0, DAG);
5681     bool isN1ZExt = isZeroExtended(N1, DAG);
5682     if (isN0ZExt && isN1ZExt)
5683       NewOpc = ARMISD::VMULLu;
5684     else if (isN1SExt || isN1ZExt) {
5685       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5686       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5687       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5688         NewOpc = ARMISD::VMULLs;
5689         isMLA = true;
5690       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5691         NewOpc = ARMISD::VMULLu;
5692         isMLA = true;
5693       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5694         std::swap(N0, N1);
5695         NewOpc = ARMISD::VMULLu;
5696         isMLA = true;
5697       }
5698     }
5699
5700     if (!NewOpc) {
5701       if (VT == MVT::v2i64)
5702         // Fall through to expand this.  It is not legal.
5703         return SDValue();
5704       else
5705         // Other vector multiplications are legal.
5706         return Op;
5707     }
5708   }
5709
5710   // Legalize to a VMULL instruction.
5711   SDLoc DL(Op);
5712   SDValue Op0;
5713   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5714   if (!isMLA) {
5715     Op0 = SkipExtensionForVMULL(N0, DAG);
5716     assert(Op0.getValueType().is64BitVector() &&
5717            Op1.getValueType().is64BitVector() &&
5718            "unexpected types for extended operands to VMULL");
5719     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5720   }
5721
5722   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5723   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5724   //   vmull q0, d4, d6
5725   //   vmlal q0, d5, d6
5726   // is faster than
5727   //   vaddl q0, d4, d5
5728   //   vmovl q1, d6
5729   //   vmul  q0, q0, q1
5730   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5731   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5732   EVT Op1VT = Op1.getValueType();
5733   return DAG.getNode(N0->getOpcode(), DL, VT,
5734                      DAG.getNode(NewOpc, DL, VT,
5735                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5736                      DAG.getNode(NewOpc, DL, VT,
5737                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5738 }
5739
5740 static SDValue
5741 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5742   // Convert to float
5743   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5744   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5745   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5746   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5747   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5748   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5749   // Get reciprocal estimate.
5750   // float4 recip = vrecpeq_f32(yf);
5751   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5752                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5753   // Because char has a smaller range than uchar, we can actually get away
5754   // without any newton steps.  This requires that we use a weird bias
5755   // of 0xb000, however (again, this has been exhaustively tested).
5756   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5757   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5758   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5759   Y = DAG.getConstant(0xb000, MVT::i32);
5760   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5761   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5762   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5763   // Convert back to short.
5764   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5765   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5766   return X;
5767 }
5768
5769 static SDValue
5770 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5771   SDValue N2;
5772   // Convert to float.
5773   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5774   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5775   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5776   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5777   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5778   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5779
5780   // Use reciprocal estimate and one refinement step.
5781   // float4 recip = vrecpeq_f32(yf);
5782   // recip *= vrecpsq_f32(yf, recip);
5783   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5784                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5785   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5786                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5787                    N1, N2);
5788   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5789   // Because short has a smaller range than ushort, we can actually get away
5790   // with only a single newton step.  This requires that we use a weird bias
5791   // of 89, however (again, this has been exhaustively tested).
5792   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5793   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5794   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5795   N1 = DAG.getConstant(0x89, MVT::i32);
5796   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5797   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5798   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5799   // Convert back to integer and return.
5800   // return vmovn_s32(vcvt_s32_f32(result));
5801   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5802   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5803   return N0;
5804 }
5805
5806 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5807   EVT VT = Op.getValueType();
5808   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5809          "unexpected type for custom-lowering ISD::SDIV");
5810
5811   SDLoc dl(Op);
5812   SDValue N0 = Op.getOperand(0);
5813   SDValue N1 = Op.getOperand(1);
5814   SDValue N2, N3;
5815
5816   if (VT == MVT::v8i8) {
5817     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5818     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5819
5820     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5821                      DAG.getIntPtrConstant(4));
5822     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5823                      DAG.getIntPtrConstant(4));
5824     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5825                      DAG.getIntPtrConstant(0));
5826     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5827                      DAG.getIntPtrConstant(0));
5828
5829     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5830     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5831
5832     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5833     N0 = LowerCONCAT_VECTORS(N0, DAG);
5834
5835     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5836     return N0;
5837   }
5838   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5839 }
5840
5841 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5842   EVT VT = Op.getValueType();
5843   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5844          "unexpected type for custom-lowering ISD::UDIV");
5845
5846   SDLoc dl(Op);
5847   SDValue N0 = Op.getOperand(0);
5848   SDValue N1 = Op.getOperand(1);
5849   SDValue N2, N3;
5850
5851   if (VT == MVT::v8i8) {
5852     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5853     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5854
5855     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5856                      DAG.getIntPtrConstant(4));
5857     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5858                      DAG.getIntPtrConstant(4));
5859     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5860                      DAG.getIntPtrConstant(0));
5861     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5862                      DAG.getIntPtrConstant(0));
5863
5864     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5865     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5866
5867     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5868     N0 = LowerCONCAT_VECTORS(N0, DAG);
5869
5870     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5871                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5872                      N0);
5873     return N0;
5874   }
5875
5876   // v4i16 sdiv ... Convert to float.
5877   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5878   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5879   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5880   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5881   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5882   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5883
5884   // Use reciprocal estimate and two refinement steps.
5885   // float4 recip = vrecpeq_f32(yf);
5886   // recip *= vrecpsq_f32(yf, recip);
5887   // recip *= vrecpsq_f32(yf, recip);
5888   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5889                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
5890   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5891                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5892                    BN1, N2);
5893   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5894   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5895                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5896                    BN1, N2);
5897   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5898   // Simply multiplying by the reciprocal estimate can leave us a few ulps
5899   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
5900   // and that it will never cause us to return an answer too large).
5901   // float4 result = as_float4(as_int4(xf*recip) + 2);
5902   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5903   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5904   N1 = DAG.getConstant(2, MVT::i32);
5905   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5906   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5907   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5908   // Convert back to integer and return.
5909   // return vmovn_u32(vcvt_s32_f32(result));
5910   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5911   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5912   return N0;
5913 }
5914
5915 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
5916   EVT VT = Op.getNode()->getValueType(0);
5917   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
5918
5919   unsigned Opc;
5920   bool ExtraOp = false;
5921   switch (Op.getOpcode()) {
5922   default: llvm_unreachable("Invalid code");
5923   case ISD::ADDC: Opc = ARMISD::ADDC; break;
5924   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
5925   case ISD::SUBC: Opc = ARMISD::SUBC; break;
5926   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
5927   }
5928
5929   if (!ExtraOp)
5930     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5931                        Op.getOperand(1));
5932   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
5933                      Op.getOperand(1), Op.getOperand(2));
5934 }
5935
5936 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
5937   assert(Subtarget->isTargetDarwin());
5938
5939   // For iOS, we want to call an alternative entry point: __sincos_stret,
5940   // return values are passed via sret.
5941   SDLoc dl(Op);
5942   SDValue Arg = Op.getOperand(0);
5943   EVT ArgVT = Arg.getValueType();
5944   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
5945
5946   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5948
5949   // Pair of floats / doubles used to pass the result.
5950   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
5951
5952   // Create stack object for sret.
5953   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
5954   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
5955   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
5956   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
5957
5958   ArgListTy Args;
5959   ArgListEntry Entry;
5960
5961   Entry.Node = SRet;
5962   Entry.Ty = RetTy->getPointerTo();
5963   Entry.isSExt = false;
5964   Entry.isZExt = false;
5965   Entry.isSRet = true;
5966   Args.push_back(Entry);
5967
5968   Entry.Node = Arg;
5969   Entry.Ty = ArgTy;
5970   Entry.isSExt = false;
5971   Entry.isZExt = false;
5972   Args.push_back(Entry);
5973
5974   const char *LibcallName  = (ArgVT == MVT::f64)
5975   ? "__sincos_stret" : "__sincosf_stret";
5976   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
5977
5978   TargetLowering::
5979   CallLoweringInfo CLI(DAG.getEntryNode(), Type::getVoidTy(*DAG.getContext()),
5980                        false, false, false, false, 0,
5981                        CallingConv::C, /*isTaillCall=*/false,
5982                        /*doesNotRet=*/false, /*isReturnValueUsed*/false,
5983                        Callee, Args, DAG, dl);
5984   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
5985
5986   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
5987                                 MachinePointerInfo(), false, false, false, 0);
5988
5989   // Address of cos field.
5990   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
5991                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
5992   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
5993                                 MachinePointerInfo(), false, false, false, 0);
5994
5995   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
5996   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
5997                      LoadSin.getValue(0), LoadCos.getValue(0));
5998 }
5999
6000 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6001   // Monotonic load/store is legal for all targets
6002   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6003     return Op;
6004
6005   // Acquire/Release load/store is not legal for targets without a
6006   // dmb or equivalent available.
6007   return SDValue();
6008 }
6009
6010 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6011                                     SmallVectorImpl<SDValue> &Results,
6012                                     SelectionDAG &DAG,
6013                                     const ARMSubtarget *Subtarget) {
6014   SDLoc DL(N);
6015   SDValue Cycles32, OutChain;
6016
6017   if (Subtarget->hasPerfMon()) {
6018     // Under Power Management extensions, the cycle-count is:
6019     //    mrc p15, #0, <Rt>, c9, c13, #0
6020     SDValue Ops[] = { N->getOperand(0), // Chain
6021                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6022                       DAG.getConstant(15, MVT::i32),
6023                       DAG.getConstant(0, MVT::i32),
6024                       DAG.getConstant(9, MVT::i32),
6025                       DAG.getConstant(13, MVT::i32),
6026                       DAG.getConstant(0, MVT::i32)
6027     };
6028
6029     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6030                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6031     OutChain = Cycles32.getValue(1);
6032   } else {
6033     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6034     // there are older ARM CPUs that have implementation-specific ways of
6035     // obtaining this information (FIXME!).
6036     Cycles32 = DAG.getConstant(0, MVT::i32);
6037     OutChain = DAG.getEntryNode();
6038   }
6039
6040
6041   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6042                                  Cycles32, DAG.getConstant(0, MVT::i32));
6043   Results.push_back(Cycles64);
6044   Results.push_back(OutChain);
6045 }
6046
6047 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6048   switch (Op.getOpcode()) {
6049   default: llvm_unreachable("Don't know how to custom lower this!");
6050   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6051   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6052   case ISD::GlobalAddress:
6053     return Subtarget->isTargetMachO() ? LowerGlobalAddressDarwin(Op, DAG) :
6054       LowerGlobalAddressELF(Op, DAG);
6055   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6056   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6057   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6058   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6059   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6060   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6061   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6062   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6063   case ISD::SINT_TO_FP:
6064   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6065   case ISD::FP_TO_SINT:
6066   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6067   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6068   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6069   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6070   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6071   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6072   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6073   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6074                                                                Subtarget);
6075   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6076   case ISD::SHL:
6077   case ISD::SRL:
6078   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6079   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6080   case ISD::SRL_PARTS:
6081   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6082   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6083   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6084   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6085   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6086   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6087   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6088   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6089   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6090   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6091   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6092   case ISD::MUL:           return LowerMUL(Op, DAG);
6093   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6094   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6095   case ISD::ADDC:
6096   case ISD::ADDE:
6097   case ISD::SUBC:
6098   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6099   case ISD::ATOMIC_LOAD:
6100   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6101   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6102   case ISD::SDIVREM:
6103   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6104   }
6105 }
6106
6107 /// ReplaceNodeResults - Replace the results of node with an illegal result
6108 /// type with new values built out of custom code.
6109 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6110                                            SmallVectorImpl<SDValue>&Results,
6111                                            SelectionDAG &DAG) const {
6112   SDValue Res;
6113   switch (N->getOpcode()) {
6114   default:
6115     llvm_unreachable("Don't know how to custom expand this!");
6116   case ISD::BITCAST:
6117     Res = ExpandBITCAST(N, DAG);
6118     break;
6119   case ISD::SRL:
6120   case ISD::SRA:
6121     Res = Expand64BitShift(N, DAG, Subtarget);
6122     break;
6123   case ISD::READCYCLECOUNTER:
6124     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6125     return;
6126   }
6127   if (Res.getNode())
6128     Results.push_back(Res);
6129 }
6130
6131 //===----------------------------------------------------------------------===//
6132 //                           ARM Scheduler Hooks
6133 //===----------------------------------------------------------------------===//
6134
6135 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6136 /// registers the function context.
6137 void ARMTargetLowering::
6138 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6139                        MachineBasicBlock *DispatchBB, int FI) const {
6140   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6141   DebugLoc dl = MI->getDebugLoc();
6142   MachineFunction *MF = MBB->getParent();
6143   MachineRegisterInfo *MRI = &MF->getRegInfo();
6144   MachineConstantPool *MCP = MF->getConstantPool();
6145   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6146   const Function *F = MF->getFunction();
6147
6148   bool isThumb = Subtarget->isThumb();
6149   bool isThumb2 = Subtarget->isThumb2();
6150
6151   unsigned PCLabelId = AFI->createPICLabelUId();
6152   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6153   ARMConstantPoolValue *CPV =
6154     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6155   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6156
6157   const TargetRegisterClass *TRC = isThumb ?
6158     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6159     (const TargetRegisterClass*)&ARM::GPRRegClass;
6160
6161   // Grab constant pool and fixed stack memory operands.
6162   MachineMemOperand *CPMMO =
6163     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6164                              MachineMemOperand::MOLoad, 4, 4);
6165
6166   MachineMemOperand *FIMMOSt =
6167     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6168                              MachineMemOperand::MOStore, 4, 4);
6169
6170   // Load the address of the dispatch MBB into the jump buffer.
6171   if (isThumb2) {
6172     // Incoming value: jbuf
6173     //   ldr.n  r5, LCPI1_1
6174     //   orr    r5, r5, #1
6175     //   add    r5, pc
6176     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6177     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6178     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6179                    .addConstantPoolIndex(CPI)
6180                    .addMemOperand(CPMMO));
6181     // Set the low bit because of thumb mode.
6182     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6183     AddDefaultCC(
6184       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6185                      .addReg(NewVReg1, RegState::Kill)
6186                      .addImm(0x01)));
6187     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6188     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6189       .addReg(NewVReg2, RegState::Kill)
6190       .addImm(PCLabelId);
6191     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6192                    .addReg(NewVReg3, RegState::Kill)
6193                    .addFrameIndex(FI)
6194                    .addImm(36)  // &jbuf[1] :: pc
6195                    .addMemOperand(FIMMOSt));
6196   } else if (isThumb) {
6197     // Incoming value: jbuf
6198     //   ldr.n  r1, LCPI1_4
6199     //   add    r1, pc
6200     //   mov    r2, #1
6201     //   orrs   r1, r2
6202     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6203     //   str    r1, [r2]
6204     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6205     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6206                    .addConstantPoolIndex(CPI)
6207                    .addMemOperand(CPMMO));
6208     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6209     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6210       .addReg(NewVReg1, RegState::Kill)
6211       .addImm(PCLabelId);
6212     // Set the low bit because of thumb mode.
6213     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6214     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6215                    .addReg(ARM::CPSR, RegState::Define)
6216                    .addImm(1));
6217     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6218     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6219                    .addReg(ARM::CPSR, RegState::Define)
6220                    .addReg(NewVReg2, RegState::Kill)
6221                    .addReg(NewVReg3, RegState::Kill));
6222     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6223     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6224                    .addFrameIndex(FI)
6225                    .addImm(36)); // &jbuf[1] :: pc
6226     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6227                    .addReg(NewVReg4, RegState::Kill)
6228                    .addReg(NewVReg5, RegState::Kill)
6229                    .addImm(0)
6230                    .addMemOperand(FIMMOSt));
6231   } else {
6232     // Incoming value: jbuf
6233     //   ldr  r1, LCPI1_1
6234     //   add  r1, pc, r1
6235     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6236     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6237     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6238                    .addConstantPoolIndex(CPI)
6239                    .addImm(0)
6240                    .addMemOperand(CPMMO));
6241     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6242     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6243                    .addReg(NewVReg1, RegState::Kill)
6244                    .addImm(PCLabelId));
6245     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6246                    .addReg(NewVReg2, RegState::Kill)
6247                    .addFrameIndex(FI)
6248                    .addImm(36)  // &jbuf[1] :: pc
6249                    .addMemOperand(FIMMOSt));
6250   }
6251 }
6252
6253 MachineBasicBlock *ARMTargetLowering::
6254 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6255   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6256   DebugLoc dl = MI->getDebugLoc();
6257   MachineFunction *MF = MBB->getParent();
6258   MachineRegisterInfo *MRI = &MF->getRegInfo();
6259   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6260   MachineFrameInfo *MFI = MF->getFrameInfo();
6261   int FI = MFI->getFunctionContextIndex();
6262
6263   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6264     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6265     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6266
6267   // Get a mapping of the call site numbers to all of the landing pads they're
6268   // associated with.
6269   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6270   unsigned MaxCSNum = 0;
6271   MachineModuleInfo &MMI = MF->getMMI();
6272   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6273        ++BB) {
6274     if (!BB->isLandingPad()) continue;
6275
6276     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6277     // pad.
6278     for (MachineBasicBlock::iterator
6279            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6280       if (!II->isEHLabel()) continue;
6281
6282       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6283       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6284
6285       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6286       for (SmallVectorImpl<unsigned>::iterator
6287              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6288            CSI != CSE; ++CSI) {
6289         CallSiteNumToLPad[*CSI].push_back(BB);
6290         MaxCSNum = std::max(MaxCSNum, *CSI);
6291       }
6292       break;
6293     }
6294   }
6295
6296   // Get an ordered list of the machine basic blocks for the jump table.
6297   std::vector<MachineBasicBlock*> LPadList;
6298   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6299   LPadList.reserve(CallSiteNumToLPad.size());
6300   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6301     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6302     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6303            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6304       LPadList.push_back(*II);
6305       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6306     }
6307   }
6308
6309   assert(!LPadList.empty() &&
6310          "No landing pad destinations for the dispatch jump table!");
6311
6312   // Create the jump table and associated information.
6313   MachineJumpTableInfo *JTI =
6314     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6315   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6316   unsigned UId = AFI->createJumpTableUId();
6317   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6318
6319   // Create the MBBs for the dispatch code.
6320
6321   // Shove the dispatch's address into the return slot in the function context.
6322   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6323   DispatchBB->setIsLandingPad();
6324
6325   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6326   unsigned trap_opcode;
6327   if (Subtarget->isThumb())
6328     trap_opcode = ARM::tTRAP;
6329   else
6330     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6331
6332   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6333   DispatchBB->addSuccessor(TrapBB);
6334
6335   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6336   DispatchBB->addSuccessor(DispContBB);
6337
6338   // Insert and MBBs.
6339   MF->insert(MF->end(), DispatchBB);
6340   MF->insert(MF->end(), DispContBB);
6341   MF->insert(MF->end(), TrapBB);
6342
6343   // Insert code into the entry block that creates and registers the function
6344   // context.
6345   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6346
6347   MachineMemOperand *FIMMOLd =
6348     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6349                              MachineMemOperand::MOLoad |
6350                              MachineMemOperand::MOVolatile, 4, 4);
6351
6352   MachineInstrBuilder MIB;
6353   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6354
6355   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6356   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6357
6358   // Add a register mask with no preserved registers.  This results in all
6359   // registers being marked as clobbered.
6360   MIB.addRegMask(RI.getNoPreservedMask());
6361
6362   unsigned NumLPads = LPadList.size();
6363   if (Subtarget->isThumb2()) {
6364     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6365     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6366                    .addFrameIndex(FI)
6367                    .addImm(4)
6368                    .addMemOperand(FIMMOLd));
6369
6370     if (NumLPads < 256) {
6371       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6372                      .addReg(NewVReg1)
6373                      .addImm(LPadList.size()));
6374     } else {
6375       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6376       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6377                      .addImm(NumLPads & 0xFFFF));
6378
6379       unsigned VReg2 = VReg1;
6380       if ((NumLPads & 0xFFFF0000) != 0) {
6381         VReg2 = MRI->createVirtualRegister(TRC);
6382         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6383                        .addReg(VReg1)
6384                        .addImm(NumLPads >> 16));
6385       }
6386
6387       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6388                      .addReg(NewVReg1)
6389                      .addReg(VReg2));
6390     }
6391
6392     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6393       .addMBB(TrapBB)
6394       .addImm(ARMCC::HI)
6395       .addReg(ARM::CPSR);
6396
6397     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6398     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6399                    .addJumpTableIndex(MJTI)
6400                    .addImm(UId));
6401
6402     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6403     AddDefaultCC(
6404       AddDefaultPred(
6405         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6406         .addReg(NewVReg3, RegState::Kill)
6407         .addReg(NewVReg1)
6408         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6409
6410     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6411       .addReg(NewVReg4, RegState::Kill)
6412       .addReg(NewVReg1)
6413       .addJumpTableIndex(MJTI)
6414       .addImm(UId);
6415   } else if (Subtarget->isThumb()) {
6416     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6417     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6418                    .addFrameIndex(FI)
6419                    .addImm(1)
6420                    .addMemOperand(FIMMOLd));
6421
6422     if (NumLPads < 256) {
6423       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6424                      .addReg(NewVReg1)
6425                      .addImm(NumLPads));
6426     } else {
6427       MachineConstantPool *ConstantPool = MF->getConstantPool();
6428       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6429       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6430
6431       // MachineConstantPool wants an explicit alignment.
6432       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6433       if (Align == 0)
6434         Align = getDataLayout()->getTypeAllocSize(C->getType());
6435       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6436
6437       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6438       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6439                      .addReg(VReg1, RegState::Define)
6440                      .addConstantPoolIndex(Idx));
6441       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6442                      .addReg(NewVReg1)
6443                      .addReg(VReg1));
6444     }
6445
6446     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6447       .addMBB(TrapBB)
6448       .addImm(ARMCC::HI)
6449       .addReg(ARM::CPSR);
6450
6451     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6452     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6453                    .addReg(ARM::CPSR, RegState::Define)
6454                    .addReg(NewVReg1)
6455                    .addImm(2));
6456
6457     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6458     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6459                    .addJumpTableIndex(MJTI)
6460                    .addImm(UId));
6461
6462     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6463     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6464                    .addReg(ARM::CPSR, RegState::Define)
6465                    .addReg(NewVReg2, RegState::Kill)
6466                    .addReg(NewVReg3));
6467
6468     MachineMemOperand *JTMMOLd =
6469       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6470                                MachineMemOperand::MOLoad, 4, 4);
6471
6472     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6473     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6474                    .addReg(NewVReg4, RegState::Kill)
6475                    .addImm(0)
6476                    .addMemOperand(JTMMOLd));
6477
6478     unsigned NewVReg6 = NewVReg5;
6479     if (RelocM == Reloc::PIC_) {
6480       NewVReg6 = MRI->createVirtualRegister(TRC);
6481       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6482                      .addReg(ARM::CPSR, RegState::Define)
6483                      .addReg(NewVReg5, RegState::Kill)
6484                      .addReg(NewVReg3));
6485     }
6486
6487     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6488       .addReg(NewVReg6, RegState::Kill)
6489       .addJumpTableIndex(MJTI)
6490       .addImm(UId);
6491   } else {
6492     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6493     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6494                    .addFrameIndex(FI)
6495                    .addImm(4)
6496                    .addMemOperand(FIMMOLd));
6497
6498     if (NumLPads < 256) {
6499       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6500                      .addReg(NewVReg1)
6501                      .addImm(NumLPads));
6502     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6503       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6504       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6505                      .addImm(NumLPads & 0xFFFF));
6506
6507       unsigned VReg2 = VReg1;
6508       if ((NumLPads & 0xFFFF0000) != 0) {
6509         VReg2 = MRI->createVirtualRegister(TRC);
6510         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6511                        .addReg(VReg1)
6512                        .addImm(NumLPads >> 16));
6513       }
6514
6515       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6516                      .addReg(NewVReg1)
6517                      .addReg(VReg2));
6518     } else {
6519       MachineConstantPool *ConstantPool = MF->getConstantPool();
6520       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6521       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6522
6523       // MachineConstantPool wants an explicit alignment.
6524       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6525       if (Align == 0)
6526         Align = getDataLayout()->getTypeAllocSize(C->getType());
6527       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6528
6529       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6530       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6531                      .addReg(VReg1, RegState::Define)
6532                      .addConstantPoolIndex(Idx)
6533                      .addImm(0));
6534       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6535                      .addReg(NewVReg1)
6536                      .addReg(VReg1, RegState::Kill));
6537     }
6538
6539     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6540       .addMBB(TrapBB)
6541       .addImm(ARMCC::HI)
6542       .addReg(ARM::CPSR);
6543
6544     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6545     AddDefaultCC(
6546       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6547                      .addReg(NewVReg1)
6548                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6549     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6551                    .addJumpTableIndex(MJTI)
6552                    .addImm(UId));
6553
6554     MachineMemOperand *JTMMOLd =
6555       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6556                                MachineMemOperand::MOLoad, 4, 4);
6557     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6558     AddDefaultPred(
6559       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6560       .addReg(NewVReg3, RegState::Kill)
6561       .addReg(NewVReg4)
6562       .addImm(0)
6563       .addMemOperand(JTMMOLd));
6564
6565     if (RelocM == Reloc::PIC_) {
6566       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6567         .addReg(NewVReg5, RegState::Kill)
6568         .addReg(NewVReg4)
6569         .addJumpTableIndex(MJTI)
6570         .addImm(UId);
6571     } else {
6572       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6573         .addReg(NewVReg5, RegState::Kill)
6574         .addJumpTableIndex(MJTI)
6575         .addImm(UId);
6576     }
6577   }
6578
6579   // Add the jump table entries as successors to the MBB.
6580   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6581   for (std::vector<MachineBasicBlock*>::iterator
6582          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6583     MachineBasicBlock *CurMBB = *I;
6584     if (SeenMBBs.insert(CurMBB))
6585       DispContBB->addSuccessor(CurMBB);
6586   }
6587
6588   // N.B. the order the invoke BBs are processed in doesn't matter here.
6589   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6590   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6591   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6592          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6593     MachineBasicBlock *BB = *I;
6594
6595     // Remove the landing pad successor from the invoke block and replace it
6596     // with the new dispatch block.
6597     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6598                                                   BB->succ_end());
6599     while (!Successors.empty()) {
6600       MachineBasicBlock *SMBB = Successors.pop_back_val();
6601       if (SMBB->isLandingPad()) {
6602         BB->removeSuccessor(SMBB);
6603         MBBLPads.push_back(SMBB);
6604       }
6605     }
6606
6607     BB->addSuccessor(DispatchBB);
6608
6609     // Find the invoke call and mark all of the callee-saved registers as
6610     // 'implicit defined' so that they're spilled. This prevents code from
6611     // moving instructions to before the EH block, where they will never be
6612     // executed.
6613     for (MachineBasicBlock::reverse_iterator
6614            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6615       if (!II->isCall()) continue;
6616
6617       DenseMap<unsigned, bool> DefRegs;
6618       for (MachineInstr::mop_iterator
6619              OI = II->operands_begin(), OE = II->operands_end();
6620            OI != OE; ++OI) {
6621         if (!OI->isReg()) continue;
6622         DefRegs[OI->getReg()] = true;
6623       }
6624
6625       MachineInstrBuilder MIB(*MF, &*II);
6626
6627       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6628         unsigned Reg = SavedRegs[i];
6629         if (Subtarget->isThumb2() &&
6630             !ARM::tGPRRegClass.contains(Reg) &&
6631             !ARM::hGPRRegClass.contains(Reg))
6632           continue;
6633         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6634           continue;
6635         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6636           continue;
6637         if (!DefRegs[Reg])
6638           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6639       }
6640
6641       break;
6642     }
6643   }
6644
6645   // Mark all former landing pads as non-landing pads. The dispatch is the only
6646   // landing pad now.
6647   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6648          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6649     (*I)->setIsLandingPad(false);
6650
6651   // The instruction is gone now.
6652   MI->eraseFromParent();
6653
6654   return MBB;
6655 }
6656
6657 static
6658 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6659   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6660        E = MBB->succ_end(); I != E; ++I)
6661     if (*I != Succ)
6662       return *I;
6663   llvm_unreachable("Expecting a BB with two successors!");
6664 }
6665
6666 /// Return the load opcode for a given load size. If load size >= 8,
6667 /// neon opcode will be returned.
6668 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6669   if (LdSize >= 8)
6670     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6671                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6672   if (IsThumb1)
6673     return LdSize == 4 ? ARM::tLDRi
6674                        : LdSize == 2 ? ARM::tLDRHi
6675                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6676   if (IsThumb2)
6677     return LdSize == 4 ? ARM::t2LDR_POST
6678                        : LdSize == 2 ? ARM::t2LDRH_POST
6679                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6680   return LdSize == 4 ? ARM::LDR_POST_IMM
6681                      : LdSize == 2 ? ARM::LDRH_POST
6682                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6683 }
6684
6685 /// Return the store opcode for a given store size. If store size >= 8,
6686 /// neon opcode will be returned.
6687 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6688   if (StSize >= 8)
6689     return StSize == 16 ? ARM::VST1q32wb_fixed
6690                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6691   if (IsThumb1)
6692     return StSize == 4 ? ARM::tSTRi
6693                        : StSize == 2 ? ARM::tSTRHi
6694                                      : StSize == 1 ? ARM::tSTRBi : 0;
6695   if (IsThumb2)
6696     return StSize == 4 ? ARM::t2STR_POST
6697                        : StSize == 2 ? ARM::t2STRH_POST
6698                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6699   return StSize == 4 ? ARM::STR_POST_IMM
6700                      : StSize == 2 ? ARM::STRH_POST
6701                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6702 }
6703
6704 /// Emit a post-increment load operation with given size. The instructions
6705 /// will be added to BB at Pos.
6706 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6707                        const TargetInstrInfo *TII, DebugLoc dl,
6708                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6709                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6710   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6711   assert(LdOpc != 0 && "Should have a load opcode");
6712   if (LdSize >= 8) {
6713     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6714                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6715                        .addImm(0));
6716   } else if (IsThumb1) {
6717     // load + update AddrIn
6718     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6719                        .addReg(AddrIn).addImm(0));
6720     MachineInstrBuilder MIB =
6721         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6722     MIB = AddDefaultT1CC(MIB);
6723     MIB.addReg(AddrIn).addImm(LdSize);
6724     AddDefaultPred(MIB);
6725   } else if (IsThumb2) {
6726     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6727                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6728                        .addImm(LdSize));
6729   } else { // arm
6730     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6731                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6732                        .addReg(0).addImm(LdSize));
6733   }
6734 }
6735
6736 /// Emit a post-increment store operation with given size. The instructions
6737 /// will be added to BB at Pos.
6738 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6739                        const TargetInstrInfo *TII, DebugLoc dl,
6740                        unsigned StSize, unsigned Data, unsigned AddrIn,
6741                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6742   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6743   assert(StOpc != 0 && "Should have a store opcode");
6744   if (StSize >= 8) {
6745     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6746                        .addReg(AddrIn).addImm(0).addReg(Data));
6747   } else if (IsThumb1) {
6748     // store + update AddrIn
6749     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6750                        .addReg(AddrIn).addImm(0));
6751     MachineInstrBuilder MIB =
6752         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6753     MIB = AddDefaultT1CC(MIB);
6754     MIB.addReg(AddrIn).addImm(StSize);
6755     AddDefaultPred(MIB);
6756   } else if (IsThumb2) {
6757     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6758                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6759   } else { // arm
6760     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6761                        .addReg(Data).addReg(AddrIn).addReg(0)
6762                        .addImm(StSize));
6763   }
6764 }
6765
6766 MachineBasicBlock *
6767 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6768                                    MachineBasicBlock *BB) const {
6769   // This pseudo instruction has 3 operands: dst, src, size
6770   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6771   // Otherwise, we will generate unrolled scalar copies.
6772   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6773   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6774   MachineFunction::iterator It = BB;
6775   ++It;
6776
6777   unsigned dest = MI->getOperand(0).getReg();
6778   unsigned src = MI->getOperand(1).getReg();
6779   unsigned SizeVal = MI->getOperand(2).getImm();
6780   unsigned Align = MI->getOperand(3).getImm();
6781   DebugLoc dl = MI->getDebugLoc();
6782
6783   MachineFunction *MF = BB->getParent();
6784   MachineRegisterInfo &MRI = MF->getRegInfo();
6785   unsigned UnitSize = 0;
6786   const TargetRegisterClass *TRC = nullptr;
6787   const TargetRegisterClass *VecTRC = nullptr;
6788
6789   bool IsThumb1 = Subtarget->isThumb1Only();
6790   bool IsThumb2 = Subtarget->isThumb2();
6791
6792   if (Align & 1) {
6793     UnitSize = 1;
6794   } else if (Align & 2) {
6795     UnitSize = 2;
6796   } else {
6797     // Check whether we can use NEON instructions.
6798     if (!MF->getFunction()->getAttributes().
6799           hasAttribute(AttributeSet::FunctionIndex,
6800                        Attribute::NoImplicitFloat) &&
6801         Subtarget->hasNEON()) {
6802       if ((Align % 16 == 0) && SizeVal >= 16)
6803         UnitSize = 16;
6804       else if ((Align % 8 == 0) && SizeVal >= 8)
6805         UnitSize = 8;
6806     }
6807     // Can't use NEON instructions.
6808     if (UnitSize == 0)
6809       UnitSize = 4;
6810   }
6811
6812   // Select the correct opcode and register class for unit size load/store
6813   bool IsNeon = UnitSize >= 8;
6814   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6815                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6816   if (IsNeon)
6817     VecTRC = UnitSize == 16
6818                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6819                  : UnitSize == 8
6820                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6821                        : nullptr;
6822
6823   unsigned BytesLeft = SizeVal % UnitSize;
6824   unsigned LoopSize = SizeVal - BytesLeft;
6825
6826   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6827     // Use LDR and STR to copy.
6828     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6829     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6830     unsigned srcIn = src;
6831     unsigned destIn = dest;
6832     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6833       unsigned srcOut = MRI.createVirtualRegister(TRC);
6834       unsigned destOut = MRI.createVirtualRegister(TRC);
6835       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6836       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6837                  IsThumb1, IsThumb2);
6838       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6839                  IsThumb1, IsThumb2);
6840       srcIn = srcOut;
6841       destIn = destOut;
6842     }
6843
6844     // Handle the leftover bytes with LDRB and STRB.
6845     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6846     // [destOut] = STRB_POST(scratch, destIn, 1)
6847     for (unsigned i = 0; i < BytesLeft; i++) {
6848       unsigned srcOut = MRI.createVirtualRegister(TRC);
6849       unsigned destOut = MRI.createVirtualRegister(TRC);
6850       unsigned scratch = MRI.createVirtualRegister(TRC);
6851       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6852                  IsThumb1, IsThumb2);
6853       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6854                  IsThumb1, IsThumb2);
6855       srcIn = srcOut;
6856       destIn = destOut;
6857     }
6858     MI->eraseFromParent();   // The instruction is gone now.
6859     return BB;
6860   }
6861
6862   // Expand the pseudo op to a loop.
6863   // thisMBB:
6864   //   ...
6865   //   movw varEnd, # --> with thumb2
6866   //   movt varEnd, #
6867   //   ldrcp varEnd, idx --> without thumb2
6868   //   fallthrough --> loopMBB
6869   // loopMBB:
6870   //   PHI varPhi, varEnd, varLoop
6871   //   PHI srcPhi, src, srcLoop
6872   //   PHI destPhi, dst, destLoop
6873   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6874   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
6875   //   subs varLoop, varPhi, #UnitSize
6876   //   bne loopMBB
6877   //   fallthrough --> exitMBB
6878   // exitMBB:
6879   //   epilogue to handle left-over bytes
6880   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6881   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6882   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6883   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
6884   MF->insert(It, loopMBB);
6885   MF->insert(It, exitMBB);
6886
6887   // Transfer the remainder of BB and its successor edges to exitMBB.
6888   exitMBB->splice(exitMBB->begin(), BB,
6889                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6890   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6891
6892   // Load an immediate to varEnd.
6893   unsigned varEnd = MRI.createVirtualRegister(TRC);
6894   if (IsThumb2) {
6895     unsigned Vtmp = varEnd;
6896     if ((LoopSize & 0xFFFF0000) != 0)
6897       Vtmp = MRI.createVirtualRegister(TRC);
6898     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
6899                        .addImm(LoopSize & 0xFFFF));
6900
6901     if ((LoopSize & 0xFFFF0000) != 0)
6902       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
6903                          .addReg(Vtmp).addImm(LoopSize >> 16));
6904   } else {
6905     MachineConstantPool *ConstantPool = MF->getConstantPool();
6906     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6907     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
6908
6909     // MachineConstantPool wants an explicit alignment.
6910     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6911     if (Align == 0)
6912       Align = getDataLayout()->getTypeAllocSize(C->getType());
6913     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6914
6915     if (IsThumb1)
6916       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
6917           varEnd, RegState::Define).addConstantPoolIndex(Idx));
6918     else
6919       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
6920           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
6921   }
6922   BB->addSuccessor(loopMBB);
6923
6924   // Generate the loop body:
6925   //   varPhi = PHI(varLoop, varEnd)
6926   //   srcPhi = PHI(srcLoop, src)
6927   //   destPhi = PHI(destLoop, dst)
6928   MachineBasicBlock *entryBB = BB;
6929   BB = loopMBB;
6930   unsigned varLoop = MRI.createVirtualRegister(TRC);
6931   unsigned varPhi = MRI.createVirtualRegister(TRC);
6932   unsigned srcLoop = MRI.createVirtualRegister(TRC);
6933   unsigned srcPhi = MRI.createVirtualRegister(TRC);
6934   unsigned destLoop = MRI.createVirtualRegister(TRC);
6935   unsigned destPhi = MRI.createVirtualRegister(TRC);
6936
6937   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
6938     .addReg(varLoop).addMBB(loopMBB)
6939     .addReg(varEnd).addMBB(entryBB);
6940   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
6941     .addReg(srcLoop).addMBB(loopMBB)
6942     .addReg(src).addMBB(entryBB);
6943   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
6944     .addReg(destLoop).addMBB(loopMBB)
6945     .addReg(dest).addMBB(entryBB);
6946
6947   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
6948   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
6949   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6950   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
6951              IsThumb1, IsThumb2);
6952   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
6953              IsThumb1, IsThumb2);
6954
6955   // Decrement loop variable by UnitSize.
6956   if (IsThumb1) {
6957     MachineInstrBuilder MIB =
6958         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
6959     MIB = AddDefaultT1CC(MIB);
6960     MIB.addReg(varPhi).addImm(UnitSize);
6961     AddDefaultPred(MIB);
6962   } else {
6963     MachineInstrBuilder MIB =
6964         BuildMI(*BB, BB->end(), dl,
6965                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
6966     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
6967     MIB->getOperand(5).setReg(ARM::CPSR);
6968     MIB->getOperand(5).setIsDef(true);
6969   }
6970   BuildMI(*BB, BB->end(), dl,
6971           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
6972       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
6973
6974   // loopMBB can loop back to loopMBB or fall through to exitMBB.
6975   BB->addSuccessor(loopMBB);
6976   BB->addSuccessor(exitMBB);
6977
6978   // Add epilogue to handle BytesLeft.
6979   BB = exitMBB;
6980   MachineInstr *StartOfExit = exitMBB->begin();
6981
6982   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
6983   //   [destOut] = STRB_POST(scratch, destLoop, 1)
6984   unsigned srcIn = srcLoop;
6985   unsigned destIn = destLoop;
6986   for (unsigned i = 0; i < BytesLeft; i++) {
6987     unsigned srcOut = MRI.createVirtualRegister(TRC);
6988     unsigned destOut = MRI.createVirtualRegister(TRC);
6989     unsigned scratch = MRI.createVirtualRegister(TRC);
6990     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
6991                IsThumb1, IsThumb2);
6992     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
6993                IsThumb1, IsThumb2);
6994     srcIn = srcOut;
6995     destIn = destOut;
6996   }
6997
6998   MI->eraseFromParent();   // The instruction is gone now.
6999   return BB;
7000 }
7001
7002 MachineBasicBlock *
7003 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7004                                                MachineBasicBlock *BB) const {
7005   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7006   DebugLoc dl = MI->getDebugLoc();
7007   bool isThumb2 = Subtarget->isThumb2();
7008   switch (MI->getOpcode()) {
7009   default: {
7010     MI->dump();
7011     llvm_unreachable("Unexpected instr type to insert");
7012   }
7013   // The Thumb2 pre-indexed stores have the same MI operands, they just
7014   // define them differently in the .td files from the isel patterns, so
7015   // they need pseudos.
7016   case ARM::t2STR_preidx:
7017     MI->setDesc(TII->get(ARM::t2STR_PRE));
7018     return BB;
7019   case ARM::t2STRB_preidx:
7020     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7021     return BB;
7022   case ARM::t2STRH_preidx:
7023     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7024     return BB;
7025
7026   case ARM::STRi_preidx:
7027   case ARM::STRBi_preidx: {
7028     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7029       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7030     // Decode the offset.
7031     unsigned Offset = MI->getOperand(4).getImm();
7032     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7033     Offset = ARM_AM::getAM2Offset(Offset);
7034     if (isSub)
7035       Offset = -Offset;
7036
7037     MachineMemOperand *MMO = *MI->memoperands_begin();
7038     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7039       .addOperand(MI->getOperand(0))  // Rn_wb
7040       .addOperand(MI->getOperand(1))  // Rt
7041       .addOperand(MI->getOperand(2))  // Rn
7042       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7043       .addOperand(MI->getOperand(5))  // pred
7044       .addOperand(MI->getOperand(6))
7045       .addMemOperand(MMO);
7046     MI->eraseFromParent();
7047     return BB;
7048   }
7049   case ARM::STRr_preidx:
7050   case ARM::STRBr_preidx:
7051   case ARM::STRH_preidx: {
7052     unsigned NewOpc;
7053     switch (MI->getOpcode()) {
7054     default: llvm_unreachable("unexpected opcode!");
7055     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7056     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7057     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7058     }
7059     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7060     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7061       MIB.addOperand(MI->getOperand(i));
7062     MI->eraseFromParent();
7063     return BB;
7064   }
7065
7066   case ARM::tMOVCCr_pseudo: {
7067     // To "insert" a SELECT_CC instruction, we actually have to insert the
7068     // diamond control-flow pattern.  The incoming instruction knows the
7069     // destination vreg to set, the condition code register to branch on, the
7070     // true/false values to select between, and a branch opcode to use.
7071     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7072     MachineFunction::iterator It = BB;
7073     ++It;
7074
7075     //  thisMBB:
7076     //  ...
7077     //   TrueVal = ...
7078     //   cmpTY ccX, r1, r2
7079     //   bCC copy1MBB
7080     //   fallthrough --> copy0MBB
7081     MachineBasicBlock *thisMBB  = BB;
7082     MachineFunction *F = BB->getParent();
7083     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7084     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7085     F->insert(It, copy0MBB);
7086     F->insert(It, sinkMBB);
7087
7088     // Transfer the remainder of BB and its successor edges to sinkMBB.
7089     sinkMBB->splice(sinkMBB->begin(), BB,
7090                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7091     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7092
7093     BB->addSuccessor(copy0MBB);
7094     BB->addSuccessor(sinkMBB);
7095
7096     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7097       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7098
7099     //  copy0MBB:
7100     //   %FalseValue = ...
7101     //   # fallthrough to sinkMBB
7102     BB = copy0MBB;
7103
7104     // Update machine-CFG edges
7105     BB->addSuccessor(sinkMBB);
7106
7107     //  sinkMBB:
7108     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7109     //  ...
7110     BB = sinkMBB;
7111     BuildMI(*BB, BB->begin(), dl,
7112             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7113       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7114       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7115
7116     MI->eraseFromParent();   // The pseudo instruction is gone now.
7117     return BB;
7118   }
7119
7120   case ARM::BCCi64:
7121   case ARM::BCCZi64: {
7122     // If there is an unconditional branch to the other successor, remove it.
7123     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7124
7125     // Compare both parts that make up the double comparison separately for
7126     // equality.
7127     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7128
7129     unsigned LHS1 = MI->getOperand(1).getReg();
7130     unsigned LHS2 = MI->getOperand(2).getReg();
7131     if (RHSisZero) {
7132       AddDefaultPred(BuildMI(BB, dl,
7133                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7134                      .addReg(LHS1).addImm(0));
7135       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7136         .addReg(LHS2).addImm(0)
7137         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7138     } else {
7139       unsigned RHS1 = MI->getOperand(3).getReg();
7140       unsigned RHS2 = MI->getOperand(4).getReg();
7141       AddDefaultPred(BuildMI(BB, dl,
7142                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7143                      .addReg(LHS1).addReg(RHS1));
7144       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7145         .addReg(LHS2).addReg(RHS2)
7146         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7147     }
7148
7149     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7150     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7151     if (MI->getOperand(0).getImm() == ARMCC::NE)
7152       std::swap(destMBB, exitMBB);
7153
7154     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7155       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7156     if (isThumb2)
7157       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7158     else
7159       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7160
7161     MI->eraseFromParent();   // The pseudo instruction is gone now.
7162     return BB;
7163   }
7164
7165   case ARM::Int_eh_sjlj_setjmp:
7166   case ARM::Int_eh_sjlj_setjmp_nofp:
7167   case ARM::tInt_eh_sjlj_setjmp:
7168   case ARM::t2Int_eh_sjlj_setjmp:
7169   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7170     EmitSjLjDispatchBlock(MI, BB);
7171     return BB;
7172
7173   case ARM::ABS:
7174   case ARM::t2ABS: {
7175     // To insert an ABS instruction, we have to insert the
7176     // diamond control-flow pattern.  The incoming instruction knows the
7177     // source vreg to test against 0, the destination vreg to set,
7178     // the condition code register to branch on, the
7179     // true/false values to select between, and a branch opcode to use.
7180     // It transforms
7181     //     V1 = ABS V0
7182     // into
7183     //     V2 = MOVS V0
7184     //     BCC                      (branch to SinkBB if V0 >= 0)
7185     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7186     //     SinkBB: V1 = PHI(V2, V3)
7187     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7188     MachineFunction::iterator BBI = BB;
7189     ++BBI;
7190     MachineFunction *Fn = BB->getParent();
7191     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7192     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7193     Fn->insert(BBI, RSBBB);
7194     Fn->insert(BBI, SinkBB);
7195
7196     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7197     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7198     bool isThumb2 = Subtarget->isThumb2();
7199     MachineRegisterInfo &MRI = Fn->getRegInfo();
7200     // In Thumb mode S must not be specified if source register is the SP or
7201     // PC and if destination register is the SP, so restrict register class
7202     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7203       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7204       (const TargetRegisterClass*)&ARM::GPRRegClass);
7205
7206     // Transfer the remainder of BB and its successor edges to sinkMBB.
7207     SinkBB->splice(SinkBB->begin(), BB,
7208                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7209     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7210
7211     BB->addSuccessor(RSBBB);
7212     BB->addSuccessor(SinkBB);
7213
7214     // fall through to SinkMBB
7215     RSBBB->addSuccessor(SinkBB);
7216
7217     // insert a cmp at the end of BB
7218     AddDefaultPred(BuildMI(BB, dl,
7219                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7220                    .addReg(ABSSrcReg).addImm(0));
7221
7222     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7223     BuildMI(BB, dl,
7224       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7225       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7226
7227     // insert rsbri in RSBBB
7228     // Note: BCC and rsbri will be converted into predicated rsbmi
7229     // by if-conversion pass
7230     BuildMI(*RSBBB, RSBBB->begin(), dl,
7231       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7232       .addReg(ABSSrcReg, RegState::Kill)
7233       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7234
7235     // insert PHI in SinkBB,
7236     // reuse ABSDstReg to not change uses of ABS instruction
7237     BuildMI(*SinkBB, SinkBB->begin(), dl,
7238       TII->get(ARM::PHI), ABSDstReg)
7239       .addReg(NewRsbDstReg).addMBB(RSBBB)
7240       .addReg(ABSSrcReg).addMBB(BB);
7241
7242     // remove ABS instruction
7243     MI->eraseFromParent();
7244
7245     // return last added BB
7246     return SinkBB;
7247   }
7248   case ARM::COPY_STRUCT_BYVAL_I32:
7249     ++NumLoopByVals;
7250     return EmitStructByval(MI, BB);
7251   }
7252 }
7253
7254 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7255                                                       SDNode *Node) const {
7256   if (!MI->hasPostISelHook()) {
7257     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7258            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7259     return;
7260   }
7261
7262   const MCInstrDesc *MCID = &MI->getDesc();
7263   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7264   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7265   // operand is still set to noreg. If needed, set the optional operand's
7266   // register to CPSR, and remove the redundant implicit def.
7267   //
7268   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7269
7270   // Rename pseudo opcodes.
7271   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7272   if (NewOpc) {
7273     const ARMBaseInstrInfo *TII =
7274       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7275     MCID = &TII->get(NewOpc);
7276
7277     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7278            "converted opcode should be the same except for cc_out");
7279
7280     MI->setDesc(*MCID);
7281
7282     // Add the optional cc_out operand
7283     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7284   }
7285   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7286
7287   // Any ARM instruction that sets the 's' bit should specify an optional
7288   // "cc_out" operand in the last operand position.
7289   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7290     assert(!NewOpc && "Optional cc_out operand required");
7291     return;
7292   }
7293   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7294   // since we already have an optional CPSR def.
7295   bool definesCPSR = false;
7296   bool deadCPSR = false;
7297   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7298        i != e; ++i) {
7299     const MachineOperand &MO = MI->getOperand(i);
7300     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7301       definesCPSR = true;
7302       if (MO.isDead())
7303         deadCPSR = true;
7304       MI->RemoveOperand(i);
7305       break;
7306     }
7307   }
7308   if (!definesCPSR) {
7309     assert(!NewOpc && "Optional cc_out operand required");
7310     return;
7311   }
7312   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7313   if (deadCPSR) {
7314     assert(!MI->getOperand(ccOutIdx).getReg() &&
7315            "expect uninitialized optional cc_out operand");
7316     return;
7317   }
7318
7319   // If this instruction was defined with an optional CPSR def and its dag node
7320   // had a live implicit CPSR def, then activate the optional CPSR def.
7321   MachineOperand &MO = MI->getOperand(ccOutIdx);
7322   MO.setReg(ARM::CPSR);
7323   MO.setIsDef(true);
7324 }
7325
7326 //===----------------------------------------------------------------------===//
7327 //                           ARM Optimization Hooks
7328 //===----------------------------------------------------------------------===//
7329
7330 // Helper function that checks if N is a null or all ones constant.
7331 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7332   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7333   if (!C)
7334     return false;
7335   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7336 }
7337
7338 // Return true if N is conditionally 0 or all ones.
7339 // Detects these expressions where cc is an i1 value:
7340 //
7341 //   (select cc 0, y)   [AllOnes=0]
7342 //   (select cc y, 0)   [AllOnes=0]
7343 //   (zext cc)          [AllOnes=0]
7344 //   (sext cc)          [AllOnes=0/1]
7345 //   (select cc -1, y)  [AllOnes=1]
7346 //   (select cc y, -1)  [AllOnes=1]
7347 //
7348 // Invert is set when N is the null/all ones constant when CC is false.
7349 // OtherOp is set to the alternative value of N.
7350 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7351                                        SDValue &CC, bool &Invert,
7352                                        SDValue &OtherOp,
7353                                        SelectionDAG &DAG) {
7354   switch (N->getOpcode()) {
7355   default: return false;
7356   case ISD::SELECT: {
7357     CC = N->getOperand(0);
7358     SDValue N1 = N->getOperand(1);
7359     SDValue N2 = N->getOperand(2);
7360     if (isZeroOrAllOnes(N1, AllOnes)) {
7361       Invert = false;
7362       OtherOp = N2;
7363       return true;
7364     }
7365     if (isZeroOrAllOnes(N2, AllOnes)) {
7366       Invert = true;
7367       OtherOp = N1;
7368       return true;
7369     }
7370     return false;
7371   }
7372   case ISD::ZERO_EXTEND:
7373     // (zext cc) can never be the all ones value.
7374     if (AllOnes)
7375       return false;
7376     // Fall through.
7377   case ISD::SIGN_EXTEND: {
7378     EVT VT = N->getValueType(0);
7379     CC = N->getOperand(0);
7380     if (CC.getValueType() != MVT::i1)
7381       return false;
7382     Invert = !AllOnes;
7383     if (AllOnes)
7384       // When looking for an AllOnes constant, N is an sext, and the 'other'
7385       // value is 0.
7386       OtherOp = DAG.getConstant(0, VT);
7387     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7388       // When looking for a 0 constant, N can be zext or sext.
7389       OtherOp = DAG.getConstant(1, VT);
7390     else
7391       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7392     return true;
7393   }
7394   }
7395 }
7396
7397 // Combine a constant select operand into its use:
7398 //
7399 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7400 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7401 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7402 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7403 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7404 //
7405 // The transform is rejected if the select doesn't have a constant operand that
7406 // is null, or all ones when AllOnes is set.
7407 //
7408 // Also recognize sext/zext from i1:
7409 //
7410 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7411 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7412 //
7413 // These transformations eventually create predicated instructions.
7414 //
7415 // @param N       The node to transform.
7416 // @param Slct    The N operand that is a select.
7417 // @param OtherOp The other N operand (x above).
7418 // @param DCI     Context.
7419 // @param AllOnes Require the select constant to be all ones instead of null.
7420 // @returns The new node, or SDValue() on failure.
7421 static
7422 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7423                             TargetLowering::DAGCombinerInfo &DCI,
7424                             bool AllOnes = false) {
7425   SelectionDAG &DAG = DCI.DAG;
7426   EVT VT = N->getValueType(0);
7427   SDValue NonConstantVal;
7428   SDValue CCOp;
7429   bool SwapSelectOps;
7430   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7431                                   NonConstantVal, DAG))
7432     return SDValue();
7433
7434   // Slct is now know to be the desired identity constant when CC is true.
7435   SDValue TrueVal = OtherOp;
7436   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7437                                  OtherOp, NonConstantVal);
7438   // Unless SwapSelectOps says CC should be false.
7439   if (SwapSelectOps)
7440     std::swap(TrueVal, FalseVal);
7441
7442   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7443                      CCOp, TrueVal, FalseVal);
7444 }
7445
7446 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7447 static
7448 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7449                                        TargetLowering::DAGCombinerInfo &DCI) {
7450   SDValue N0 = N->getOperand(0);
7451   SDValue N1 = N->getOperand(1);
7452   if (N0.getNode()->hasOneUse()) {
7453     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7454     if (Result.getNode())
7455       return Result;
7456   }
7457   if (N1.getNode()->hasOneUse()) {
7458     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7459     if (Result.getNode())
7460       return Result;
7461   }
7462   return SDValue();
7463 }
7464
7465 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7466 // (only after legalization).
7467 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7468                                  TargetLowering::DAGCombinerInfo &DCI,
7469                                  const ARMSubtarget *Subtarget) {
7470
7471   // Only perform optimization if after legalize, and if NEON is available. We
7472   // also expected both operands to be BUILD_VECTORs.
7473   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7474       || N0.getOpcode() != ISD::BUILD_VECTOR
7475       || N1.getOpcode() != ISD::BUILD_VECTOR)
7476     return SDValue();
7477
7478   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7479   EVT VT = N->getValueType(0);
7480   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7481     return SDValue();
7482
7483   // Check that the vector operands are of the right form.
7484   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7485   // operands, where N is the size of the formed vector.
7486   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7487   // index such that we have a pair wise add pattern.
7488
7489   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7490   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7491     return SDValue();
7492   SDValue Vec = N0->getOperand(0)->getOperand(0);
7493   SDNode *V = Vec.getNode();
7494   unsigned nextIndex = 0;
7495
7496   // For each operands to the ADD which are BUILD_VECTORs,
7497   // check to see if each of their operands are an EXTRACT_VECTOR with
7498   // the same vector and appropriate index.
7499   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7500     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7501         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7502
7503       SDValue ExtVec0 = N0->getOperand(i);
7504       SDValue ExtVec1 = N1->getOperand(i);
7505
7506       // First operand is the vector, verify its the same.
7507       if (V != ExtVec0->getOperand(0).getNode() ||
7508           V != ExtVec1->getOperand(0).getNode())
7509         return SDValue();
7510
7511       // Second is the constant, verify its correct.
7512       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7513       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7514
7515       // For the constant, we want to see all the even or all the odd.
7516       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7517           || C1->getZExtValue() != nextIndex+1)
7518         return SDValue();
7519
7520       // Increment index.
7521       nextIndex+=2;
7522     } else
7523       return SDValue();
7524   }
7525
7526   // Create VPADDL node.
7527   SelectionDAG &DAG = DCI.DAG;
7528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7529
7530   // Build operand list.
7531   SmallVector<SDValue, 8> Ops;
7532   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7533                                 TLI.getPointerTy()));
7534
7535   // Input is the vector.
7536   Ops.push_back(Vec);
7537
7538   // Get widened type and narrowed type.
7539   MVT widenType;
7540   unsigned numElem = VT.getVectorNumElements();
7541   
7542   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7543   switch (inputLaneType.getSimpleVT().SimpleTy) {
7544     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7545     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7546     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7547     default:
7548       llvm_unreachable("Invalid vector element type for padd optimization.");
7549   }
7550
7551   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7552   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7553   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7554 }
7555
7556 static SDValue findMUL_LOHI(SDValue V) {
7557   if (V->getOpcode() == ISD::UMUL_LOHI ||
7558       V->getOpcode() == ISD::SMUL_LOHI)
7559     return V;
7560   return SDValue();
7561 }
7562
7563 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7564                                      TargetLowering::DAGCombinerInfo &DCI,
7565                                      const ARMSubtarget *Subtarget) {
7566
7567   if (Subtarget->isThumb1Only()) return SDValue();
7568
7569   // Only perform the checks after legalize when the pattern is available.
7570   if (DCI.isBeforeLegalize()) return SDValue();
7571
7572   // Look for multiply add opportunities.
7573   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7574   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7575   // a glue link from the first add to the second add.
7576   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7577   // a S/UMLAL instruction.
7578   //          loAdd   UMUL_LOHI
7579   //            \    / :lo    \ :hi
7580   //             \  /          \          [no multiline comment]
7581   //              ADDC         |  hiAdd
7582   //                 \ :glue  /  /
7583   //                  \      /  /
7584   //                    ADDE
7585   //
7586   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7587   SDValue AddcOp0 = AddcNode->getOperand(0);
7588   SDValue AddcOp1 = AddcNode->getOperand(1);
7589
7590   // Check if the two operands are from the same mul_lohi node.
7591   if (AddcOp0.getNode() == AddcOp1.getNode())
7592     return SDValue();
7593
7594   assert(AddcNode->getNumValues() == 2 &&
7595          AddcNode->getValueType(0) == MVT::i32 &&
7596          "Expect ADDC with two result values. First: i32");
7597
7598   // Check that we have a glued ADDC node.
7599   if (AddcNode->getValueType(1) != MVT::Glue)
7600     return SDValue();
7601
7602   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7603   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7604       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7605       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7606       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7607     return SDValue();
7608
7609   // Look for the glued ADDE.
7610   SDNode* AddeNode = AddcNode->getGluedUser();
7611   if (!AddeNode)
7612     return SDValue();
7613
7614   // Make sure it is really an ADDE.
7615   if (AddeNode->getOpcode() != ISD::ADDE)
7616     return SDValue();
7617
7618   assert(AddeNode->getNumOperands() == 3 &&
7619          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7620          "ADDE node has the wrong inputs");
7621
7622   // Check for the triangle shape.
7623   SDValue AddeOp0 = AddeNode->getOperand(0);
7624   SDValue AddeOp1 = AddeNode->getOperand(1);
7625
7626   // Make sure that the ADDE operands are not coming from the same node.
7627   if (AddeOp0.getNode() == AddeOp1.getNode())
7628     return SDValue();
7629
7630   // Find the MUL_LOHI node walking up ADDE's operands.
7631   bool IsLeftOperandMUL = false;
7632   SDValue MULOp = findMUL_LOHI(AddeOp0);
7633   if (MULOp == SDValue())
7634    MULOp = findMUL_LOHI(AddeOp1);
7635   else
7636     IsLeftOperandMUL = true;
7637   if (MULOp == SDValue())
7638      return SDValue();
7639
7640   // Figure out the right opcode.
7641   unsigned Opc = MULOp->getOpcode();
7642   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7643
7644   // Figure out the high and low input values to the MLAL node.
7645   SDValue* HiMul = &MULOp;
7646   SDValue* HiAdd = nullptr;
7647   SDValue* LoMul = nullptr;
7648   SDValue* LowAdd = nullptr;
7649
7650   if (IsLeftOperandMUL)
7651     HiAdd = &AddeOp1;
7652   else
7653     HiAdd = &AddeOp0;
7654
7655
7656   if (AddcOp0->getOpcode() == Opc) {
7657     LoMul = &AddcOp0;
7658     LowAdd = &AddcOp1;
7659   }
7660   if (AddcOp1->getOpcode() == Opc) {
7661     LoMul = &AddcOp1;
7662     LowAdd = &AddcOp0;
7663   }
7664
7665   if (!LoMul)
7666     return SDValue();
7667
7668   if (LoMul->getNode() != HiMul->getNode())
7669     return SDValue();
7670
7671   // Create the merged node.
7672   SelectionDAG &DAG = DCI.DAG;
7673
7674   // Build operand list.
7675   SmallVector<SDValue, 8> Ops;
7676   Ops.push_back(LoMul->getOperand(0));
7677   Ops.push_back(LoMul->getOperand(1));
7678   Ops.push_back(*LowAdd);
7679   Ops.push_back(*HiAdd);
7680
7681   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7682                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7683
7684   // Replace the ADDs' nodes uses by the MLA node's values.
7685   SDValue HiMLALResult(MLALNode.getNode(), 1);
7686   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7687
7688   SDValue LoMLALResult(MLALNode.getNode(), 0);
7689   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7690
7691   // Return original node to notify the driver to stop replacing.
7692   SDValue resNode(AddcNode, 0);
7693   return resNode;
7694 }
7695
7696 /// PerformADDCCombine - Target-specific dag combine transform from
7697 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7698 static SDValue PerformADDCCombine(SDNode *N,
7699                                  TargetLowering::DAGCombinerInfo &DCI,
7700                                  const ARMSubtarget *Subtarget) {
7701
7702   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7703
7704 }
7705
7706 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7707 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7708 /// called with the default operands, and if that fails, with commuted
7709 /// operands.
7710 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7711                                           TargetLowering::DAGCombinerInfo &DCI,
7712                                           const ARMSubtarget *Subtarget){
7713
7714   // Attempt to create vpaddl for this add.
7715   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7716   if (Result.getNode())
7717     return Result;
7718
7719   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7720   if (N0.getNode()->hasOneUse()) {
7721     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7722     if (Result.getNode()) return Result;
7723   }
7724   return SDValue();
7725 }
7726
7727 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7728 ///
7729 static SDValue PerformADDCombine(SDNode *N,
7730                                  TargetLowering::DAGCombinerInfo &DCI,
7731                                  const ARMSubtarget *Subtarget) {
7732   SDValue N0 = N->getOperand(0);
7733   SDValue N1 = N->getOperand(1);
7734
7735   // First try with the default operand order.
7736   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7737   if (Result.getNode())
7738     return Result;
7739
7740   // If that didn't work, try again with the operands commuted.
7741   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7742 }
7743
7744 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7745 ///
7746 static SDValue PerformSUBCombine(SDNode *N,
7747                                  TargetLowering::DAGCombinerInfo &DCI) {
7748   SDValue N0 = N->getOperand(0);
7749   SDValue N1 = N->getOperand(1);
7750
7751   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7752   if (N1.getNode()->hasOneUse()) {
7753     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7754     if (Result.getNode()) return Result;
7755   }
7756
7757   return SDValue();
7758 }
7759
7760 /// PerformVMULCombine
7761 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7762 /// special multiplier accumulator forwarding.
7763 ///   vmul d3, d0, d2
7764 ///   vmla d3, d1, d2
7765 /// is faster than
7766 ///   vadd d3, d0, d1
7767 ///   vmul d3, d3, d2
7768 //  However, for (A + B) * (A + B),
7769 //    vadd d2, d0, d1
7770 //    vmul d3, d0, d2
7771 //    vmla d3, d1, d2
7772 //  is slower than
7773 //    vadd d2, d0, d1
7774 //    vmul d3, d2, d2
7775 static SDValue PerformVMULCombine(SDNode *N,
7776                                   TargetLowering::DAGCombinerInfo &DCI,
7777                                   const ARMSubtarget *Subtarget) {
7778   if (!Subtarget->hasVMLxForwarding())
7779     return SDValue();
7780
7781   SelectionDAG &DAG = DCI.DAG;
7782   SDValue N0 = N->getOperand(0);
7783   SDValue N1 = N->getOperand(1);
7784   unsigned Opcode = N0.getOpcode();
7785   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7786       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7787     Opcode = N1.getOpcode();
7788     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7789         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7790       return SDValue();
7791     std::swap(N0, N1);
7792   }
7793
7794   if (N0 == N1)
7795     return SDValue();
7796
7797   EVT VT = N->getValueType(0);
7798   SDLoc DL(N);
7799   SDValue N00 = N0->getOperand(0);
7800   SDValue N01 = N0->getOperand(1);
7801   return DAG.getNode(Opcode, DL, VT,
7802                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
7803                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
7804 }
7805
7806 static SDValue PerformMULCombine(SDNode *N,
7807                                  TargetLowering::DAGCombinerInfo &DCI,
7808                                  const ARMSubtarget *Subtarget) {
7809   SelectionDAG &DAG = DCI.DAG;
7810
7811   if (Subtarget->isThumb1Only())
7812     return SDValue();
7813
7814   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7815     return SDValue();
7816
7817   EVT VT = N->getValueType(0);
7818   if (VT.is64BitVector() || VT.is128BitVector())
7819     return PerformVMULCombine(N, DCI, Subtarget);
7820   if (VT != MVT::i32)
7821     return SDValue();
7822
7823   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7824   if (!C)
7825     return SDValue();
7826
7827   int64_t MulAmt = C->getSExtValue();
7828   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
7829
7830   ShiftAmt = ShiftAmt & (32 - 1);
7831   SDValue V = N->getOperand(0);
7832   SDLoc DL(N);
7833
7834   SDValue Res;
7835   MulAmt >>= ShiftAmt;
7836
7837   if (MulAmt >= 0) {
7838     if (isPowerOf2_32(MulAmt - 1)) {
7839       // (mul x, 2^N + 1) => (add (shl x, N), x)
7840       Res = DAG.getNode(ISD::ADD, DL, VT,
7841                         V,
7842                         DAG.getNode(ISD::SHL, DL, VT,
7843                                     V,
7844                                     DAG.getConstant(Log2_32(MulAmt - 1),
7845                                                     MVT::i32)));
7846     } else if (isPowerOf2_32(MulAmt + 1)) {
7847       // (mul x, 2^N - 1) => (sub (shl x, N), x)
7848       Res = DAG.getNode(ISD::SUB, DL, VT,
7849                         DAG.getNode(ISD::SHL, DL, VT,
7850                                     V,
7851                                     DAG.getConstant(Log2_32(MulAmt + 1),
7852                                                     MVT::i32)),
7853                         V);
7854     } else
7855       return SDValue();
7856   } else {
7857     uint64_t MulAmtAbs = -MulAmt;
7858     if (isPowerOf2_32(MulAmtAbs + 1)) {
7859       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7860       Res = DAG.getNode(ISD::SUB, DL, VT,
7861                         V,
7862                         DAG.getNode(ISD::SHL, DL, VT,
7863                                     V,
7864                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
7865                                                     MVT::i32)));
7866     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
7867       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7868       Res = DAG.getNode(ISD::ADD, DL, VT,
7869                         V,
7870                         DAG.getNode(ISD::SHL, DL, VT,
7871                                     V,
7872                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
7873                                                     MVT::i32)));
7874       Res = DAG.getNode(ISD::SUB, DL, VT,
7875                         DAG.getConstant(0, MVT::i32),Res);
7876
7877     } else
7878       return SDValue();
7879   }
7880
7881   if (ShiftAmt != 0)
7882     Res = DAG.getNode(ISD::SHL, DL, VT,
7883                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
7884
7885   // Do not add new nodes to DAG combiner worklist.
7886   DCI.CombineTo(N, Res, false);
7887   return SDValue();
7888 }
7889
7890 static SDValue PerformANDCombine(SDNode *N,
7891                                  TargetLowering::DAGCombinerInfo &DCI,
7892                                  const ARMSubtarget *Subtarget) {
7893
7894   // Attempt to use immediate-form VBIC
7895   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7896   SDLoc dl(N);
7897   EVT VT = N->getValueType(0);
7898   SelectionDAG &DAG = DCI.DAG;
7899
7900   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7901     return SDValue();
7902
7903   APInt SplatBits, SplatUndef;
7904   unsigned SplatBitSize;
7905   bool HasAnyUndefs;
7906   if (BVN &&
7907       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7908     if (SplatBitSize <= 64) {
7909       EVT VbicVT;
7910       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
7911                                       SplatUndef.getZExtValue(), SplatBitSize,
7912                                       DAG, VbicVT, VT.is128BitVector(),
7913                                       OtherModImm);
7914       if (Val.getNode()) {
7915         SDValue Input =
7916           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
7917         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
7918         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
7919       }
7920     }
7921   }
7922
7923   if (!Subtarget->isThumb1Only()) {
7924     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
7925     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
7926     if (Result.getNode())
7927       return Result;
7928   }
7929
7930   return SDValue();
7931 }
7932
7933 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
7934 static SDValue PerformORCombine(SDNode *N,
7935                                 TargetLowering::DAGCombinerInfo &DCI,
7936                                 const ARMSubtarget *Subtarget) {
7937   // Attempt to use immediate-form VORR
7938   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
7939   SDLoc dl(N);
7940   EVT VT = N->getValueType(0);
7941   SelectionDAG &DAG = DCI.DAG;
7942
7943   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7944     return SDValue();
7945
7946   APInt SplatBits, SplatUndef;
7947   unsigned SplatBitSize;
7948   bool HasAnyUndefs;
7949   if (BVN && Subtarget->hasNEON() &&
7950       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7951     if (SplatBitSize <= 64) {
7952       EVT VorrVT;
7953       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
7954                                       SplatUndef.getZExtValue(), SplatBitSize,
7955                                       DAG, VorrVT, VT.is128BitVector(),
7956                                       OtherModImm);
7957       if (Val.getNode()) {
7958         SDValue Input =
7959           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
7960         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
7961         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
7962       }
7963     }
7964   }
7965
7966   if (!Subtarget->isThumb1Only()) {
7967     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
7968     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
7969     if (Result.getNode())
7970       return Result;
7971   }
7972
7973   // The code below optimizes (or (and X, Y), Z).
7974   // The AND operand needs to have a single user to make these optimizations
7975   // profitable.
7976   SDValue N0 = N->getOperand(0);
7977   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
7978     return SDValue();
7979   SDValue N1 = N->getOperand(1);
7980
7981   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
7982   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
7983       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
7984     APInt SplatUndef;
7985     unsigned SplatBitSize;
7986     bool HasAnyUndefs;
7987
7988     APInt SplatBits0, SplatBits1;
7989     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
7990     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
7991     // Ensure that the second operand of both ands are constants
7992     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
7993                                       HasAnyUndefs) && !HasAnyUndefs) {
7994         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
7995                                           HasAnyUndefs) && !HasAnyUndefs) {
7996             // Ensure that the bit width of the constants are the same and that
7997             // the splat arguments are logical inverses as per the pattern we
7998             // are trying to simplify.
7999             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8000                 SplatBits0 == ~SplatBits1) {
8001                 // Canonicalize the vector type to make instruction selection
8002                 // simpler.
8003                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8004                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8005                                              N0->getOperand(1),
8006                                              N0->getOperand(0),
8007                                              N1->getOperand(0));
8008                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8009             }
8010         }
8011     }
8012   }
8013
8014   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8015   // reasonable.
8016
8017   // BFI is only available on V6T2+
8018   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8019     return SDValue();
8020
8021   SDLoc DL(N);
8022   // 1) or (and A, mask), val => ARMbfi A, val, mask
8023   //      iff (val & mask) == val
8024   //
8025   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8026   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8027   //          && mask == ~mask2
8028   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8029   //          && ~mask == mask2
8030   //  (i.e., copy a bitfield value into another bitfield of the same width)
8031
8032   if (VT != MVT::i32)
8033     return SDValue();
8034
8035   SDValue N00 = N0.getOperand(0);
8036
8037   // The value and the mask need to be constants so we can verify this is
8038   // actually a bitfield set. If the mask is 0xffff, we can do better
8039   // via a movt instruction, so don't use BFI in that case.
8040   SDValue MaskOp = N0.getOperand(1);
8041   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8042   if (!MaskC)
8043     return SDValue();
8044   unsigned Mask = MaskC->getZExtValue();
8045   if (Mask == 0xffff)
8046     return SDValue();
8047   SDValue Res;
8048   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8050   if (N1C) {
8051     unsigned Val = N1C->getZExtValue();
8052     if ((Val & ~Mask) != Val)
8053       return SDValue();
8054
8055     if (ARM::isBitFieldInvertedMask(Mask)) {
8056       Val >>= countTrailingZeros(~Mask);
8057
8058       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8059                         DAG.getConstant(Val, MVT::i32),
8060                         DAG.getConstant(Mask, MVT::i32));
8061
8062       // Do not add new nodes to DAG combiner worklist.
8063       DCI.CombineTo(N, Res, false);
8064       return SDValue();
8065     }
8066   } else if (N1.getOpcode() == ISD::AND) {
8067     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8068     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8069     if (!N11C)
8070       return SDValue();
8071     unsigned Mask2 = N11C->getZExtValue();
8072
8073     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8074     // as is to match.
8075     if (ARM::isBitFieldInvertedMask(Mask) &&
8076         (Mask == ~Mask2)) {
8077       // The pack halfword instruction works better for masks that fit it,
8078       // so use that when it's available.
8079       if (Subtarget->hasT2ExtractPack() &&
8080           (Mask == 0xffff || Mask == 0xffff0000))
8081         return SDValue();
8082       // 2a
8083       unsigned amt = countTrailingZeros(Mask2);
8084       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8085                         DAG.getConstant(amt, MVT::i32));
8086       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8087                         DAG.getConstant(Mask, MVT::i32));
8088       // Do not add new nodes to DAG combiner worklist.
8089       DCI.CombineTo(N, Res, false);
8090       return SDValue();
8091     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8092                (~Mask == Mask2)) {
8093       // The pack halfword instruction works better for masks that fit it,
8094       // so use that when it's available.
8095       if (Subtarget->hasT2ExtractPack() &&
8096           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8097         return SDValue();
8098       // 2b
8099       unsigned lsb = countTrailingZeros(Mask);
8100       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8101                         DAG.getConstant(lsb, MVT::i32));
8102       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8103                         DAG.getConstant(Mask2, MVT::i32));
8104       // Do not add new nodes to DAG combiner worklist.
8105       DCI.CombineTo(N, Res, false);
8106       return SDValue();
8107     }
8108   }
8109
8110   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8111       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8112       ARM::isBitFieldInvertedMask(~Mask)) {
8113     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8114     // where lsb(mask) == #shamt and masked bits of B are known zero.
8115     SDValue ShAmt = N00.getOperand(1);
8116     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8117     unsigned LSB = countTrailingZeros(Mask);
8118     if (ShAmtC != LSB)
8119       return SDValue();
8120
8121     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8122                       DAG.getConstant(~Mask, MVT::i32));
8123
8124     // Do not add new nodes to DAG combiner worklist.
8125     DCI.CombineTo(N, Res, false);
8126   }
8127
8128   return SDValue();
8129 }
8130
8131 static SDValue PerformXORCombine(SDNode *N,
8132                                  TargetLowering::DAGCombinerInfo &DCI,
8133                                  const ARMSubtarget *Subtarget) {
8134   EVT VT = N->getValueType(0);
8135   SelectionDAG &DAG = DCI.DAG;
8136
8137   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8138     return SDValue();
8139
8140   if (!Subtarget->isThumb1Only()) {
8141     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8142     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8143     if (Result.getNode())
8144       return Result;
8145   }
8146
8147   return SDValue();
8148 }
8149
8150 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8151 /// the bits being cleared by the AND are not demanded by the BFI.
8152 static SDValue PerformBFICombine(SDNode *N,
8153                                  TargetLowering::DAGCombinerInfo &DCI) {
8154   SDValue N1 = N->getOperand(1);
8155   if (N1.getOpcode() == ISD::AND) {
8156     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8157     if (!N11C)
8158       return SDValue();
8159     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8160     unsigned LSB = countTrailingZeros(~InvMask);
8161     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8162     unsigned Mask = (1 << Width)-1;
8163     unsigned Mask2 = N11C->getZExtValue();
8164     if ((Mask & (~Mask2)) == 0)
8165       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8166                              N->getOperand(0), N1.getOperand(0),
8167                              N->getOperand(2));
8168   }
8169   return SDValue();
8170 }
8171
8172 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8173 /// ARMISD::VMOVRRD.
8174 static SDValue PerformVMOVRRDCombine(SDNode *N,
8175                                      TargetLowering::DAGCombinerInfo &DCI) {
8176   // vmovrrd(vmovdrr x, y) -> x,y
8177   SDValue InDouble = N->getOperand(0);
8178   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8179     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8180
8181   // vmovrrd(load f64) -> (load i32), (load i32)
8182   SDNode *InNode = InDouble.getNode();
8183   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8184       InNode->getValueType(0) == MVT::f64 &&
8185       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8186       !cast<LoadSDNode>(InNode)->isVolatile()) {
8187     // TODO: Should this be done for non-FrameIndex operands?
8188     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8189
8190     SelectionDAG &DAG = DCI.DAG;
8191     SDLoc DL(LD);
8192     SDValue BasePtr = LD->getBasePtr();
8193     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8194                                  LD->getPointerInfo(), LD->isVolatile(),
8195                                  LD->isNonTemporal(), LD->isInvariant(),
8196                                  LD->getAlignment());
8197
8198     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8199                                     DAG.getConstant(4, MVT::i32));
8200     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8201                                  LD->getPointerInfo(), LD->isVolatile(),
8202                                  LD->isNonTemporal(), LD->isInvariant(),
8203                                  std::min(4U, LD->getAlignment() / 2));
8204
8205     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8206     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8207     DCI.RemoveFromWorklist(LD);
8208     DAG.DeleteNode(LD);
8209     return Result;
8210   }
8211
8212   return SDValue();
8213 }
8214
8215 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8216 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8217 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8218   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8219   SDValue Op0 = N->getOperand(0);
8220   SDValue Op1 = N->getOperand(1);
8221   if (Op0.getOpcode() == ISD::BITCAST)
8222     Op0 = Op0.getOperand(0);
8223   if (Op1.getOpcode() == ISD::BITCAST)
8224     Op1 = Op1.getOperand(0);
8225   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8226       Op0.getNode() == Op1.getNode() &&
8227       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8228     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8229                        N->getValueType(0), Op0.getOperand(0));
8230   return SDValue();
8231 }
8232
8233 /// PerformSTORECombine - Target-specific dag combine xforms for
8234 /// ISD::STORE.
8235 static SDValue PerformSTORECombine(SDNode *N,
8236                                    TargetLowering::DAGCombinerInfo &DCI) {
8237   StoreSDNode *St = cast<StoreSDNode>(N);
8238   if (St->isVolatile())
8239     return SDValue();
8240
8241   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8242   // pack all of the elements in one place.  Next, store to memory in fewer
8243   // chunks.
8244   SDValue StVal = St->getValue();
8245   EVT VT = StVal.getValueType();
8246   if (St->isTruncatingStore() && VT.isVector()) {
8247     SelectionDAG &DAG = DCI.DAG;
8248     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8249     EVT StVT = St->getMemoryVT();
8250     unsigned NumElems = VT.getVectorNumElements();
8251     assert(StVT != VT && "Cannot truncate to the same type");
8252     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8253     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8254
8255     // From, To sizes and ElemCount must be pow of two
8256     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8257
8258     // We are going to use the original vector elt for storing.
8259     // Accumulated smaller vector elements must be a multiple of the store size.
8260     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8261
8262     unsigned SizeRatio  = FromEltSz / ToEltSz;
8263     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8264
8265     // Create a type on which we perform the shuffle.
8266     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8267                                      NumElems*SizeRatio);
8268     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8269
8270     SDLoc DL(St);
8271     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8272     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8273     for (unsigned i = 0; i < NumElems; ++i) ShuffleVec[i] = i * SizeRatio;
8274
8275     // Can't shuffle using an illegal type.
8276     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8277
8278     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8279                                 DAG.getUNDEF(WideVec.getValueType()),
8280                                 ShuffleVec.data());
8281     // At this point all of the data is stored at the bottom of the
8282     // register. We now need to save it to mem.
8283
8284     // Find the largest store unit
8285     MVT StoreType = MVT::i8;
8286     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8287          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8288       MVT Tp = (MVT::SimpleValueType)tp;
8289       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8290         StoreType = Tp;
8291     }
8292     // Didn't find a legal store type.
8293     if (!TLI.isTypeLegal(StoreType))
8294       return SDValue();
8295
8296     // Bitcast the original vector into a vector of store-size units
8297     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8298             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8299     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8300     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8301     SmallVector<SDValue, 8> Chains;
8302     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8303                                         TLI.getPointerTy());
8304     SDValue BasePtr = St->getBasePtr();
8305
8306     // Perform one or more big stores into memory.
8307     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8308     for (unsigned I = 0; I < E; I++) {
8309       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8310                                    StoreType, ShuffWide,
8311                                    DAG.getIntPtrConstant(I));
8312       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8313                                 St->getPointerInfo(), St->isVolatile(),
8314                                 St->isNonTemporal(), St->getAlignment());
8315       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8316                             Increment);
8317       Chains.push_back(Ch);
8318     }
8319     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8320   }
8321
8322   if (!ISD::isNormalStore(St))
8323     return SDValue();
8324
8325   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8326   // ARM stores of arguments in the same cache line.
8327   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8328       StVal.getNode()->hasOneUse()) {
8329     SelectionDAG  &DAG = DCI.DAG;
8330     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8331     SDLoc DL(St);
8332     SDValue BasePtr = St->getBasePtr();
8333     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8334                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8335                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8336                                   St->isNonTemporal(), St->getAlignment());
8337
8338     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8339                                     DAG.getConstant(4, MVT::i32));
8340     return DAG.getStore(NewST1.getValue(0), DL,
8341                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8342                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8343                         St->isNonTemporal(),
8344                         std::min(4U, St->getAlignment() / 2));
8345   }
8346
8347   if (StVal.getValueType() != MVT::i64 ||
8348       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8349     return SDValue();
8350
8351   // Bitcast an i64 store extracted from a vector to f64.
8352   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8353   SelectionDAG &DAG = DCI.DAG;
8354   SDLoc dl(StVal);
8355   SDValue IntVec = StVal.getOperand(0);
8356   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8357                                  IntVec.getValueType().getVectorNumElements());
8358   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8359   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8360                                Vec, StVal.getOperand(1));
8361   dl = SDLoc(N);
8362   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8363   // Make the DAGCombiner fold the bitcasts.
8364   DCI.AddToWorklist(Vec.getNode());
8365   DCI.AddToWorklist(ExtElt.getNode());
8366   DCI.AddToWorklist(V.getNode());
8367   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8368                       St->getPointerInfo(), St->isVolatile(),
8369                       St->isNonTemporal(), St->getAlignment(),
8370                       St->getTBAAInfo());
8371 }
8372
8373 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8374 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8375 /// i64 vector to have f64 elements, since the value can then be loaded
8376 /// directly into a VFP register.
8377 static bool hasNormalLoadOperand(SDNode *N) {
8378   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8379   for (unsigned i = 0; i < NumElts; ++i) {
8380     SDNode *Elt = N->getOperand(i).getNode();
8381     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8382       return true;
8383   }
8384   return false;
8385 }
8386
8387 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8388 /// ISD::BUILD_VECTOR.
8389 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8390                                           TargetLowering::DAGCombinerInfo &DCI){
8391   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8392   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8393   // into a pair of GPRs, which is fine when the value is used as a scalar,
8394   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8395   SelectionDAG &DAG = DCI.DAG;
8396   if (N->getNumOperands() == 2) {
8397     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8398     if (RV.getNode())
8399       return RV;
8400   }
8401
8402   // Load i64 elements as f64 values so that type legalization does not split
8403   // them up into i32 values.
8404   EVT VT = N->getValueType(0);
8405   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8406     return SDValue();
8407   SDLoc dl(N);
8408   SmallVector<SDValue, 8> Ops;
8409   unsigned NumElts = VT.getVectorNumElements();
8410   for (unsigned i = 0; i < NumElts; ++i) {
8411     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8412     Ops.push_back(V);
8413     // Make the DAGCombiner fold the bitcast.
8414     DCI.AddToWorklist(V.getNode());
8415   }
8416   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8417   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8418   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8419 }
8420
8421 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8422 static SDValue
8423 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8424   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8425   // At that time, we may have inserted bitcasts from integer to float.
8426   // If these bitcasts have survived DAGCombine, change the lowering of this
8427   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8428   // force to use floating point types.
8429
8430   // Make sure we can change the type of the vector.
8431   // This is possible iff:
8432   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8433   //    1.1. Vector is used only once.
8434   //    1.2. Use is a bit convert to an integer type.
8435   // 2. The size of its operands are 32-bits (64-bits are not legal).
8436   EVT VT = N->getValueType(0);
8437   EVT EltVT = VT.getVectorElementType();
8438
8439   // Check 1.1. and 2.
8440   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8441     return SDValue();
8442
8443   // By construction, the input type must be float.
8444   assert(EltVT == MVT::f32 && "Unexpected type!");
8445
8446   // Check 1.2.
8447   SDNode *Use = *N->use_begin();
8448   if (Use->getOpcode() != ISD::BITCAST ||
8449       Use->getValueType(0).isFloatingPoint())
8450     return SDValue();
8451
8452   // Check profitability.
8453   // Model is, if more than half of the relevant operands are bitcast from
8454   // i32, turn the build_vector into a sequence of insert_vector_elt.
8455   // Relevant operands are everything that is not statically
8456   // (i.e., at compile time) bitcasted.
8457   unsigned NumOfBitCastedElts = 0;
8458   unsigned NumElts = VT.getVectorNumElements();
8459   unsigned NumOfRelevantElts = NumElts;
8460   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8461     SDValue Elt = N->getOperand(Idx);
8462     if (Elt->getOpcode() == ISD::BITCAST) {
8463       // Assume only bit cast to i32 will go away.
8464       if (Elt->getOperand(0).getValueType() == MVT::i32)
8465         ++NumOfBitCastedElts;
8466     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8467       // Constants are statically casted, thus do not count them as
8468       // relevant operands.
8469       --NumOfRelevantElts;
8470   }
8471
8472   // Check if more than half of the elements require a non-free bitcast.
8473   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8474     return SDValue();
8475
8476   SelectionDAG &DAG = DCI.DAG;
8477   // Create the new vector type.
8478   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8479   // Check if the type is legal.
8480   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8481   if (!TLI.isTypeLegal(VecVT))
8482     return SDValue();
8483
8484   // Combine:
8485   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8486   // => BITCAST INSERT_VECTOR_ELT
8487   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8488   //                      (BITCAST EN), N.
8489   SDValue Vec = DAG.getUNDEF(VecVT);
8490   SDLoc dl(N);
8491   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8492     SDValue V = N->getOperand(Idx);
8493     if (V.getOpcode() == ISD::UNDEF)
8494       continue;
8495     if (V.getOpcode() == ISD::BITCAST &&
8496         V->getOperand(0).getValueType() == MVT::i32)
8497       // Fold obvious case.
8498       V = V.getOperand(0);
8499     else {
8500       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8501       // Make the DAGCombiner fold the bitcasts.
8502       DCI.AddToWorklist(V.getNode());
8503     }
8504     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8505     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8506   }
8507   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8508   // Make the DAGCombiner fold the bitcasts.
8509   DCI.AddToWorklist(Vec.getNode());
8510   return Vec;
8511 }
8512
8513 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8514 /// ISD::INSERT_VECTOR_ELT.
8515 static SDValue PerformInsertEltCombine(SDNode *N,
8516                                        TargetLowering::DAGCombinerInfo &DCI) {
8517   // Bitcast an i64 load inserted into a vector to f64.
8518   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8519   EVT VT = N->getValueType(0);
8520   SDNode *Elt = N->getOperand(1).getNode();
8521   if (VT.getVectorElementType() != MVT::i64 ||
8522       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8523     return SDValue();
8524
8525   SelectionDAG &DAG = DCI.DAG;
8526   SDLoc dl(N);
8527   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8528                                  VT.getVectorNumElements());
8529   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8530   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8531   // Make the DAGCombiner fold the bitcasts.
8532   DCI.AddToWorklist(Vec.getNode());
8533   DCI.AddToWorklist(V.getNode());
8534   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8535                                Vec, V, N->getOperand(2));
8536   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8537 }
8538
8539 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8540 /// ISD::VECTOR_SHUFFLE.
8541 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8542   // The LLVM shufflevector instruction does not require the shuffle mask
8543   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8544   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8545   // operands do not match the mask length, they are extended by concatenating
8546   // them with undef vectors.  That is probably the right thing for other
8547   // targets, but for NEON it is better to concatenate two double-register
8548   // size vector operands into a single quad-register size vector.  Do that
8549   // transformation here:
8550   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8551   //   shuffle(concat(v1, v2), undef)
8552   SDValue Op0 = N->getOperand(0);
8553   SDValue Op1 = N->getOperand(1);
8554   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8555       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8556       Op0.getNumOperands() != 2 ||
8557       Op1.getNumOperands() != 2)
8558     return SDValue();
8559   SDValue Concat0Op1 = Op0.getOperand(1);
8560   SDValue Concat1Op1 = Op1.getOperand(1);
8561   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8562       Concat1Op1.getOpcode() != ISD::UNDEF)
8563     return SDValue();
8564   // Skip the transformation if any of the types are illegal.
8565   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8566   EVT VT = N->getValueType(0);
8567   if (!TLI.isTypeLegal(VT) ||
8568       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8569       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8570     return SDValue();
8571
8572   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8573                                   Op0.getOperand(0), Op1.getOperand(0));
8574   // Translate the shuffle mask.
8575   SmallVector<int, 16> NewMask;
8576   unsigned NumElts = VT.getVectorNumElements();
8577   unsigned HalfElts = NumElts/2;
8578   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8579   for (unsigned n = 0; n < NumElts; ++n) {
8580     int MaskElt = SVN->getMaskElt(n);
8581     int NewElt = -1;
8582     if (MaskElt < (int)HalfElts)
8583       NewElt = MaskElt;
8584     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8585       NewElt = HalfElts + MaskElt - NumElts;
8586     NewMask.push_back(NewElt);
8587   }
8588   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8589                               DAG.getUNDEF(VT), NewMask.data());
8590 }
8591
8592 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8593 /// NEON load/store intrinsics to merge base address updates.
8594 static SDValue CombineBaseUpdate(SDNode *N,
8595                                  TargetLowering::DAGCombinerInfo &DCI) {
8596   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8597     return SDValue();
8598
8599   SelectionDAG &DAG = DCI.DAG;
8600   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8601                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8602   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8603   SDValue Addr = N->getOperand(AddrOpIdx);
8604
8605   // Search for a use of the address operand that is an increment.
8606   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8607          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8608     SDNode *User = *UI;
8609     if (User->getOpcode() != ISD::ADD ||
8610         UI.getUse().getResNo() != Addr.getResNo())
8611       continue;
8612
8613     // Check that the add is independent of the load/store.  Otherwise, folding
8614     // it would create a cycle.
8615     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8616       continue;
8617
8618     // Find the new opcode for the updating load/store.
8619     bool isLoad = true;
8620     bool isLaneOp = false;
8621     unsigned NewOpc = 0;
8622     unsigned NumVecs = 0;
8623     if (isIntrinsic) {
8624       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8625       switch (IntNo) {
8626       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8627       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8628         NumVecs = 1; break;
8629       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8630         NumVecs = 2; break;
8631       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8632         NumVecs = 3; break;
8633       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8634         NumVecs = 4; break;
8635       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8636         NumVecs = 2; isLaneOp = true; break;
8637       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8638         NumVecs = 3; isLaneOp = true; break;
8639       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8640         NumVecs = 4; isLaneOp = true; break;
8641       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8642         NumVecs = 1; isLoad = false; break;
8643       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8644         NumVecs = 2; isLoad = false; break;
8645       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8646         NumVecs = 3; isLoad = false; break;
8647       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8648         NumVecs = 4; isLoad = false; break;
8649       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8650         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8651       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8652         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8653       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8654         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8655       }
8656     } else {
8657       isLaneOp = true;
8658       switch (N->getOpcode()) {
8659       default: llvm_unreachable("unexpected opcode for Neon base update");
8660       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8661       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8662       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8663       }
8664     }
8665
8666     // Find the size of memory referenced by the load/store.
8667     EVT VecTy;
8668     if (isLoad)
8669       VecTy = N->getValueType(0);
8670     else
8671       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8672     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8673     if (isLaneOp)
8674       NumBytes /= VecTy.getVectorNumElements();
8675
8676     // If the increment is a constant, it must match the memory ref size.
8677     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8678     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8679       uint64_t IncVal = CInc->getZExtValue();
8680       if (IncVal != NumBytes)
8681         continue;
8682     } else if (NumBytes >= 3 * 16) {
8683       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8684       // separate instructions that make it harder to use a non-constant update.
8685       continue;
8686     }
8687
8688     // Create the new updating load/store node.
8689     EVT Tys[6];
8690     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8691     unsigned n;
8692     for (n = 0; n < NumResultVecs; ++n)
8693       Tys[n] = VecTy;
8694     Tys[n++] = MVT::i32;
8695     Tys[n] = MVT::Other;
8696     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8697     SmallVector<SDValue, 8> Ops;
8698     Ops.push_back(N->getOperand(0)); // incoming chain
8699     Ops.push_back(N->getOperand(AddrOpIdx));
8700     Ops.push_back(Inc);
8701     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8702       Ops.push_back(N->getOperand(i));
8703     }
8704     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8705     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8706                                            Ops, MemInt->getMemoryVT(),
8707                                            MemInt->getMemOperand());
8708
8709     // Update the uses.
8710     std::vector<SDValue> NewResults;
8711     for (unsigned i = 0; i < NumResultVecs; ++i) {
8712       NewResults.push_back(SDValue(UpdN.getNode(), i));
8713     }
8714     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8715     DCI.CombineTo(N, NewResults);
8716     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8717
8718     break;
8719   }
8720   return SDValue();
8721 }
8722
8723 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8724 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8725 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8726 /// return true.
8727 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8728   SelectionDAG &DAG = DCI.DAG;
8729   EVT VT = N->getValueType(0);
8730   // vldN-dup instructions only support 64-bit vectors for N > 1.
8731   if (!VT.is64BitVector())
8732     return false;
8733
8734   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8735   SDNode *VLD = N->getOperand(0).getNode();
8736   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8737     return false;
8738   unsigned NumVecs = 0;
8739   unsigned NewOpc = 0;
8740   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8741   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8742     NumVecs = 2;
8743     NewOpc = ARMISD::VLD2DUP;
8744   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8745     NumVecs = 3;
8746     NewOpc = ARMISD::VLD3DUP;
8747   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8748     NumVecs = 4;
8749     NewOpc = ARMISD::VLD4DUP;
8750   } else {
8751     return false;
8752   }
8753
8754   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8755   // numbers match the load.
8756   unsigned VLDLaneNo =
8757     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8758   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8759        UI != UE; ++UI) {
8760     // Ignore uses of the chain result.
8761     if (UI.getUse().getResNo() == NumVecs)
8762       continue;
8763     SDNode *User = *UI;
8764     if (User->getOpcode() != ARMISD::VDUPLANE ||
8765         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8766       return false;
8767   }
8768
8769   // Create the vldN-dup node.
8770   EVT Tys[5];
8771   unsigned n;
8772   for (n = 0; n < NumVecs; ++n)
8773     Tys[n] = VT;
8774   Tys[n] = MVT::Other;
8775   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8776   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8777   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8778   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8779                                            Ops, VLDMemInt->getMemoryVT(),
8780                                            VLDMemInt->getMemOperand());
8781
8782   // Update the uses.
8783   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8784        UI != UE; ++UI) {
8785     unsigned ResNo = UI.getUse().getResNo();
8786     // Ignore uses of the chain result.
8787     if (ResNo == NumVecs)
8788       continue;
8789     SDNode *User = *UI;
8790     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8791   }
8792
8793   // Now the vldN-lane intrinsic is dead except for its chain result.
8794   // Update uses of the chain.
8795   std::vector<SDValue> VLDDupResults;
8796   for (unsigned n = 0; n < NumVecs; ++n)
8797     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
8798   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
8799   DCI.CombineTo(VLD, VLDDupResults);
8800
8801   return true;
8802 }
8803
8804 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
8805 /// ARMISD::VDUPLANE.
8806 static SDValue PerformVDUPLANECombine(SDNode *N,
8807                                       TargetLowering::DAGCombinerInfo &DCI) {
8808   SDValue Op = N->getOperand(0);
8809
8810   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
8811   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
8812   if (CombineVLDDUP(N, DCI))
8813     return SDValue(N, 0);
8814
8815   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
8816   // redundant.  Ignore bit_converts for now; element sizes are checked below.
8817   while (Op.getOpcode() == ISD::BITCAST)
8818     Op = Op.getOperand(0);
8819   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
8820     return SDValue();
8821
8822   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
8823   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
8824   // The canonical VMOV for a zero vector uses a 32-bit element size.
8825   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8826   unsigned EltBits;
8827   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
8828     EltSize = 8;
8829   EVT VT = N->getValueType(0);
8830   if (EltSize > VT.getVectorElementType().getSizeInBits())
8831     return SDValue();
8832
8833   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
8834 }
8835
8836 // isConstVecPow2 - Return true if each vector element is a power of 2, all
8837 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
8838 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
8839 {
8840   integerPart cN;
8841   integerPart c0 = 0;
8842   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
8843        I != E; I++) {
8844     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
8845     if (!C)
8846       return false;
8847
8848     bool isExact;
8849     APFloat APF = C->getValueAPF();
8850     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
8851         != APFloat::opOK || !isExact)
8852       return false;
8853
8854     c0 = (I == 0) ? cN : c0;
8855     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
8856       return false;
8857   }
8858   C = c0;
8859   return true;
8860 }
8861
8862 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
8863 /// can replace combinations of VMUL and VCVT (floating-point to integer)
8864 /// when the VMUL has a constant operand that is a power of 2.
8865 ///
8866 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8867 ///  vmul.f32        d16, d17, d16
8868 ///  vcvt.s32.f32    d16, d16
8869 /// becomes:
8870 ///  vcvt.s32.f32    d16, d16, #3
8871 static SDValue PerformVCVTCombine(SDNode *N,
8872                                   TargetLowering::DAGCombinerInfo &DCI,
8873                                   const ARMSubtarget *Subtarget) {
8874   SelectionDAG &DAG = DCI.DAG;
8875   SDValue Op = N->getOperand(0);
8876
8877   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
8878       Op.getOpcode() != ISD::FMUL)
8879     return SDValue();
8880
8881   uint64_t C;
8882   SDValue N0 = Op->getOperand(0);
8883   SDValue ConstVec = Op->getOperand(1);
8884   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
8885
8886   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8887       !isConstVecPow2(ConstVec, isSigned, C))
8888     return SDValue();
8889
8890   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8891   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8892   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8893     // These instructions only exist converting from f32 to i32. We can handle
8894     // smaller integers by generating an extra truncate, but larger ones would
8895     // be lossy.
8896     return SDValue();
8897   }
8898
8899   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
8900     Intrinsic::arm_neon_vcvtfp2fxu;
8901   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8902   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8903                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8904                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
8905                                  DAG.getConstant(Log2_64(C), MVT::i32));
8906
8907   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8908     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
8909
8910   return FixConv;
8911 }
8912
8913 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
8914 /// can replace combinations of VCVT (integer to floating-point) and VDIV
8915 /// when the VDIV has a constant operand that is a power of 2.
8916 ///
8917 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
8918 ///  vcvt.f32.s32    d16, d16
8919 ///  vdiv.f32        d16, d17, d16
8920 /// becomes:
8921 ///  vcvt.f32.s32    d16, d16, #3
8922 static SDValue PerformVDIVCombine(SDNode *N,
8923                                   TargetLowering::DAGCombinerInfo &DCI,
8924                                   const ARMSubtarget *Subtarget) {
8925   SelectionDAG &DAG = DCI.DAG;
8926   SDValue Op = N->getOperand(0);
8927   unsigned OpOpcode = Op.getNode()->getOpcode();
8928
8929   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
8930       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
8931     return SDValue();
8932
8933   uint64_t C;
8934   SDValue ConstVec = N->getOperand(1);
8935   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
8936
8937   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
8938       !isConstVecPow2(ConstVec, isSigned, C))
8939     return SDValue();
8940
8941   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8942   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8943   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
8944     // These instructions only exist converting from i32 to f32. We can handle
8945     // smaller integers by generating an extra extend, but larger ones would
8946     // be lossy.
8947     return SDValue();
8948   }
8949
8950   SDValue ConvInput = Op.getOperand(0);
8951   unsigned NumLanes = Op.getValueType().getVectorNumElements();
8952   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
8953     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
8954                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
8955                             ConvInput);
8956
8957   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
8958     Intrinsic::arm_neon_vcvtfxu2fp;
8959   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
8960                      Op.getValueType(),
8961                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
8962                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
8963 }
8964
8965 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
8966 /// operand of a vector shift operation, where all the elements of the
8967 /// build_vector must have the same constant integer value.
8968 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
8969   // Ignore bit_converts.
8970   while (Op.getOpcode() == ISD::BITCAST)
8971     Op = Op.getOperand(0);
8972   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8973   APInt SplatBits, SplatUndef;
8974   unsigned SplatBitSize;
8975   bool HasAnyUndefs;
8976   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
8977                                       HasAnyUndefs, ElementBits) ||
8978       SplatBitSize > ElementBits)
8979     return false;
8980   Cnt = SplatBits.getSExtValue();
8981   return true;
8982 }
8983
8984 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
8985 /// operand of a vector shift left operation.  That value must be in the range:
8986 ///   0 <= Value < ElementBits for a left shift; or
8987 ///   0 <= Value <= ElementBits for a long left shift.
8988 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
8989   assert(VT.isVector() && "vector shift count is not a vector type");
8990   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
8991   if (! getVShiftImm(Op, ElementBits, Cnt))
8992     return false;
8993   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
8994 }
8995
8996 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
8997 /// operand of a vector shift right operation.  For a shift opcode, the value
8998 /// is positive, but for an intrinsic the value count must be negative. The
8999 /// absolute value must be in the range:
9000 ///   1 <= |Value| <= ElementBits for a right shift; or
9001 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9002 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9003                          int64_t &Cnt) {
9004   assert(VT.isVector() && "vector shift count is not a vector type");
9005   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9006   if (! getVShiftImm(Op, ElementBits, Cnt))
9007     return false;
9008   if (isIntrinsic)
9009     Cnt = -Cnt;
9010   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9011 }
9012
9013 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9014 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9015   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9016   switch (IntNo) {
9017   default:
9018     // Don't do anything for most intrinsics.
9019     break;
9020
9021   // Vector shifts: check for immediate versions and lower them.
9022   // Note: This is done during DAG combining instead of DAG legalizing because
9023   // the build_vectors for 64-bit vector element shift counts are generally
9024   // not legal, and it is hard to see their values after they get legalized to
9025   // loads from a constant pool.
9026   case Intrinsic::arm_neon_vshifts:
9027   case Intrinsic::arm_neon_vshiftu:
9028   case Intrinsic::arm_neon_vrshifts:
9029   case Intrinsic::arm_neon_vrshiftu:
9030   case Intrinsic::arm_neon_vrshiftn:
9031   case Intrinsic::arm_neon_vqshifts:
9032   case Intrinsic::arm_neon_vqshiftu:
9033   case Intrinsic::arm_neon_vqshiftsu:
9034   case Intrinsic::arm_neon_vqshiftns:
9035   case Intrinsic::arm_neon_vqshiftnu:
9036   case Intrinsic::arm_neon_vqshiftnsu:
9037   case Intrinsic::arm_neon_vqrshiftns:
9038   case Intrinsic::arm_neon_vqrshiftnu:
9039   case Intrinsic::arm_neon_vqrshiftnsu: {
9040     EVT VT = N->getOperand(1).getValueType();
9041     int64_t Cnt;
9042     unsigned VShiftOpc = 0;
9043
9044     switch (IntNo) {
9045     case Intrinsic::arm_neon_vshifts:
9046     case Intrinsic::arm_neon_vshiftu:
9047       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9048         VShiftOpc = ARMISD::VSHL;
9049         break;
9050       }
9051       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9052         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9053                      ARMISD::VSHRs : ARMISD::VSHRu);
9054         break;
9055       }
9056       return SDValue();
9057
9058     case Intrinsic::arm_neon_vrshifts:
9059     case Intrinsic::arm_neon_vrshiftu:
9060       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9061         break;
9062       return SDValue();
9063
9064     case Intrinsic::arm_neon_vqshifts:
9065     case Intrinsic::arm_neon_vqshiftu:
9066       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9067         break;
9068       return SDValue();
9069
9070     case Intrinsic::arm_neon_vqshiftsu:
9071       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9072         break;
9073       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9074
9075     case Intrinsic::arm_neon_vrshiftn:
9076     case Intrinsic::arm_neon_vqshiftns:
9077     case Intrinsic::arm_neon_vqshiftnu:
9078     case Intrinsic::arm_neon_vqshiftnsu:
9079     case Intrinsic::arm_neon_vqrshiftns:
9080     case Intrinsic::arm_neon_vqrshiftnu:
9081     case Intrinsic::arm_neon_vqrshiftnsu:
9082       // Narrowing shifts require an immediate right shift.
9083       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9084         break;
9085       llvm_unreachable("invalid shift count for narrowing vector shift "
9086                        "intrinsic");
9087
9088     default:
9089       llvm_unreachable("unhandled vector shift");
9090     }
9091
9092     switch (IntNo) {
9093     case Intrinsic::arm_neon_vshifts:
9094     case Intrinsic::arm_neon_vshiftu:
9095       // Opcode already set above.
9096       break;
9097     case Intrinsic::arm_neon_vrshifts:
9098       VShiftOpc = ARMISD::VRSHRs; break;
9099     case Intrinsic::arm_neon_vrshiftu:
9100       VShiftOpc = ARMISD::VRSHRu; break;
9101     case Intrinsic::arm_neon_vrshiftn:
9102       VShiftOpc = ARMISD::VRSHRN; break;
9103     case Intrinsic::arm_neon_vqshifts:
9104       VShiftOpc = ARMISD::VQSHLs; break;
9105     case Intrinsic::arm_neon_vqshiftu:
9106       VShiftOpc = ARMISD::VQSHLu; break;
9107     case Intrinsic::arm_neon_vqshiftsu:
9108       VShiftOpc = ARMISD::VQSHLsu; break;
9109     case Intrinsic::arm_neon_vqshiftns:
9110       VShiftOpc = ARMISD::VQSHRNs; break;
9111     case Intrinsic::arm_neon_vqshiftnu:
9112       VShiftOpc = ARMISD::VQSHRNu; break;
9113     case Intrinsic::arm_neon_vqshiftnsu:
9114       VShiftOpc = ARMISD::VQSHRNsu; break;
9115     case Intrinsic::arm_neon_vqrshiftns:
9116       VShiftOpc = ARMISD::VQRSHRNs; break;
9117     case Intrinsic::arm_neon_vqrshiftnu:
9118       VShiftOpc = ARMISD::VQRSHRNu; break;
9119     case Intrinsic::arm_neon_vqrshiftnsu:
9120       VShiftOpc = ARMISD::VQRSHRNsu; break;
9121     }
9122
9123     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9124                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9125   }
9126
9127   case Intrinsic::arm_neon_vshiftins: {
9128     EVT VT = N->getOperand(1).getValueType();
9129     int64_t Cnt;
9130     unsigned VShiftOpc = 0;
9131
9132     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9133       VShiftOpc = ARMISD::VSLI;
9134     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9135       VShiftOpc = ARMISD::VSRI;
9136     else {
9137       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9138     }
9139
9140     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9141                        N->getOperand(1), N->getOperand(2),
9142                        DAG.getConstant(Cnt, MVT::i32));
9143   }
9144
9145   case Intrinsic::arm_neon_vqrshifts:
9146   case Intrinsic::arm_neon_vqrshiftu:
9147     // No immediate versions of these to check for.
9148     break;
9149   }
9150
9151   return SDValue();
9152 }
9153
9154 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9155 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9156 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9157 /// vector element shift counts are generally not legal, and it is hard to see
9158 /// their values after they get legalized to loads from a constant pool.
9159 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9160                                    const ARMSubtarget *ST) {
9161   EVT VT = N->getValueType(0);
9162   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9163     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9164     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9165     SDValue N1 = N->getOperand(1);
9166     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9167       SDValue N0 = N->getOperand(0);
9168       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9169           DAG.MaskedValueIsZero(N0.getOperand(0),
9170                                 APInt::getHighBitsSet(32, 16)))
9171         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9172     }
9173   }
9174
9175   // Nothing to be done for scalar shifts.
9176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9177   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9178     return SDValue();
9179
9180   assert(ST->hasNEON() && "unexpected vector shift");
9181   int64_t Cnt;
9182
9183   switch (N->getOpcode()) {
9184   default: llvm_unreachable("unexpected shift opcode");
9185
9186   case ISD::SHL:
9187     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9188       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9189                          DAG.getConstant(Cnt, MVT::i32));
9190     break;
9191
9192   case ISD::SRA:
9193   case ISD::SRL:
9194     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9195       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9196                             ARMISD::VSHRs : ARMISD::VSHRu);
9197       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9198                          DAG.getConstant(Cnt, MVT::i32));
9199     }
9200   }
9201   return SDValue();
9202 }
9203
9204 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9205 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9206 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9207                                     const ARMSubtarget *ST) {
9208   SDValue N0 = N->getOperand(0);
9209
9210   // Check for sign- and zero-extensions of vector extract operations of 8-
9211   // and 16-bit vector elements.  NEON supports these directly.  They are
9212   // handled during DAG combining because type legalization will promote them
9213   // to 32-bit types and it is messy to recognize the operations after that.
9214   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9215     SDValue Vec = N0.getOperand(0);
9216     SDValue Lane = N0.getOperand(1);
9217     EVT VT = N->getValueType(0);
9218     EVT EltVT = N0.getValueType();
9219     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9220
9221     if (VT == MVT::i32 &&
9222         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9223         TLI.isTypeLegal(Vec.getValueType()) &&
9224         isa<ConstantSDNode>(Lane)) {
9225
9226       unsigned Opc = 0;
9227       switch (N->getOpcode()) {
9228       default: llvm_unreachable("unexpected opcode");
9229       case ISD::SIGN_EXTEND:
9230         Opc = ARMISD::VGETLANEs;
9231         break;
9232       case ISD::ZERO_EXTEND:
9233       case ISD::ANY_EXTEND:
9234         Opc = ARMISD::VGETLANEu;
9235         break;
9236       }
9237       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9238     }
9239   }
9240
9241   return SDValue();
9242 }
9243
9244 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9245 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9246 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9247                                        const ARMSubtarget *ST) {
9248   // If the target supports NEON, try to use vmax/vmin instructions for f32
9249   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9250   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9251   // a NaN; only do the transformation when it matches that behavior.
9252
9253   // For now only do this when using NEON for FP operations; if using VFP, it
9254   // is not obvious that the benefit outweighs the cost of switching to the
9255   // NEON pipeline.
9256   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9257       N->getValueType(0) != MVT::f32)
9258     return SDValue();
9259
9260   SDValue CondLHS = N->getOperand(0);
9261   SDValue CondRHS = N->getOperand(1);
9262   SDValue LHS = N->getOperand(2);
9263   SDValue RHS = N->getOperand(3);
9264   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9265
9266   unsigned Opcode = 0;
9267   bool IsReversed;
9268   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9269     IsReversed = false; // x CC y ? x : y
9270   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9271     IsReversed = true ; // x CC y ? y : x
9272   } else {
9273     return SDValue();
9274   }
9275
9276   bool IsUnordered;
9277   switch (CC) {
9278   default: break;
9279   case ISD::SETOLT:
9280   case ISD::SETOLE:
9281   case ISD::SETLT:
9282   case ISD::SETLE:
9283   case ISD::SETULT:
9284   case ISD::SETULE:
9285     // If LHS is NaN, an ordered comparison will be false and the result will
9286     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9287     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9288     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9289     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9290       break;
9291     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9292     // will return -0, so vmin can only be used for unsafe math or if one of
9293     // the operands is known to be nonzero.
9294     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9295         !DAG.getTarget().Options.UnsafeFPMath &&
9296         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9297       break;
9298     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9299     break;
9300
9301   case ISD::SETOGT:
9302   case ISD::SETOGE:
9303   case ISD::SETGT:
9304   case ISD::SETGE:
9305   case ISD::SETUGT:
9306   case ISD::SETUGE:
9307     // If LHS is NaN, an ordered comparison will be false and the result will
9308     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9309     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9310     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9311     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9312       break;
9313     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9314     // will return +0, so vmax can only be used for unsafe math or if one of
9315     // the operands is known to be nonzero.
9316     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9317         !DAG.getTarget().Options.UnsafeFPMath &&
9318         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9319       break;
9320     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9321     break;
9322   }
9323
9324   if (!Opcode)
9325     return SDValue();
9326   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9327 }
9328
9329 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9330 SDValue
9331 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9332   SDValue Cmp = N->getOperand(4);
9333   if (Cmp.getOpcode() != ARMISD::CMPZ)
9334     // Only looking at EQ and NE cases.
9335     return SDValue();
9336
9337   EVT VT = N->getValueType(0);
9338   SDLoc dl(N);
9339   SDValue LHS = Cmp.getOperand(0);
9340   SDValue RHS = Cmp.getOperand(1);
9341   SDValue FalseVal = N->getOperand(0);
9342   SDValue TrueVal = N->getOperand(1);
9343   SDValue ARMcc = N->getOperand(2);
9344   ARMCC::CondCodes CC =
9345     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9346
9347   // Simplify
9348   //   mov     r1, r0
9349   //   cmp     r1, x
9350   //   mov     r0, y
9351   //   moveq   r0, x
9352   // to
9353   //   cmp     r0, x
9354   //   movne   r0, y
9355   //
9356   //   mov     r1, r0
9357   //   cmp     r1, x
9358   //   mov     r0, x
9359   //   movne   r0, y
9360   // to
9361   //   cmp     r0, x
9362   //   movne   r0, y
9363   /// FIXME: Turn this into a target neutral optimization?
9364   SDValue Res;
9365   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9366     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9367                       N->getOperand(3), Cmp);
9368   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9369     SDValue ARMcc;
9370     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9371     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9372                       N->getOperand(3), NewCmp);
9373   }
9374
9375   if (Res.getNode()) {
9376     APInt KnownZero, KnownOne;
9377     DAG.ComputeMaskedBits(SDValue(N,0), KnownZero, KnownOne);
9378     // Capture demanded bits information that would be otherwise lost.
9379     if (KnownZero == 0xfffffffe)
9380       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9381                         DAG.getValueType(MVT::i1));
9382     else if (KnownZero == 0xffffff00)
9383       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9384                         DAG.getValueType(MVT::i8));
9385     else if (KnownZero == 0xffff0000)
9386       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9387                         DAG.getValueType(MVT::i16));
9388   }
9389
9390   return Res;
9391 }
9392
9393 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9394                                              DAGCombinerInfo &DCI) const {
9395   switch (N->getOpcode()) {
9396   default: break;
9397   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9398   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9399   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9400   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9401   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9402   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9403   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9404   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9405   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9406   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9407   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9408   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9409   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9410   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9411   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9412   case ISD::FP_TO_SINT:
9413   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9414   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9415   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9416   case ISD::SHL:
9417   case ISD::SRA:
9418   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9419   case ISD::SIGN_EXTEND:
9420   case ISD::ZERO_EXTEND:
9421   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9422   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9423   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9424   case ARMISD::VLD2DUP:
9425   case ARMISD::VLD3DUP:
9426   case ARMISD::VLD4DUP:
9427     return CombineBaseUpdate(N, DCI);
9428   case ARMISD::BUILD_VECTOR:
9429     return PerformARMBUILD_VECTORCombine(N, DCI);
9430   case ISD::INTRINSIC_VOID:
9431   case ISD::INTRINSIC_W_CHAIN:
9432     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9433     case Intrinsic::arm_neon_vld1:
9434     case Intrinsic::arm_neon_vld2:
9435     case Intrinsic::arm_neon_vld3:
9436     case Intrinsic::arm_neon_vld4:
9437     case Intrinsic::arm_neon_vld2lane:
9438     case Intrinsic::arm_neon_vld3lane:
9439     case Intrinsic::arm_neon_vld4lane:
9440     case Intrinsic::arm_neon_vst1:
9441     case Intrinsic::arm_neon_vst2:
9442     case Intrinsic::arm_neon_vst3:
9443     case Intrinsic::arm_neon_vst4:
9444     case Intrinsic::arm_neon_vst2lane:
9445     case Intrinsic::arm_neon_vst3lane:
9446     case Intrinsic::arm_neon_vst4lane:
9447       return CombineBaseUpdate(N, DCI);
9448     default: break;
9449     }
9450     break;
9451   }
9452   return SDValue();
9453 }
9454
9455 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9456                                                           EVT VT) const {
9457   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9458 }
9459
9460 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9461                                                       bool *Fast) const {
9462   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9463   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9464
9465   switch (VT.getSimpleVT().SimpleTy) {
9466   default:
9467     return false;
9468   case MVT::i8:
9469   case MVT::i16:
9470   case MVT::i32: {
9471     // Unaligned access can use (for example) LRDB, LRDH, LDR
9472     if (AllowsUnaligned) {
9473       if (Fast)
9474         *Fast = Subtarget->hasV7Ops();
9475       return true;
9476     }
9477     return false;
9478   }
9479   case MVT::f64:
9480   case MVT::v2f64: {
9481     // For any little-endian targets with neon, we can support unaligned ld/st
9482     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9483     // A big-endian target may also explicitly support unaligned accesses
9484     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9485       if (Fast)
9486         *Fast = true;
9487       return true;
9488     }
9489     return false;
9490   }
9491   }
9492 }
9493
9494 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9495                        unsigned AlignCheck) {
9496   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9497           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9498 }
9499
9500 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9501                                            unsigned DstAlign, unsigned SrcAlign,
9502                                            bool IsMemset, bool ZeroMemset,
9503                                            bool MemcpyStrSrc,
9504                                            MachineFunction &MF) const {
9505   const Function *F = MF.getFunction();
9506
9507   // See if we can use NEON instructions for this...
9508   if ((!IsMemset || ZeroMemset) &&
9509       Subtarget->hasNEON() &&
9510       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9511                                        Attribute::NoImplicitFloat)) {
9512     bool Fast;
9513     if (Size >= 16 &&
9514         (memOpAlign(SrcAlign, DstAlign, 16) ||
9515          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9516       return MVT::v2f64;
9517     } else if (Size >= 8 &&
9518                (memOpAlign(SrcAlign, DstAlign, 8) ||
9519                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9520       return MVT::f64;
9521     }
9522   }
9523
9524   // Lowering to i32/i16 if the size permits.
9525   if (Size >= 4)
9526     return MVT::i32;
9527   else if (Size >= 2)
9528     return MVT::i16;
9529
9530   // Let the target-independent logic figure it out.
9531   return MVT::Other;
9532 }
9533
9534 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9535   if (Val.getOpcode() != ISD::LOAD)
9536     return false;
9537
9538   EVT VT1 = Val.getValueType();
9539   if (!VT1.isSimple() || !VT1.isInteger() ||
9540       !VT2.isSimple() || !VT2.isInteger())
9541     return false;
9542
9543   switch (VT1.getSimpleVT().SimpleTy) {
9544   default: break;
9545   case MVT::i1:
9546   case MVT::i8:
9547   case MVT::i16:
9548     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9549     return true;
9550   }
9551
9552   return false;
9553 }
9554
9555 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9556   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9557     return false;
9558
9559   if (!isTypeLegal(EVT::getEVT(Ty1)))
9560     return false;
9561
9562   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9563
9564   // Assuming the caller doesn't have a zeroext or signext return parameter,
9565   // truncation all the way down to i1 is valid.
9566   return true;
9567 }
9568
9569
9570 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9571   if (V < 0)
9572     return false;
9573
9574   unsigned Scale = 1;
9575   switch (VT.getSimpleVT().SimpleTy) {
9576   default: return false;
9577   case MVT::i1:
9578   case MVT::i8:
9579     // Scale == 1;
9580     break;
9581   case MVT::i16:
9582     // Scale == 2;
9583     Scale = 2;
9584     break;
9585   case MVT::i32:
9586     // Scale == 4;
9587     Scale = 4;
9588     break;
9589   }
9590
9591   if ((V & (Scale - 1)) != 0)
9592     return false;
9593   V /= Scale;
9594   return V == (V & ((1LL << 5) - 1));
9595 }
9596
9597 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9598                                       const ARMSubtarget *Subtarget) {
9599   bool isNeg = false;
9600   if (V < 0) {
9601     isNeg = true;
9602     V = - V;
9603   }
9604
9605   switch (VT.getSimpleVT().SimpleTy) {
9606   default: return false;
9607   case MVT::i1:
9608   case MVT::i8:
9609   case MVT::i16:
9610   case MVT::i32:
9611     // + imm12 or - imm8
9612     if (isNeg)
9613       return V == (V & ((1LL << 8) - 1));
9614     return V == (V & ((1LL << 12) - 1));
9615   case MVT::f32:
9616   case MVT::f64:
9617     // Same as ARM mode. FIXME: NEON?
9618     if (!Subtarget->hasVFP2())
9619       return false;
9620     if ((V & 3) != 0)
9621       return false;
9622     V >>= 2;
9623     return V == (V & ((1LL << 8) - 1));
9624   }
9625 }
9626
9627 /// isLegalAddressImmediate - Return true if the integer value can be used
9628 /// as the offset of the target addressing mode for load / store of the
9629 /// given type.
9630 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9631                                     const ARMSubtarget *Subtarget) {
9632   if (V == 0)
9633     return true;
9634
9635   if (!VT.isSimple())
9636     return false;
9637
9638   if (Subtarget->isThumb1Only())
9639     return isLegalT1AddressImmediate(V, VT);
9640   else if (Subtarget->isThumb2())
9641     return isLegalT2AddressImmediate(V, VT, Subtarget);
9642
9643   // ARM mode.
9644   if (V < 0)
9645     V = - V;
9646   switch (VT.getSimpleVT().SimpleTy) {
9647   default: return false;
9648   case MVT::i1:
9649   case MVT::i8:
9650   case MVT::i32:
9651     // +- imm12
9652     return V == (V & ((1LL << 12) - 1));
9653   case MVT::i16:
9654     // +- imm8
9655     return V == (V & ((1LL << 8) - 1));
9656   case MVT::f32:
9657   case MVT::f64:
9658     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9659       return false;
9660     if ((V & 3) != 0)
9661       return false;
9662     V >>= 2;
9663     return V == (V & ((1LL << 8) - 1));
9664   }
9665 }
9666
9667 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9668                                                       EVT VT) const {
9669   int Scale = AM.Scale;
9670   if (Scale < 0)
9671     return false;
9672
9673   switch (VT.getSimpleVT().SimpleTy) {
9674   default: return false;
9675   case MVT::i1:
9676   case MVT::i8:
9677   case MVT::i16:
9678   case MVT::i32:
9679     if (Scale == 1)
9680       return true;
9681     // r + r << imm
9682     Scale = Scale & ~1;
9683     return Scale == 2 || Scale == 4 || Scale == 8;
9684   case MVT::i64:
9685     // r + r
9686     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9687       return true;
9688     return false;
9689   case MVT::isVoid:
9690     // Note, we allow "void" uses (basically, uses that aren't loads or
9691     // stores), because arm allows folding a scale into many arithmetic
9692     // operations.  This should be made more precise and revisited later.
9693
9694     // Allow r << imm, but the imm has to be a multiple of two.
9695     if (Scale & 1) return false;
9696     return isPowerOf2_32(Scale);
9697   }
9698 }
9699
9700 /// isLegalAddressingMode - Return true if the addressing mode represented
9701 /// by AM is legal for this target, for a load/store of the specified type.
9702 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9703                                               Type *Ty) const {
9704   EVT VT = getValueType(Ty, true);
9705   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9706     return false;
9707
9708   // Can never fold addr of global into load/store.
9709   if (AM.BaseGV)
9710     return false;
9711
9712   switch (AM.Scale) {
9713   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9714     break;
9715   case 1:
9716     if (Subtarget->isThumb1Only())
9717       return false;
9718     // FALL THROUGH.
9719   default:
9720     // ARM doesn't support any R+R*scale+imm addr modes.
9721     if (AM.BaseOffs)
9722       return false;
9723
9724     if (!VT.isSimple())
9725       return false;
9726
9727     if (Subtarget->isThumb2())
9728       return isLegalT2ScaledAddressingMode(AM, VT);
9729
9730     int Scale = AM.Scale;
9731     switch (VT.getSimpleVT().SimpleTy) {
9732     default: return false;
9733     case MVT::i1:
9734     case MVT::i8:
9735     case MVT::i32:
9736       if (Scale < 0) Scale = -Scale;
9737       if (Scale == 1)
9738         return true;
9739       // r + r << imm
9740       return isPowerOf2_32(Scale & ~1);
9741     case MVT::i16:
9742     case MVT::i64:
9743       // r + r
9744       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9745         return true;
9746       return false;
9747
9748     case MVT::isVoid:
9749       // Note, we allow "void" uses (basically, uses that aren't loads or
9750       // stores), because arm allows folding a scale into many arithmetic
9751       // operations.  This should be made more precise and revisited later.
9752
9753       // Allow r << imm, but the imm has to be a multiple of two.
9754       if (Scale & 1) return false;
9755       return isPowerOf2_32(Scale);
9756     }
9757   }
9758   return true;
9759 }
9760
9761 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9762 /// icmp immediate, that is the target has icmp instructions which can compare
9763 /// a register against the immediate without having to materialize the
9764 /// immediate into a register.
9765 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9766   // Thumb2 and ARM modes can use cmn for negative immediates.
9767   if (!Subtarget->isThumb())
9768     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9769   if (Subtarget->isThumb2())
9770     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9771   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9772   return Imm >= 0 && Imm <= 255;
9773 }
9774
9775 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9776 /// *or sub* immediate, that is the target has add or sub instructions which can
9777 /// add a register with the immediate without having to materialize the
9778 /// immediate into a register.
9779 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9780   // Same encoding for add/sub, just flip the sign.
9781   int64_t AbsImm = llvm::abs64(Imm);
9782   if (!Subtarget->isThumb())
9783     return ARM_AM::getSOImmVal(AbsImm) != -1;
9784   if (Subtarget->isThumb2())
9785     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9786   // Thumb1 only has 8-bit unsigned immediate.
9787   return AbsImm >= 0 && AbsImm <= 255;
9788 }
9789
9790 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9791                                       bool isSEXTLoad, SDValue &Base,
9792                                       SDValue &Offset, bool &isInc,
9793                                       SelectionDAG &DAG) {
9794   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9795     return false;
9796
9797   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
9798     // AddressingMode 3
9799     Base = Ptr->getOperand(0);
9800     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9801       int RHSC = (int)RHS->getZExtValue();
9802       if (RHSC < 0 && RHSC > -256) {
9803         assert(Ptr->getOpcode() == ISD::ADD);
9804         isInc = false;
9805         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9806         return true;
9807       }
9808     }
9809     isInc = (Ptr->getOpcode() == ISD::ADD);
9810     Offset = Ptr->getOperand(1);
9811     return true;
9812   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
9813     // AddressingMode 2
9814     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9815       int RHSC = (int)RHS->getZExtValue();
9816       if (RHSC < 0 && RHSC > -0x1000) {
9817         assert(Ptr->getOpcode() == ISD::ADD);
9818         isInc = false;
9819         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9820         Base = Ptr->getOperand(0);
9821         return true;
9822       }
9823     }
9824
9825     if (Ptr->getOpcode() == ISD::ADD) {
9826       isInc = true;
9827       ARM_AM::ShiftOpc ShOpcVal=
9828         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
9829       if (ShOpcVal != ARM_AM::no_shift) {
9830         Base = Ptr->getOperand(1);
9831         Offset = Ptr->getOperand(0);
9832       } else {
9833         Base = Ptr->getOperand(0);
9834         Offset = Ptr->getOperand(1);
9835       }
9836       return true;
9837     }
9838
9839     isInc = (Ptr->getOpcode() == ISD::ADD);
9840     Base = Ptr->getOperand(0);
9841     Offset = Ptr->getOperand(1);
9842     return true;
9843   }
9844
9845   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
9846   return false;
9847 }
9848
9849 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
9850                                      bool isSEXTLoad, SDValue &Base,
9851                                      SDValue &Offset, bool &isInc,
9852                                      SelectionDAG &DAG) {
9853   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
9854     return false;
9855
9856   Base = Ptr->getOperand(0);
9857   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
9858     int RHSC = (int)RHS->getZExtValue();
9859     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
9860       assert(Ptr->getOpcode() == ISD::ADD);
9861       isInc = false;
9862       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
9863       return true;
9864     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
9865       isInc = Ptr->getOpcode() == ISD::ADD;
9866       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
9867       return true;
9868     }
9869   }
9870
9871   return false;
9872 }
9873
9874 /// getPreIndexedAddressParts - returns true by value, base pointer and
9875 /// offset pointer and addressing mode by reference if the node's address
9876 /// can be legally represented as pre-indexed load / store address.
9877 bool
9878 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9879                                              SDValue &Offset,
9880                                              ISD::MemIndexedMode &AM,
9881                                              SelectionDAG &DAG) const {
9882   if (Subtarget->isThumb1Only())
9883     return false;
9884
9885   EVT VT;
9886   SDValue Ptr;
9887   bool isSEXTLoad = false;
9888   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9889     Ptr = LD->getBasePtr();
9890     VT  = LD->getMemoryVT();
9891     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9892   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9893     Ptr = ST->getBasePtr();
9894     VT  = ST->getMemoryVT();
9895   } else
9896     return false;
9897
9898   bool isInc;
9899   bool isLegal = false;
9900   if (Subtarget->isThumb2())
9901     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9902                                        Offset, isInc, DAG);
9903   else
9904     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
9905                                         Offset, isInc, DAG);
9906   if (!isLegal)
9907     return false;
9908
9909   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
9910   return true;
9911 }
9912
9913 /// getPostIndexedAddressParts - returns true by value, base pointer and
9914 /// offset pointer and addressing mode by reference if this node can be
9915 /// combined with a load / store to form a post-indexed load / store.
9916 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
9917                                                    SDValue &Base,
9918                                                    SDValue &Offset,
9919                                                    ISD::MemIndexedMode &AM,
9920                                                    SelectionDAG &DAG) const {
9921   if (Subtarget->isThumb1Only())
9922     return false;
9923
9924   EVT VT;
9925   SDValue Ptr;
9926   bool isSEXTLoad = false;
9927   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9928     VT  = LD->getMemoryVT();
9929     Ptr = LD->getBasePtr();
9930     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
9931   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9932     VT  = ST->getMemoryVT();
9933     Ptr = ST->getBasePtr();
9934   } else
9935     return false;
9936
9937   bool isInc;
9938   bool isLegal = false;
9939   if (Subtarget->isThumb2())
9940     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9941                                        isInc, DAG);
9942   else
9943     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
9944                                         isInc, DAG);
9945   if (!isLegal)
9946     return false;
9947
9948   if (Ptr != Base) {
9949     // Swap base ptr and offset to catch more post-index load / store when
9950     // it's legal. In Thumb2 mode, offset must be an immediate.
9951     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
9952         !Subtarget->isThumb2())
9953       std::swap(Base, Offset);
9954
9955     // Post-indexed load / store update the base pointer.
9956     if (Ptr != Base)
9957       return false;
9958   }
9959
9960   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
9961   return true;
9962 }
9963
9964 void ARMTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9965                                                        APInt &KnownZero,
9966                                                        APInt &KnownOne,
9967                                                        const SelectionDAG &DAG,
9968                                                        unsigned Depth) const {
9969   unsigned BitWidth = KnownOne.getBitWidth();
9970   KnownZero = KnownOne = APInt(BitWidth, 0);
9971   switch (Op.getOpcode()) {
9972   default: break;
9973   case ARMISD::ADDC:
9974   case ARMISD::ADDE:
9975   case ARMISD::SUBC:
9976   case ARMISD::SUBE:
9977     // These nodes' second result is a boolean
9978     if (Op.getResNo() == 0)
9979       break;
9980     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
9981     break;
9982   case ARMISD::CMOV: {
9983     // Bits are known zero/one if known on the LHS and RHS.
9984     DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
9985     if (KnownZero == 0 && KnownOne == 0) return;
9986
9987     APInt KnownZeroRHS, KnownOneRHS;
9988     DAG.ComputeMaskedBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
9989     KnownZero &= KnownZeroRHS;
9990     KnownOne  &= KnownOneRHS;
9991     return;
9992   }
9993   case ISD::INTRINSIC_W_CHAIN: {
9994     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
9995     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
9996     switch (IntID) {
9997     default: return;
9998     case Intrinsic::arm_ldaex:
9999     case Intrinsic::arm_ldrex: {
10000       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10001       unsigned MemBits = VT.getScalarType().getSizeInBits();
10002       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10003       return;
10004     }
10005     }
10006   }
10007   }
10008 }
10009
10010 //===----------------------------------------------------------------------===//
10011 //                           ARM Inline Assembly Support
10012 //===----------------------------------------------------------------------===//
10013
10014 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10015   // Looking for "rev" which is V6+.
10016   if (!Subtarget->hasV6Ops())
10017     return false;
10018
10019   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10020   std::string AsmStr = IA->getAsmString();
10021   SmallVector<StringRef, 4> AsmPieces;
10022   SplitString(AsmStr, AsmPieces, ";\n");
10023
10024   switch (AsmPieces.size()) {
10025   default: return false;
10026   case 1:
10027     AsmStr = AsmPieces[0];
10028     AsmPieces.clear();
10029     SplitString(AsmStr, AsmPieces, " \t,");
10030
10031     // rev $0, $1
10032     if (AsmPieces.size() == 3 &&
10033         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10034         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10035       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10036       if (Ty && Ty->getBitWidth() == 32)
10037         return IntrinsicLowering::LowerToByteSwap(CI);
10038     }
10039     break;
10040   }
10041
10042   return false;
10043 }
10044
10045 /// getConstraintType - Given a constraint letter, return the type of
10046 /// constraint it is for this target.
10047 ARMTargetLowering::ConstraintType
10048 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10049   if (Constraint.size() == 1) {
10050     switch (Constraint[0]) {
10051     default:  break;
10052     case 'l': return C_RegisterClass;
10053     case 'w': return C_RegisterClass;
10054     case 'h': return C_RegisterClass;
10055     case 'x': return C_RegisterClass;
10056     case 't': return C_RegisterClass;
10057     case 'j': return C_Other; // Constant for movw.
10058       // An address with a single base register. Due to the way we
10059       // currently handle addresses it is the same as an 'r' memory constraint.
10060     case 'Q': return C_Memory;
10061     }
10062   } else if (Constraint.size() == 2) {
10063     switch (Constraint[0]) {
10064     default: break;
10065     // All 'U+' constraints are addresses.
10066     case 'U': return C_Memory;
10067     }
10068   }
10069   return TargetLowering::getConstraintType(Constraint);
10070 }
10071
10072 /// Examine constraint type and operand type and determine a weight value.
10073 /// This object must already have been set up with the operand type
10074 /// and the current alternative constraint selected.
10075 TargetLowering::ConstraintWeight
10076 ARMTargetLowering::getSingleConstraintMatchWeight(
10077     AsmOperandInfo &info, const char *constraint) const {
10078   ConstraintWeight weight = CW_Invalid;
10079   Value *CallOperandVal = info.CallOperandVal;
10080     // If we don't have a value, we can't do a match,
10081     // but allow it at the lowest weight.
10082   if (!CallOperandVal)
10083     return CW_Default;
10084   Type *type = CallOperandVal->getType();
10085   // Look at the constraint type.
10086   switch (*constraint) {
10087   default:
10088     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10089     break;
10090   case 'l':
10091     if (type->isIntegerTy()) {
10092       if (Subtarget->isThumb())
10093         weight = CW_SpecificReg;
10094       else
10095         weight = CW_Register;
10096     }
10097     break;
10098   case 'w':
10099     if (type->isFloatingPointTy())
10100       weight = CW_Register;
10101     break;
10102   }
10103   return weight;
10104 }
10105
10106 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10107 RCPair
10108 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10109                                                 MVT VT) const {
10110   if (Constraint.size() == 1) {
10111     // GCC ARM Constraint Letters
10112     switch (Constraint[0]) {
10113     case 'l': // Low regs or general regs.
10114       if (Subtarget->isThumb())
10115         return RCPair(0U, &ARM::tGPRRegClass);
10116       return RCPair(0U, &ARM::GPRRegClass);
10117     case 'h': // High regs or no regs.
10118       if (Subtarget->isThumb())
10119         return RCPair(0U, &ARM::hGPRRegClass);
10120       break;
10121     case 'r':
10122       return RCPair(0U, &ARM::GPRRegClass);
10123     case 'w':
10124       if (VT == MVT::Other)
10125         break;
10126       if (VT == MVT::f32)
10127         return RCPair(0U, &ARM::SPRRegClass);
10128       if (VT.getSizeInBits() == 64)
10129         return RCPair(0U, &ARM::DPRRegClass);
10130       if (VT.getSizeInBits() == 128)
10131         return RCPair(0U, &ARM::QPRRegClass);
10132       break;
10133     case 'x':
10134       if (VT == MVT::Other)
10135         break;
10136       if (VT == MVT::f32)
10137         return RCPair(0U, &ARM::SPR_8RegClass);
10138       if (VT.getSizeInBits() == 64)
10139         return RCPair(0U, &ARM::DPR_8RegClass);
10140       if (VT.getSizeInBits() == 128)
10141         return RCPair(0U, &ARM::QPR_8RegClass);
10142       break;
10143     case 't':
10144       if (VT == MVT::f32)
10145         return RCPair(0U, &ARM::SPRRegClass);
10146       break;
10147     }
10148   }
10149   if (StringRef("{cc}").equals_lower(Constraint))
10150     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10151
10152   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10153 }
10154
10155 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10156 /// vector.  If it is invalid, don't add anything to Ops.
10157 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10158                                                      std::string &Constraint,
10159                                                      std::vector<SDValue>&Ops,
10160                                                      SelectionDAG &DAG) const {
10161   SDValue Result;
10162
10163   // Currently only support length 1 constraints.
10164   if (Constraint.length() != 1) return;
10165
10166   char ConstraintLetter = Constraint[0];
10167   switch (ConstraintLetter) {
10168   default: break;
10169   case 'j':
10170   case 'I': case 'J': case 'K': case 'L':
10171   case 'M': case 'N': case 'O':
10172     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10173     if (!C)
10174       return;
10175
10176     int64_t CVal64 = C->getSExtValue();
10177     int CVal = (int) CVal64;
10178     // None of these constraints allow values larger than 32 bits.  Check
10179     // that the value fits in an int.
10180     if (CVal != CVal64)
10181       return;
10182
10183     switch (ConstraintLetter) {
10184       case 'j':
10185         // Constant suitable for movw, must be between 0 and
10186         // 65535.
10187         if (Subtarget->hasV6T2Ops())
10188           if (CVal >= 0 && CVal <= 65535)
10189             break;
10190         return;
10191       case 'I':
10192         if (Subtarget->isThumb1Only()) {
10193           // This must be a constant between 0 and 255, for ADD
10194           // immediates.
10195           if (CVal >= 0 && CVal <= 255)
10196             break;
10197         } else if (Subtarget->isThumb2()) {
10198           // A constant that can be used as an immediate value in a
10199           // data-processing instruction.
10200           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10201             break;
10202         } else {
10203           // A constant that can be used as an immediate value in a
10204           // data-processing instruction.
10205           if (ARM_AM::getSOImmVal(CVal) != -1)
10206             break;
10207         }
10208         return;
10209
10210       case 'J':
10211         if (Subtarget->isThumb()) {  // FIXME thumb2
10212           // This must be a constant between -255 and -1, for negated ADD
10213           // immediates. This can be used in GCC with an "n" modifier that
10214           // prints the negated value, for use with SUB instructions. It is
10215           // not useful otherwise but is implemented for compatibility.
10216           if (CVal >= -255 && CVal <= -1)
10217             break;
10218         } else {
10219           // This must be a constant between -4095 and 4095. It is not clear
10220           // what this constraint is intended for. Implemented for
10221           // compatibility with GCC.
10222           if (CVal >= -4095 && CVal <= 4095)
10223             break;
10224         }
10225         return;
10226
10227       case 'K':
10228         if (Subtarget->isThumb1Only()) {
10229           // A 32-bit value where only one byte has a nonzero value. Exclude
10230           // zero to match GCC. This constraint is used by GCC internally for
10231           // constants that can be loaded with a move/shift combination.
10232           // It is not useful otherwise but is implemented for compatibility.
10233           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10234             break;
10235         } else if (Subtarget->isThumb2()) {
10236           // A constant whose bitwise inverse can be used as an immediate
10237           // value in a data-processing instruction. This can be used in GCC
10238           // with a "B" modifier that prints the inverted value, for use with
10239           // BIC and MVN instructions. It is not useful otherwise but is
10240           // implemented for compatibility.
10241           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10242             break;
10243         } else {
10244           // A constant whose bitwise inverse can be used as an immediate
10245           // value in a data-processing instruction. This can be used in GCC
10246           // with a "B" modifier that prints the inverted value, for use with
10247           // BIC and MVN instructions. It is not useful otherwise but is
10248           // implemented for compatibility.
10249           if (ARM_AM::getSOImmVal(~CVal) != -1)
10250             break;
10251         }
10252         return;
10253
10254       case 'L':
10255         if (Subtarget->isThumb1Only()) {
10256           // This must be a constant between -7 and 7,
10257           // for 3-operand ADD/SUB immediate instructions.
10258           if (CVal >= -7 && CVal < 7)
10259             break;
10260         } else if (Subtarget->isThumb2()) {
10261           // A constant whose negation can be used as an immediate value in a
10262           // data-processing instruction. This can be used in GCC with an "n"
10263           // modifier that prints the negated value, for use with SUB
10264           // instructions. It is not useful otherwise but is implemented for
10265           // compatibility.
10266           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10267             break;
10268         } else {
10269           // A constant whose negation can be used as an immediate value in a
10270           // data-processing instruction. This can be used in GCC with an "n"
10271           // modifier that prints the negated value, for use with SUB
10272           // instructions. It is not useful otherwise but is implemented for
10273           // compatibility.
10274           if (ARM_AM::getSOImmVal(-CVal) != -1)
10275             break;
10276         }
10277         return;
10278
10279       case 'M':
10280         if (Subtarget->isThumb()) { // FIXME thumb2
10281           // This must be a multiple of 4 between 0 and 1020, for
10282           // ADD sp + immediate.
10283           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10284             break;
10285         } else {
10286           // A power of two or a constant between 0 and 32.  This is used in
10287           // GCC for the shift amount on shifted register operands, but it is
10288           // useful in general for any shift amounts.
10289           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10290             break;
10291         }
10292         return;
10293
10294       case 'N':
10295         if (Subtarget->isThumb()) {  // FIXME thumb2
10296           // This must be a constant between 0 and 31, for shift amounts.
10297           if (CVal >= 0 && CVal <= 31)
10298             break;
10299         }
10300         return;
10301
10302       case 'O':
10303         if (Subtarget->isThumb()) {  // FIXME thumb2
10304           // This must be a multiple of 4 between -508 and 508, for
10305           // ADD/SUB sp = sp + immediate.
10306           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10307             break;
10308         }
10309         return;
10310     }
10311     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10312     break;
10313   }
10314
10315   if (Result.getNode()) {
10316     Ops.push_back(Result);
10317     return;
10318   }
10319   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10320 }
10321
10322 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10323   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10324   unsigned Opcode = Op->getOpcode();
10325   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10326       "Invalid opcode for Div/Rem lowering");
10327   bool isSigned = (Opcode == ISD::SDIVREM);
10328   EVT VT = Op->getValueType(0);
10329   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10330
10331   RTLIB::Libcall LC;
10332   switch (VT.getSimpleVT().SimpleTy) {
10333   default: llvm_unreachable("Unexpected request for libcall!");
10334   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10335   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10336   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10337   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10338   }
10339
10340   SDValue InChain = DAG.getEntryNode();
10341
10342   TargetLowering::ArgListTy Args;
10343   TargetLowering::ArgListEntry Entry;
10344   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10345     EVT ArgVT = Op->getOperand(i).getValueType();
10346     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10347     Entry.Node = Op->getOperand(i);
10348     Entry.Ty = ArgTy;
10349     Entry.isSExt = isSigned;
10350     Entry.isZExt = !isSigned;
10351     Args.push_back(Entry);
10352   }
10353
10354   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10355                                          getPointerTy());
10356
10357   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10358
10359   SDLoc dl(Op);
10360   TargetLowering::
10361   CallLoweringInfo CLI(InChain, RetTy, isSigned, !isSigned, false, true,
10362                     0, getLibcallCallingConv(LC), /*isTailCall=*/false,
10363                     /*doesNotReturn=*/false, /*isReturnValueUsed=*/true,
10364                     Callee, Args, DAG, dl);
10365   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10366
10367   return CallInfo.first;
10368 }
10369
10370 bool
10371 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10372   // The ARM target isn't yet aware of offsets.
10373   return false;
10374 }
10375
10376 bool ARM::isBitFieldInvertedMask(unsigned v) {
10377   if (v == 0xffffffff)
10378     return false;
10379
10380   // there can be 1's on either or both "outsides", all the "inside"
10381   // bits must be 0's
10382   unsigned TO = CountTrailingOnes_32(v);
10383   unsigned LO = CountLeadingOnes_32(v);
10384   v = (v >> TO) << TO;
10385   v = (v << LO) >> LO;
10386   return v == 0;
10387 }
10388
10389 /// isFPImmLegal - Returns true if the target can instruction select the
10390 /// specified FP immediate natively. If false, the legalizer will
10391 /// materialize the FP immediate as a load from a constant pool.
10392 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10393   if (!Subtarget->hasVFP3())
10394     return false;
10395   if (VT == MVT::f32)
10396     return ARM_AM::getFP32Imm(Imm) != -1;
10397   if (VT == MVT::f64)
10398     return ARM_AM::getFP64Imm(Imm) != -1;
10399   return false;
10400 }
10401
10402 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10403 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10404 /// specified in the intrinsic calls.
10405 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10406                                            const CallInst &I,
10407                                            unsigned Intrinsic) const {
10408   switch (Intrinsic) {
10409   case Intrinsic::arm_neon_vld1:
10410   case Intrinsic::arm_neon_vld2:
10411   case Intrinsic::arm_neon_vld3:
10412   case Intrinsic::arm_neon_vld4:
10413   case Intrinsic::arm_neon_vld2lane:
10414   case Intrinsic::arm_neon_vld3lane:
10415   case Intrinsic::arm_neon_vld4lane: {
10416     Info.opc = ISD::INTRINSIC_W_CHAIN;
10417     // Conservatively set memVT to the entire set of vectors loaded.
10418     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10419     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10420     Info.ptrVal = I.getArgOperand(0);
10421     Info.offset = 0;
10422     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10423     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10424     Info.vol = false; // volatile loads with NEON intrinsics not supported
10425     Info.readMem = true;
10426     Info.writeMem = false;
10427     return true;
10428   }
10429   case Intrinsic::arm_neon_vst1:
10430   case Intrinsic::arm_neon_vst2:
10431   case Intrinsic::arm_neon_vst3:
10432   case Intrinsic::arm_neon_vst4:
10433   case Intrinsic::arm_neon_vst2lane:
10434   case Intrinsic::arm_neon_vst3lane:
10435   case Intrinsic::arm_neon_vst4lane: {
10436     Info.opc = ISD::INTRINSIC_VOID;
10437     // Conservatively set memVT to the entire set of vectors stored.
10438     unsigned NumElts = 0;
10439     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10440       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10441       if (!ArgTy->isVectorTy())
10442         break;
10443       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10444     }
10445     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10446     Info.ptrVal = I.getArgOperand(0);
10447     Info.offset = 0;
10448     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10449     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10450     Info.vol = false; // volatile stores with NEON intrinsics not supported
10451     Info.readMem = false;
10452     Info.writeMem = true;
10453     return true;
10454   }
10455   case Intrinsic::arm_ldaex:
10456   case Intrinsic::arm_ldrex: {
10457     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10458     Info.opc = ISD::INTRINSIC_W_CHAIN;
10459     Info.memVT = MVT::getVT(PtrTy->getElementType());
10460     Info.ptrVal = I.getArgOperand(0);
10461     Info.offset = 0;
10462     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10463     Info.vol = true;
10464     Info.readMem = true;
10465     Info.writeMem = false;
10466     return true;
10467   }
10468   case Intrinsic::arm_stlex:
10469   case Intrinsic::arm_strex: {
10470     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10471     Info.opc = ISD::INTRINSIC_W_CHAIN;
10472     Info.memVT = MVT::getVT(PtrTy->getElementType());
10473     Info.ptrVal = I.getArgOperand(1);
10474     Info.offset = 0;
10475     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10476     Info.vol = true;
10477     Info.readMem = false;
10478     Info.writeMem = true;
10479     return true;
10480   }
10481   case Intrinsic::arm_stlexd:
10482   case Intrinsic::arm_strexd: {
10483     Info.opc = ISD::INTRINSIC_W_CHAIN;
10484     Info.memVT = MVT::i64;
10485     Info.ptrVal = I.getArgOperand(2);
10486     Info.offset = 0;
10487     Info.align = 8;
10488     Info.vol = true;
10489     Info.readMem = false;
10490     Info.writeMem = true;
10491     return true;
10492   }
10493   case Intrinsic::arm_ldaexd:
10494   case Intrinsic::arm_ldrexd: {
10495     Info.opc = ISD::INTRINSIC_W_CHAIN;
10496     Info.memVT = MVT::i64;
10497     Info.ptrVal = I.getArgOperand(0);
10498     Info.offset = 0;
10499     Info.align = 8;
10500     Info.vol = true;
10501     Info.readMem = true;
10502     Info.writeMem = false;
10503     return true;
10504   }
10505   default:
10506     break;
10507   }
10508
10509   return false;
10510 }
10511
10512 /// \brief Returns true if it is beneficial to convert a load of a constant
10513 /// to just the constant itself.
10514 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10515                                                           Type *Ty) const {
10516   assert(Ty->isIntegerTy());
10517
10518   unsigned Bits = Ty->getPrimitiveSizeInBits();
10519   if (Bits == 0 || Bits > 32)
10520     return false;
10521   return true;
10522 }
10523
10524 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10525   // Loads and stores less than 64-bits are already atomic; ones above that
10526   // are doomed anyway, so defer to the default libcall and blame the OS when
10527   // things go wrong:
10528   if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
10529     return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 64;
10530   else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
10531     return LI->getType()->getPrimitiveSizeInBits() == 64;
10532
10533   // For the real atomic operations, we have ldrex/strex up to 64 bits.
10534   return Inst->getType()->getPrimitiveSizeInBits() <= 64;
10535 }
10536
10537 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10538                                          AtomicOrdering Ord) const {
10539   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10540   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10541   bool IsAcquire =
10542       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10543
10544   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10545   // intrinsic must return {i32, i32} and we have to recombine them into a
10546   // single i64 here.
10547   if (ValTy->getPrimitiveSizeInBits() == 64) {
10548     Intrinsic::ID Int =
10549         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10550     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10551
10552     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10553     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10554
10555     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10556     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10557     if (!Subtarget->isLittle())
10558       std::swap (Lo, Hi);
10559     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10560     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10561     return Builder.CreateOr(
10562         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10563   }
10564
10565   Type *Tys[] = { Addr->getType() };
10566   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10567   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10568
10569   return Builder.CreateTruncOrBitCast(
10570       Builder.CreateCall(Ldrex, Addr),
10571       cast<PointerType>(Addr->getType())->getElementType());
10572 }
10573
10574 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10575                                                Value *Addr,
10576                                                AtomicOrdering Ord) const {
10577   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10578   bool IsRelease =
10579       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10580
10581   // Since the intrinsics must have legal type, the i64 intrinsics take two
10582   // parameters: "i32, i32". We must marshal Val into the appropriate form
10583   // before the call.
10584   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10585     Intrinsic::ID Int =
10586         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10587     Function *Strex = Intrinsic::getDeclaration(M, Int);
10588     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10589
10590     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10591     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10592     if (!Subtarget->isLittle())
10593       std::swap (Lo, Hi);
10594     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10595     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10596   }
10597
10598   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10599   Type *Tys[] = { Addr->getType() };
10600   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10601
10602   return Builder.CreateCall2(
10603       Strex, Builder.CreateZExtOrBitCast(
10604                  Val, Strex->getFunctionType()->getParamType(0)),
10605       Addr);
10606 }