Silencing a usually-helpful-but-braindead-silly-in-this-case sign mismatch warning...
[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/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalValue.h"
40 #include "llvm/IR/IRBuilder.h"
41 #include "llvm/IR/Instruction.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Type.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <utility>
52 using namespace llvm;
53
54 #define DEBUG_TYPE "arm-isel"
55
56 STATISTIC(NumTailCalls, "Number of tail calls");
57 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
58 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
59
60 cl::opt<bool>
61 EnableARMLongCalls("arm-long-calls", cl::Hidden,
62   cl::desc("Generate calls via indirect call instructions"),
63   cl::init(false));
64
65 static cl::opt<bool>
66 ARMInterworking("arm-interworking", cl::Hidden,
67   cl::desc("Enable / disable ARM interworking (for debugging only)"),
68   cl::init(true));
69
70 namespace {
71   class ARMCCState : public CCState {
72   public:
73     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
74                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
75                ParmContext PC)
76         : CCState(CC, isVarArg, MF, locs, C) {
77       assert(((PC == Call) || (PC == Prologue)) &&
78              "ARMCCState users must specify whether their context is call"
79              "or prologue generation.");
80       CallOrPrologue = PC;
81     }
82   };
83 }
84
85 // The APCS parameter registers.
86 static const MCPhysReg GPRArgRegs[] = {
87   ARM::R0, ARM::R1, ARM::R2, ARM::R3
88 };
89
90 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
91                                        MVT PromotedBitwiseVT) {
92   if (VT != PromotedLdStVT) {
93     setOperationAction(ISD::LOAD, VT, Promote);
94     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
95
96     setOperationAction(ISD::STORE, VT, Promote);
97     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
98   }
99
100   MVT ElemTy = VT.getVectorElementType();
101   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
102     setOperationAction(ISD::SETCC, VT, Custom);
103   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
104   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
105   if (ElemTy == MVT::i32) {
106     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
108     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
109     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
110   } else {
111     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
113     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
114     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
115   }
116   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
117   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
118   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
119   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
120   setOperationAction(ISD::SELECT,            VT, Expand);
121   setOperationAction(ISD::SELECT_CC,         VT, Expand);
122   setOperationAction(ISD::VSELECT,           VT, Expand);
123   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
124   if (VT.isInteger()) {
125     setOperationAction(ISD::SHL, VT, Custom);
126     setOperationAction(ISD::SRA, VT, Custom);
127     setOperationAction(ISD::SRL, VT, Custom);
128   }
129
130   // Promote all bit-wise operations.
131   if (VT.isInteger() && VT != PromotedBitwiseVT) {
132     setOperationAction(ISD::AND, VT, Promote);
133     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
134     setOperationAction(ISD::OR,  VT, Promote);
135     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
136     setOperationAction(ISD::XOR, VT, Promote);
137     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
138   }
139
140   // Neon does not support vector divide/remainder operations.
141   setOperationAction(ISD::SDIV, VT, Expand);
142   setOperationAction(ISD::UDIV, VT, Expand);
143   setOperationAction(ISD::FDIV, VT, Expand);
144   setOperationAction(ISD::SREM, VT, Expand);
145   setOperationAction(ISD::UREM, VT, Expand);
146   setOperationAction(ISD::FREM, VT, Expand);
147 }
148
149 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
150   addRegisterClass(VT, &ARM::DPRRegClass);
151   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
152 }
153
154 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
155   addRegisterClass(VT, &ARM::DPairRegClass);
156   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
157 }
158
159 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
160   if (TT.isOSBinFormatMachO())
161     return new TargetLoweringObjectFileMachO();
162   if (TT.isOSWindows())
163     return new TargetLoweringObjectFileCOFF();
164   return new ARMElfTargetObjectFile();
165 }
166
167 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
168     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
169   Subtarget = &TM.getSubtarget<ARMSubtarget>();
170   RegInfo = TM.getSubtargetImpl()->getRegisterInfo();
171   Itins = TM.getSubtargetImpl()->getInstrItineraryData();
172
173   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
174
175   if (Subtarget->isTargetMachO()) {
176     // Uses VFP for Thumb libfuncs if available.
177     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
178         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
179       // Single-precision floating-point arithmetic.
180       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
181       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
182       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
183       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
184
185       // Double-precision floating-point arithmetic.
186       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
187       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
188       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
189       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
190
191       // Single-precision comparisons.
192       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
193       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
194       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
195       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
196       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
197       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
198       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
199       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
200
201       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
207       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
208       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
209
210       // Double-precision comparisons.
211       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
212       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
213       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
214       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
215       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
216       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
217       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
218       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
219
220       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
226       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
227       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
228
229       // Floating-point to integer conversions.
230       // i64 conversions are done via library routines even when generating VFP
231       // instructions, so use the same ones.
232       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
233       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
234       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
235       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
236
237       // Conversions between floating types.
238       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
239       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
240
241       // Integer to floating-point conversions.
242       // i64 conversions are done via library routines even when generating VFP
243       // instructions, so use the same ones.
244       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
245       // e.g., __floatunsidf vs. __floatunssidfvfp.
246       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
247       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
248       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
249       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
250     }
251   }
252
253   // These libcalls are not available in 32-bit.
254   setLibcallName(RTLIB::SHL_I128, nullptr);
255   setLibcallName(RTLIB::SRL_I128, nullptr);
256   setLibcallName(RTLIB::SRA_I128, nullptr);
257
258   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
259       !Subtarget->isTargetWindows()) {
260     static const struct {
261       const RTLIB::Libcall Op;
262       const char * const Name;
263       const CallingConv::ID CC;
264       const ISD::CondCode Cond;
265     } LibraryCalls[] = {
266       // Double-precision floating-point arithmetic helper functions
267       // RTABI chapter 4.1.2, Table 2
268       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
272
273       // Double-precision floating-point comparison helper functions
274       // RTABI chapter 4.1.2, Table 3
275       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
276       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
277       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
282       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
283
284       // Single-precision floating-point arithmetic helper functions
285       // RTABI chapter 4.1.2, Table 4
286       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
290
291       // Single-precision floating-point comparison helper functions
292       // RTABI chapter 4.1.2, Table 5
293       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
294       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
295       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
300       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
301
302       // Floating-point to integer conversions.
303       // RTABI chapter 4.1.2, Table 6
304       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312
313       // Conversions between floating types.
314       // RTABI chapter 4.1.2, Table 7
315       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Integer to floating-point conversions.
320       // RTABI chapter 4.1.2, Table 8
321       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329
330       // Long long helper functions
331       // RTABI chapter 4.2, Table 9
332       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Integer division functions
338       // RTABI chapter 4.3.1
339       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347
348       // Memory operations
349       // RTABI chapter 4.3.4
350       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
353     };
354
355     for (const auto &LC : LibraryCalls) {
356       setLibcallName(LC.Op, LC.Name);
357       setLibcallCallingConv(LC.Op, LC.CC);
358       if (LC.Cond != ISD::SETCC_INVALID)
359         setCmpLibcallCC(LC.Op, LC.Cond);
360     }
361   }
362
363   if (Subtarget->isTargetWindows()) {
364     static const struct {
365       const RTLIB::Libcall Op;
366       const char * const Name;
367       const CallingConv::ID CC;
368     } LibraryCalls[] = {
369       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
376       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
377     };
378
379     for (const auto &LC : LibraryCalls) {
380       setLibcallName(LC.Op, LC.Name);
381       setLibcallCallingConv(LC.Op, LC.CC);
382     }
383   }
384
385   // Use divmod compiler-rt calls for iOS 5.0 and later.
386   if (Subtarget->getTargetTriple().isiOS() &&
387       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
388     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
389     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
390   }
391
392   // The half <-> float conversion functions are always soft-float, but are
393   // needed for some targets which use a hard-float calling convention by
394   // default.
395   if (Subtarget->isAAPCS_ABI()) {
396     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
397     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
398     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
399   } else {
400     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
401     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
402     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
403   }
404
405   if (Subtarget->isThumb1Only())
406     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
407   else
408     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
409   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
410       !Subtarget->isThumb1Only()) {
411     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
412     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
413   }
414
415   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
416        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
417     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
418          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
419       setTruncStoreAction((MVT::SimpleValueType)VT,
420                           (MVT::SimpleValueType)InnerVT, Expand);
421     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
422     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
423     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
424
425     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
426     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
427     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
428     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
429
430     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
431   }
432
433   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
434   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
435
436   if (Subtarget->hasNEON()) {
437     addDRTypeForNEON(MVT::v2f32);
438     addDRTypeForNEON(MVT::v8i8);
439     addDRTypeForNEON(MVT::v4i16);
440     addDRTypeForNEON(MVT::v2i32);
441     addDRTypeForNEON(MVT::v1i64);
442
443     addQRTypeForNEON(MVT::v4f32);
444     addQRTypeForNEON(MVT::v2f64);
445     addQRTypeForNEON(MVT::v16i8);
446     addQRTypeForNEON(MVT::v8i16);
447     addQRTypeForNEON(MVT::v4i32);
448     addQRTypeForNEON(MVT::v2i64);
449
450     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
451     // neither Neon nor VFP support any arithmetic operations on it.
452     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
453     // supported for v4f32.
454     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
455     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
456     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
457     // FIXME: Code duplication: FDIV and FREM are expanded always, see
458     // ARMTargetLowering::addTypeForNEON method for details.
459     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
460     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
461     // FIXME: Create unittest.
462     // In another words, find a way when "copysign" appears in DAG with vector
463     // operands.
464     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
465     // FIXME: Code duplication: SETCC has custom operation action, see
466     // ARMTargetLowering::addTypeForNEON method for details.
467     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FNEG and for FABS.
469     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
470     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
471     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
473     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
474     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
475     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
476     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
477     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
478     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
479     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
480     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
481     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
482     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
483     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
484     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
485     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
486     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
487     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
488
489     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
491     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
492     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
493     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
494     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
495     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
496     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
497     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
498     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
499     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
500     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
501     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
502     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
503     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
504
505     // Mark v2f32 intrinsics.
506     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
508     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
509     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
510     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
511     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
512     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
513     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
514     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
515     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
516     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
517     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
518     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
519     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
520     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
521
522     // Neon does not support some operations on v1i64 and v2i64 types.
523     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
524     // Custom handling for some quad-vector types to detect VMULL.
525     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
526     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
527     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
528     // Custom handling for some vector types to avoid expensive expansions
529     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
530     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
531     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
532     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
533     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
534     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
535     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
536     // a destination type that is wider than the source, and nor does
537     // it have a FP_TO_[SU]INT instruction with a narrower destination than
538     // source.
539     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
540     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
542     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
543
544     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
545     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
546
547     // NEON does not have single instruction CTPOP for vectors with element
548     // types wider than 8-bits.  However, custom lowering can leverage the
549     // v8i8/v16i8 vcnt instruction.
550     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
551     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
552     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
553     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
554
555     // NEON only has FMA instructions as of VFP4.
556     if (!Subtarget->hasVFP4()) {
557       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
558       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
559     }
560
561     setTargetDAGCombine(ISD::INTRINSIC_VOID);
562     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
563     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
564     setTargetDAGCombine(ISD::SHL);
565     setTargetDAGCombine(ISD::SRL);
566     setTargetDAGCombine(ISD::SRA);
567     setTargetDAGCombine(ISD::SIGN_EXTEND);
568     setTargetDAGCombine(ISD::ZERO_EXTEND);
569     setTargetDAGCombine(ISD::ANY_EXTEND);
570     setTargetDAGCombine(ISD::SELECT_CC);
571     setTargetDAGCombine(ISD::BUILD_VECTOR);
572     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
573     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
574     setTargetDAGCombine(ISD::STORE);
575     setTargetDAGCombine(ISD::FP_TO_SINT);
576     setTargetDAGCombine(ISD::FP_TO_UINT);
577     setTargetDAGCombine(ISD::FDIV);
578
579     // It is legal to extload from v4i8 to v4i16 or v4i32.
580     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
581                   MVT::v4i16, MVT::v2i16,
582                   MVT::v2i32};
583     for (unsigned i = 0; i < 6; ++i) {
584       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
585       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
586       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
587     }
588   }
589
590   // ARM and Thumb2 support UMLAL/SMLAL.
591   if (!Subtarget->isThumb1Only())
592     setTargetDAGCombine(ISD::ADDC);
593
594   if (Subtarget->isFPOnlySP()) {
595     // When targetting a floating-point unit with only single-precision
596     // operations, f64 is legal for the few double-precision instructions which
597     // are present However, no double-precision operations other than moves,
598     // loads and stores are provided by the hardware.
599     setOperationAction(ISD::FADD,       MVT::f64, Expand);
600     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
601     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
602     setOperationAction(ISD::FMA,        MVT::f64, Expand);
603     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
604     setOperationAction(ISD::FREM,       MVT::f64, Expand);
605     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
606     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
607     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
608     setOperationAction(ISD::FABS,       MVT::f64, Expand);
609     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
610     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
611     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
612     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
613     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
614     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
615     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
616     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
617     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
618     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
619     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
620     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
621     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
622     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
623     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
624     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
625     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
626   }
627
628   computeRegisterProperties();
629
630   // ARM does not have floating-point extending loads.
631   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
632   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
633
634   // ... or truncating stores
635   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
636   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
637   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
638
639   // ARM does not have i1 sign extending load.
640   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
641
642   // ARM supports all 4 flavors of integer indexed load / store.
643   if (!Subtarget->isThumb1Only()) {
644     for (unsigned im = (unsigned)ISD::PRE_INC;
645          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
646       setIndexedLoadAction(im,  MVT::i1,  Legal);
647       setIndexedLoadAction(im,  MVT::i8,  Legal);
648       setIndexedLoadAction(im,  MVT::i16, Legal);
649       setIndexedLoadAction(im,  MVT::i32, Legal);
650       setIndexedStoreAction(im, MVT::i1,  Legal);
651       setIndexedStoreAction(im, MVT::i8,  Legal);
652       setIndexedStoreAction(im, MVT::i16, Legal);
653       setIndexedStoreAction(im, MVT::i32, Legal);
654     }
655   }
656
657   setOperationAction(ISD::SADDO, MVT::i32, Custom);
658   setOperationAction(ISD::UADDO, MVT::i32, Custom);
659   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
660   setOperationAction(ISD::USUBO, MVT::i32, Custom);
661
662   // i64 operation support.
663   setOperationAction(ISD::MUL,     MVT::i64, Expand);
664   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
665   if (Subtarget->isThumb1Only()) {
666     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
667     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
668   }
669   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
670       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
671     setOperationAction(ISD::MULHS, MVT::i32, Expand);
672
673   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
674   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
675   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
676   setOperationAction(ISD::SRL,       MVT::i64, Custom);
677   setOperationAction(ISD::SRA,       MVT::i64, Custom);
678
679   if (!Subtarget->isThumb1Only()) {
680     // FIXME: We should do this for Thumb1 as well.
681     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
682     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
683     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
684     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
685   }
686
687   // ARM does not have ROTL.
688   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
689   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
690   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
691   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
692     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
693
694   // These just redirect to CTTZ and CTLZ on ARM.
695   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
696   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
697
698   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
699
700   // Only ARMv6 has BSWAP.
701   if (!Subtarget->hasV6Ops())
702     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
703
704   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
705       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
706     // These are expanded into libcalls if the cpu doesn't have HW divider.
707     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
708     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
709   }
710
711   // FIXME: Also set divmod for SREM on EABI
712   setOperationAction(ISD::SREM,  MVT::i32, Expand);
713   setOperationAction(ISD::UREM,  MVT::i32, Expand);
714   // Register based DivRem for AEABI (RTABI 4.2)
715   if (Subtarget->isTargetAEABI()) {
716     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
717     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
718     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
719     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
720     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
721     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
722     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
723     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
724
725     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
726     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
727     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
728     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
729     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
730     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
731     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
732     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
733
734     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
735     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
736   } else {
737     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
738     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
739   }
740
741   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
742   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
743   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
744   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
745   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
746
747   setOperationAction(ISD::TRAP, MVT::Other, Legal);
748
749   // Use the default implementation.
750   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
751   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
752   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
753   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
754   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
755   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
756
757   if (!Subtarget->isTargetMachO()) {
758     // Non-MachO platforms may return values in these registers via the
759     // personality function.
760     setExceptionPointerRegister(ARM::R0);
761     setExceptionSelectorRegister(ARM::R1);
762   }
763
764   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
765     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
766   else
767     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
768
769   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
770   // the default expansion. If we are targeting a single threaded system,
771   // then set them all for expand so we can lower them later into their
772   // non-atomic form.
773   if (TM.Options.ThreadModel == ThreadModel::Single)
774     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
775   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
776     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
777     // to ldrex/strex loops already.
778     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
779
780     // On v8, we have particularly efficient implementations of atomic fences
781     // if they can be combined with nearby atomic loads and stores.
782     if (!Subtarget->hasV8Ops()) {
783       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
784       setInsertFencesForAtomic(true);
785     }
786   } else {
787     // If there's anything we can use as a barrier, go through custom lowering
788     // for ATOMIC_FENCE.
789     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
790                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
791
792     // Set them all for expansion, which will force libcalls.
793     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
794     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
795     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
796     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
797     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
798     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
799     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
800     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
801     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
802     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
803     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
804     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
805     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
806     // Unordered/Monotonic case.
807     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
808     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
809   }
810
811   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
812
813   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
814   if (!Subtarget->hasV6Ops()) {
815     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
816     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
817   }
818   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
819
820   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
821       !Subtarget->isThumb1Only()) {
822     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
823     // iff target supports vfp2.
824     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
825     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
826   }
827
828   // We want to custom lower some of our intrinsics.
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
830   if (Subtarget->isTargetDarwin()) {
831     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
832     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
833     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
834   }
835
836   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
837   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
838   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
839   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
840   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
841   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
842   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
843   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
844   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
845
846   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
847   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
848   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
849   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
850   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
851
852   // We don't support sin/cos/fmod/copysign/pow
853   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
854   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
855   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
856   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
857   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
858   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
859   setOperationAction(ISD::FREM,      MVT::f64, Expand);
860   setOperationAction(ISD::FREM,      MVT::f32, Expand);
861   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
862       !Subtarget->isThumb1Only()) {
863     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
864     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
865   }
866   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
867   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
868
869   if (!Subtarget->hasVFP4()) {
870     setOperationAction(ISD::FMA, MVT::f64, Expand);
871     setOperationAction(ISD::FMA, MVT::f32, Expand);
872   }
873
874   // Various VFP goodness
875   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
876     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
877     if (Subtarget->hasVFP2()) {
878       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
879       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
880       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
881       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
882     }
883
884     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
885     if (!Subtarget->hasV8Ops()) {
886       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
887       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
888     }
889
890     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
891     if (!Subtarget->hasFP16()) {
892       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
893       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
894     }
895   }
896
897   // Combine sin / cos into one node or libcall if possible.
898   if (Subtarget->hasSinCos()) {
899     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
900     setLibcallName(RTLIB::SINCOS_F64, "sincos");
901     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
902       // For iOS, we don't want to the normal expansion of a libcall to
903       // sincos. We want to issue a libcall to __sincos_stret.
904       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
905       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
906     }
907   }
908
909   // ARMv8 implements a lot of rounding-like FP operations.
910   if (Subtarget->hasV8Ops()) {
911     static MVT RoundingTypes[] = {MVT::f32, MVT::f64};
912     for (const auto Ty : RoundingTypes) {
913       setOperationAction(ISD::FFLOOR, Ty, Legal);
914       setOperationAction(ISD::FCEIL, Ty, Legal);
915       setOperationAction(ISD::FROUND, Ty, Legal);
916       setOperationAction(ISD::FTRUNC, Ty, Legal);
917       setOperationAction(ISD::FNEARBYINT, Ty, Legal);
918       setOperationAction(ISD::FRINT, Ty, Legal);
919     }
920   }
921   // We have target-specific dag combine patterns for the following nodes:
922   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
923   setTargetDAGCombine(ISD::ADD);
924   setTargetDAGCombine(ISD::SUB);
925   setTargetDAGCombine(ISD::MUL);
926   setTargetDAGCombine(ISD::AND);
927   setTargetDAGCombine(ISD::OR);
928   setTargetDAGCombine(ISD::XOR);
929
930   if (Subtarget->hasV6Ops())
931     setTargetDAGCombine(ISD::SRL);
932
933   setStackPointerRegisterToSaveRestore(ARM::SP);
934
935   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
936       !Subtarget->hasVFP2())
937     setSchedulingPreference(Sched::RegPressure);
938   else
939     setSchedulingPreference(Sched::Hybrid);
940
941   //// temporary - rewrite interface to use type
942   MaxStoresPerMemset = 8;
943   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
944   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
945   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
946   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
947   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
948
949   // On ARM arguments smaller than 4 bytes are extended, so all arguments
950   // are at least 4 bytes aligned.
951   setMinStackArgumentAlignment(4);
952
953   // Prefer likely predicted branches to selects on out-of-order cores.
954   PredictableSelectIsExpensive = Subtarget->isLikeA9();
955
956   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
957 }
958
959 // FIXME: It might make sense to define the representative register class as the
960 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
961 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
962 // SPR's representative would be DPR_VFP2. This should work well if register
963 // pressure tracking were modified such that a register use would increment the
964 // pressure of the register class's representative and all of it's super
965 // classes' representatives transitively. We have not implemented this because
966 // of the difficulty prior to coalescing of modeling operand register classes
967 // due to the common occurrence of cross class copies and subregister insertions
968 // and extractions.
969 std::pair<const TargetRegisterClass*, uint8_t>
970 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
971   const TargetRegisterClass *RRC = nullptr;
972   uint8_t Cost = 1;
973   switch (VT.SimpleTy) {
974   default:
975     return TargetLowering::findRepresentativeClass(VT);
976   // Use DPR as representative register class for all floating point
977   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
978   // the cost is 1 for both f32 and f64.
979   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
980   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
981     RRC = &ARM::DPRRegClass;
982     // When NEON is used for SP, only half of the register file is available
983     // because operations that define both SP and DP results will be constrained
984     // to the VFP2 class (D0-D15). We currently model this constraint prior to
985     // coalescing by double-counting the SP regs. See the FIXME above.
986     if (Subtarget->useNEONForSinglePrecisionFP())
987       Cost = 2;
988     break;
989   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
990   case MVT::v4f32: case MVT::v2f64:
991     RRC = &ARM::DPRRegClass;
992     Cost = 2;
993     break;
994   case MVT::v4i64:
995     RRC = &ARM::DPRRegClass;
996     Cost = 4;
997     break;
998   case MVT::v8i64:
999     RRC = &ARM::DPRRegClass;
1000     Cost = 8;
1001     break;
1002   }
1003   return std::make_pair(RRC, Cost);
1004 }
1005
1006 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1007   switch (Opcode) {
1008   default: return nullptr;
1009   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1010   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1011   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1012   case ARMISD::CALL:          return "ARMISD::CALL";
1013   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1014   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1015   case ARMISD::tCALL:         return "ARMISD::tCALL";
1016   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1017   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1018   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1019   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1020   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1021   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1022   case ARMISD::CMP:           return "ARMISD::CMP";
1023   case ARMISD::CMN:           return "ARMISD::CMN";
1024   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1025   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1026   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1027   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1028   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1029
1030   case ARMISD::CMOV:          return "ARMISD::CMOV";
1031
1032   case ARMISD::RBIT:          return "ARMISD::RBIT";
1033
1034   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
1035   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
1036   case ARMISD::SITOF:         return "ARMISD::SITOF";
1037   case ARMISD::UITOF:         return "ARMISD::UITOF";
1038
1039   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1040   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1041   case ARMISD::RRX:           return "ARMISD::RRX";
1042
1043   case ARMISD::ADDC:          return "ARMISD::ADDC";
1044   case ARMISD::ADDE:          return "ARMISD::ADDE";
1045   case ARMISD::SUBC:          return "ARMISD::SUBC";
1046   case ARMISD::SUBE:          return "ARMISD::SUBE";
1047
1048   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1049   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1050
1051   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1052   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
1053
1054   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1055
1056   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1057
1058   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1059
1060   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1061
1062   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1063
1064   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1065
1066   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1067   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1068   case ARMISD::VCGE:          return "ARMISD::VCGE";
1069   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1070   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1071   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1072   case ARMISD::VCGT:          return "ARMISD::VCGT";
1073   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1074   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1075   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1076   case ARMISD::VTST:          return "ARMISD::VTST";
1077
1078   case ARMISD::VSHL:          return "ARMISD::VSHL";
1079   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1080   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1081   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1082   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1083   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1084   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1085   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1086   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1087   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1088   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1089   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1090   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1091   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1092   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1093   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1094   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1095   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1096   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1097   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1098   case ARMISD::VDUP:          return "ARMISD::VDUP";
1099   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1100   case ARMISD::VEXT:          return "ARMISD::VEXT";
1101   case ARMISD::VREV64:        return "ARMISD::VREV64";
1102   case ARMISD::VREV32:        return "ARMISD::VREV32";
1103   case ARMISD::VREV16:        return "ARMISD::VREV16";
1104   case ARMISD::VZIP:          return "ARMISD::VZIP";
1105   case ARMISD::VUZP:          return "ARMISD::VUZP";
1106   case ARMISD::VTRN:          return "ARMISD::VTRN";
1107   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1108   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1109   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1110   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1111   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1112   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1113   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1114   case ARMISD::FMAX:          return "ARMISD::FMAX";
1115   case ARMISD::FMIN:          return "ARMISD::FMIN";
1116   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1117   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1118   case ARMISD::BFI:           return "ARMISD::BFI";
1119   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1120   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1121   case ARMISD::VBSL:          return "ARMISD::VBSL";
1122   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1123   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1124   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1125   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1126   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1127   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1128   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1129   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1130   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1131   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1132   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1133   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1134   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1135   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1136   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1137   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1138   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1139   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1140   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1141   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1142   }
1143 }
1144
1145 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1146   if (!VT.isVector()) return getPointerTy();
1147   return VT.changeVectorElementTypeToInteger();
1148 }
1149
1150 /// getRegClassFor - Return the register class that should be used for the
1151 /// specified value type.
1152 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1153   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1154   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1155   // load / store 4 to 8 consecutive D registers.
1156   if (Subtarget->hasNEON()) {
1157     if (VT == MVT::v4i64)
1158       return &ARM::QQPRRegClass;
1159     if (VT == MVT::v8i64)
1160       return &ARM::QQQQPRRegClass;
1161   }
1162   return TargetLowering::getRegClassFor(VT);
1163 }
1164
1165 // Create a fast isel object.
1166 FastISel *
1167 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1168                                   const TargetLibraryInfo *libInfo) const {
1169   return ARM::createFastISel(funcInfo, libInfo);
1170 }
1171
1172 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1173 /// be used for loads / stores from the global.
1174 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1175   return (Subtarget->isThumb1Only() ? 127 : 4095);
1176 }
1177
1178 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1179   unsigned NumVals = N->getNumValues();
1180   if (!NumVals)
1181     return Sched::RegPressure;
1182
1183   for (unsigned i = 0; i != NumVals; ++i) {
1184     EVT VT = N->getValueType(i);
1185     if (VT == MVT::Glue || VT == MVT::Other)
1186       continue;
1187     if (VT.isFloatingPoint() || VT.isVector())
1188       return Sched::ILP;
1189   }
1190
1191   if (!N->isMachineOpcode())
1192     return Sched::RegPressure;
1193
1194   // Load are scheduled for latency even if there instruction itinerary
1195   // is not available.
1196   const TargetInstrInfo *TII =
1197       getTargetMachine().getSubtargetImpl()->getInstrInfo();
1198   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1199
1200   if (MCID.getNumDefs() == 0)
1201     return Sched::RegPressure;
1202   if (!Itins->isEmpty() &&
1203       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1204     return Sched::ILP;
1205
1206   return Sched::RegPressure;
1207 }
1208
1209 //===----------------------------------------------------------------------===//
1210 // Lowering Code
1211 //===----------------------------------------------------------------------===//
1212
1213 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1214 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1215   switch (CC) {
1216   default: llvm_unreachable("Unknown condition code!");
1217   case ISD::SETNE:  return ARMCC::NE;
1218   case ISD::SETEQ:  return ARMCC::EQ;
1219   case ISD::SETGT:  return ARMCC::GT;
1220   case ISD::SETGE:  return ARMCC::GE;
1221   case ISD::SETLT:  return ARMCC::LT;
1222   case ISD::SETLE:  return ARMCC::LE;
1223   case ISD::SETUGT: return ARMCC::HI;
1224   case ISD::SETUGE: return ARMCC::HS;
1225   case ISD::SETULT: return ARMCC::LO;
1226   case ISD::SETULE: return ARMCC::LS;
1227   }
1228 }
1229
1230 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1231 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1232                         ARMCC::CondCodes &CondCode2) {
1233   CondCode2 = ARMCC::AL;
1234   switch (CC) {
1235   default: llvm_unreachable("Unknown FP condition!");
1236   case ISD::SETEQ:
1237   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1238   case ISD::SETGT:
1239   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1240   case ISD::SETGE:
1241   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1242   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1243   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1244   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1245   case ISD::SETO:   CondCode = ARMCC::VC; break;
1246   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1247   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1248   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1249   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1250   case ISD::SETLT:
1251   case ISD::SETULT: CondCode = ARMCC::LT; break;
1252   case ISD::SETLE:
1253   case ISD::SETULE: CondCode = ARMCC::LE; break;
1254   case ISD::SETNE:
1255   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1256   }
1257 }
1258
1259 //===----------------------------------------------------------------------===//
1260 //                      Calling Convention Implementation
1261 //===----------------------------------------------------------------------===//
1262
1263 #include "ARMGenCallingConv.inc"
1264
1265 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1266 /// account presence of floating point hardware and calling convention
1267 /// limitations, such as support for variadic functions.
1268 CallingConv::ID
1269 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1270                                            bool isVarArg) const {
1271   switch (CC) {
1272   default:
1273     llvm_unreachable("Unsupported calling convention");
1274   case CallingConv::ARM_AAPCS:
1275   case CallingConv::ARM_APCS:
1276   case CallingConv::GHC:
1277     return CC;
1278   case CallingConv::ARM_AAPCS_VFP:
1279     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1280   case CallingConv::C:
1281     if (!Subtarget->isAAPCS_ABI())
1282       return CallingConv::ARM_APCS;
1283     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1284              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1285              !isVarArg)
1286       return CallingConv::ARM_AAPCS_VFP;
1287     else
1288       return CallingConv::ARM_AAPCS;
1289   case CallingConv::Fast:
1290     if (!Subtarget->isAAPCS_ABI()) {
1291       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1292         return CallingConv::Fast;
1293       return CallingConv::ARM_APCS;
1294     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1295       return CallingConv::ARM_AAPCS_VFP;
1296     else
1297       return CallingConv::ARM_AAPCS;
1298   }
1299 }
1300
1301 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1302 /// CallingConvention.
1303 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1304                                                  bool Return,
1305                                                  bool isVarArg) const {
1306   switch (getEffectiveCallingConv(CC, isVarArg)) {
1307   default:
1308     llvm_unreachable("Unsupported calling convention");
1309   case CallingConv::ARM_APCS:
1310     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1311   case CallingConv::ARM_AAPCS:
1312     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1313   case CallingConv::ARM_AAPCS_VFP:
1314     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1315   case CallingConv::Fast:
1316     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1317   case CallingConv::GHC:
1318     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1319   }
1320 }
1321
1322 /// LowerCallResult - Lower the result values of a call into the
1323 /// appropriate copies out of appropriate physical registers.
1324 SDValue
1325 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1326                                    CallingConv::ID CallConv, bool isVarArg,
1327                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1328                                    SDLoc dl, SelectionDAG &DAG,
1329                                    SmallVectorImpl<SDValue> &InVals,
1330                                    bool isThisReturn, SDValue ThisVal) const {
1331
1332   // Assign locations to each value returned by this call.
1333   SmallVector<CCValAssign, 16> RVLocs;
1334   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1335                     *DAG.getContext(), Call);
1336   CCInfo.AnalyzeCallResult(Ins,
1337                            CCAssignFnForNode(CallConv, /* Return*/ true,
1338                                              isVarArg));
1339
1340   // Copy all of the result registers out of their specified physreg.
1341   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1342     CCValAssign VA = RVLocs[i];
1343
1344     // Pass 'this' value directly from the argument to return value, to avoid
1345     // reg unit interference
1346     if (i == 0 && isThisReturn) {
1347       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1348              "unexpected return calling convention register assignment");
1349       InVals.push_back(ThisVal);
1350       continue;
1351     }
1352
1353     SDValue Val;
1354     if (VA.needsCustom()) {
1355       // Handle f64 or half of a v2f64.
1356       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1357                                       InFlag);
1358       Chain = Lo.getValue(1);
1359       InFlag = Lo.getValue(2);
1360       VA = RVLocs[++i]; // skip ahead to next loc
1361       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1362                                       InFlag);
1363       Chain = Hi.getValue(1);
1364       InFlag = Hi.getValue(2);
1365       if (!Subtarget->isLittle())
1366         std::swap (Lo, Hi);
1367       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1368
1369       if (VA.getLocVT() == MVT::v2f64) {
1370         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1371         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1372                           DAG.getConstant(0, MVT::i32));
1373
1374         VA = RVLocs[++i]; // skip ahead to next loc
1375         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1376         Chain = Lo.getValue(1);
1377         InFlag = Lo.getValue(2);
1378         VA = RVLocs[++i]; // skip ahead to next loc
1379         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1380         Chain = Hi.getValue(1);
1381         InFlag = Hi.getValue(2);
1382         if (!Subtarget->isLittle())
1383           std::swap (Lo, Hi);
1384         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1385         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1386                           DAG.getConstant(1, MVT::i32));
1387       }
1388     } else {
1389       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1390                                InFlag);
1391       Chain = Val.getValue(1);
1392       InFlag = Val.getValue(2);
1393     }
1394
1395     switch (VA.getLocInfo()) {
1396     default: llvm_unreachable("Unknown loc info!");
1397     case CCValAssign::Full: break;
1398     case CCValAssign::BCvt:
1399       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1400       break;
1401     }
1402
1403     InVals.push_back(Val);
1404   }
1405
1406   return Chain;
1407 }
1408
1409 /// LowerMemOpCallTo - Store the argument to the stack.
1410 SDValue
1411 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1412                                     SDValue StackPtr, SDValue Arg,
1413                                     SDLoc dl, SelectionDAG &DAG,
1414                                     const CCValAssign &VA,
1415                                     ISD::ArgFlagsTy Flags) const {
1416   unsigned LocMemOffset = VA.getLocMemOffset();
1417   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1418   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1419   return DAG.getStore(Chain, dl, Arg, PtrOff,
1420                       MachinePointerInfo::getStack(LocMemOffset),
1421                       false, false, 0);
1422 }
1423
1424 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1425                                          SDValue Chain, SDValue &Arg,
1426                                          RegsToPassVector &RegsToPass,
1427                                          CCValAssign &VA, CCValAssign &NextVA,
1428                                          SDValue &StackPtr,
1429                                          SmallVectorImpl<SDValue> &MemOpChains,
1430                                          ISD::ArgFlagsTy Flags) const {
1431
1432   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1433                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1434   unsigned id = Subtarget->isLittle() ? 0 : 1;
1435   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1436
1437   if (NextVA.isRegLoc())
1438     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1439   else {
1440     assert(NextVA.isMemLoc());
1441     if (!StackPtr.getNode())
1442       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1443
1444     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1445                                            dl, DAG, NextVA,
1446                                            Flags));
1447   }
1448 }
1449
1450 /// LowerCall - Lowering a call into a callseq_start <-
1451 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1452 /// nodes.
1453 SDValue
1454 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1455                              SmallVectorImpl<SDValue> &InVals) const {
1456   SelectionDAG &DAG                     = CLI.DAG;
1457   SDLoc &dl                          = CLI.DL;
1458   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1459   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1460   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1461   SDValue Chain                         = CLI.Chain;
1462   SDValue Callee                        = CLI.Callee;
1463   bool &isTailCall                      = CLI.IsTailCall;
1464   CallingConv::ID CallConv              = CLI.CallConv;
1465   bool doesNotRet                       = CLI.DoesNotReturn;
1466   bool isVarArg                         = CLI.IsVarArg;
1467
1468   MachineFunction &MF = DAG.getMachineFunction();
1469   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1470   bool isThisReturn   = false;
1471   bool isSibCall      = false;
1472
1473   // Disable tail calls if they're not supported.
1474   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1475     isTailCall = false;
1476
1477   if (isTailCall) {
1478     // Check if it's really possible to do a tail call.
1479     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1480                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1481                                                    Outs, OutVals, Ins, DAG);
1482     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1483       report_fatal_error("failed to perform tail call elimination on a call "
1484                          "site marked musttail");
1485     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1486     // detected sibcalls.
1487     if (isTailCall) {
1488       ++NumTailCalls;
1489       isSibCall = true;
1490     }
1491   }
1492
1493   // Analyze operands of the call, assigning locations to each operand.
1494   SmallVector<CCValAssign, 16> ArgLocs;
1495   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1496                     *DAG.getContext(), Call);
1497   CCInfo.AnalyzeCallOperands(Outs,
1498                              CCAssignFnForNode(CallConv, /* Return*/ false,
1499                                                isVarArg));
1500
1501   // Get a count of how many bytes are to be pushed on the stack.
1502   unsigned NumBytes = CCInfo.getNextStackOffset();
1503
1504   // For tail calls, memory operands are available in our caller's stack.
1505   if (isSibCall)
1506     NumBytes = 0;
1507
1508   // Adjust the stack pointer for the new arguments...
1509   // These operations are automatically eliminated by the prolog/epilog pass
1510   if (!isSibCall)
1511     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1512                                  dl);
1513
1514   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1515
1516   RegsToPassVector RegsToPass;
1517   SmallVector<SDValue, 8> MemOpChains;
1518
1519   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1520   // of tail call optimization, arguments are handled later.
1521   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1522        i != e;
1523        ++i, ++realArgIdx) {
1524     CCValAssign &VA = ArgLocs[i];
1525     SDValue Arg = OutVals[realArgIdx];
1526     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1527     bool isByVal = Flags.isByVal();
1528
1529     // Promote the value if needed.
1530     switch (VA.getLocInfo()) {
1531     default: llvm_unreachable("Unknown loc info!");
1532     case CCValAssign::Full: break;
1533     case CCValAssign::SExt:
1534       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1535       break;
1536     case CCValAssign::ZExt:
1537       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1538       break;
1539     case CCValAssign::AExt:
1540       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1541       break;
1542     case CCValAssign::BCvt:
1543       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1544       break;
1545     }
1546
1547     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1548     if (VA.needsCustom()) {
1549       if (VA.getLocVT() == MVT::v2f64) {
1550         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1551                                   DAG.getConstant(0, MVT::i32));
1552         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1553                                   DAG.getConstant(1, MVT::i32));
1554
1555         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1556                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1557
1558         VA = ArgLocs[++i]; // skip ahead to next loc
1559         if (VA.isRegLoc()) {
1560           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1561                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1562         } else {
1563           assert(VA.isMemLoc());
1564
1565           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1566                                                  dl, DAG, VA, Flags));
1567         }
1568       } else {
1569         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1570                          StackPtr, MemOpChains, Flags);
1571       }
1572     } else if (VA.isRegLoc()) {
1573       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1574         assert(VA.getLocVT() == MVT::i32 &&
1575                "unexpected calling convention register assignment");
1576         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1577                "unexpected use of 'returned'");
1578         isThisReturn = true;
1579       }
1580       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1581     } else if (isByVal) {
1582       assert(VA.isMemLoc());
1583       unsigned offset = 0;
1584
1585       // True if this byval aggregate will be split between registers
1586       // and memory.
1587       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1588       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1589
1590       if (CurByValIdx < ByValArgsCount) {
1591
1592         unsigned RegBegin, RegEnd;
1593         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1594
1595         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1596         unsigned int i, j;
1597         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1598           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1599           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1600           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1601                                      MachinePointerInfo(),
1602                                      false, false, false,
1603                                      DAG.InferPtrAlignment(AddArg));
1604           MemOpChains.push_back(Load.getValue(1));
1605           RegsToPass.push_back(std::make_pair(j, Load));
1606         }
1607
1608         // If parameter size outsides register area, "offset" value
1609         // helps us to calculate stack slot for remained part properly.
1610         offset = RegEnd - RegBegin;
1611
1612         CCInfo.nextInRegsParam();
1613       }
1614
1615       if (Flags.getByValSize() > 4*offset) {
1616         unsigned LocMemOffset = VA.getLocMemOffset();
1617         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1618         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1619                                   StkPtrOff);
1620         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1621         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1622         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1623                                            MVT::i32);
1624         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1625
1626         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1627         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1628         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1629                                           Ops));
1630       }
1631     } else if (!isSibCall) {
1632       assert(VA.isMemLoc());
1633
1634       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1635                                              dl, DAG, VA, Flags));
1636     }
1637   }
1638
1639   if (!MemOpChains.empty())
1640     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1641
1642   // Build a sequence of copy-to-reg nodes chained together with token chain
1643   // and flag operands which copy the outgoing args into the appropriate regs.
1644   SDValue InFlag;
1645   // Tail call byval lowering might overwrite argument registers so in case of
1646   // tail call optimization the copies to registers are lowered later.
1647   if (!isTailCall)
1648     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1649       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1650                                RegsToPass[i].second, InFlag);
1651       InFlag = Chain.getValue(1);
1652     }
1653
1654   // For tail calls lower the arguments to the 'real' stack slot.
1655   if (isTailCall) {
1656     // Force all the incoming stack arguments to be loaded from the stack
1657     // before any new outgoing arguments are stored to the stack, because the
1658     // outgoing stack slots may alias the incoming argument stack slots, and
1659     // the alias isn't otherwise explicit. This is slightly more conservative
1660     // than necessary, because it means that each store effectively depends
1661     // on every argument instead of just those arguments it would clobber.
1662
1663     // Do not flag preceding copytoreg stuff together with the following stuff.
1664     InFlag = SDValue();
1665     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1666       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1667                                RegsToPass[i].second, InFlag);
1668       InFlag = Chain.getValue(1);
1669     }
1670     InFlag = SDValue();
1671   }
1672
1673   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1674   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1675   // node so that legalize doesn't hack it.
1676   bool isDirect = false;
1677   bool isARMFunc = false;
1678   bool isLocalARMFunc = false;
1679   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1680
1681   if (EnableARMLongCalls) {
1682     assert((Subtarget->isTargetWindows() ||
1683             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1684            "long-calls with non-static relocation model!");
1685     // Handle a global address or an external symbol. If it's not one of
1686     // those, the target's already in a register, so we don't need to do
1687     // anything extra.
1688     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1689       const GlobalValue *GV = G->getGlobal();
1690       // Create a constant pool entry for the callee address
1691       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1692       ARMConstantPoolValue *CPV =
1693         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1694
1695       // Get the address of the callee into a register
1696       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1697       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1698       Callee = DAG.getLoad(getPointerTy(), dl,
1699                            DAG.getEntryNode(), CPAddr,
1700                            MachinePointerInfo::getConstantPool(),
1701                            false, false, false, 0);
1702     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1703       const char *Sym = S->getSymbol();
1704
1705       // Create a constant pool entry for the callee address
1706       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1707       ARMConstantPoolValue *CPV =
1708         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1709                                       ARMPCLabelIndex, 0);
1710       // Get the address of the callee into a register
1711       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1712       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1713       Callee = DAG.getLoad(getPointerTy(), dl,
1714                            DAG.getEntryNode(), CPAddr,
1715                            MachinePointerInfo::getConstantPool(),
1716                            false, false, false, 0);
1717     }
1718   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1719     const GlobalValue *GV = G->getGlobal();
1720     isDirect = true;
1721     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1722     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1723                    getTargetMachine().getRelocationModel() != Reloc::Static;
1724     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1725     // ARM call to a local ARM function is predicable.
1726     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1727     // tBX takes a register source operand.
1728     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1729       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1730       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1731                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
1732                                                       0, ARMII::MO_NONLAZY));
1733       Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
1734                            MachinePointerInfo::getGOT(), false, false, true, 0);
1735     } else if (Subtarget->isTargetCOFF()) {
1736       assert(Subtarget->isTargetWindows() &&
1737              "Windows is the only supported COFF target");
1738       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1739                                  ? ARMII::MO_DLLIMPORT
1740                                  : ARMII::MO_NO_FLAG;
1741       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1742                                           TargetFlags);
1743       if (GV->hasDLLImportStorageClass())
1744         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1745                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1746                                          Callee), MachinePointerInfo::getGOT(),
1747                              false, false, false, 0);
1748     } else {
1749       // On ELF targets for PIC code, direct calls should go through the PLT
1750       unsigned OpFlags = 0;
1751       if (Subtarget->isTargetELF() &&
1752           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1753         OpFlags = ARMII::MO_PLT;
1754       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1755     }
1756   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1757     isDirect = true;
1758     bool isStub = Subtarget->isTargetMachO() &&
1759                   getTargetMachine().getRelocationModel() != Reloc::Static;
1760     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1761     // tBX takes a register source operand.
1762     const char *Sym = S->getSymbol();
1763     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1764       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1765       ARMConstantPoolValue *CPV =
1766         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1767                                       ARMPCLabelIndex, 4);
1768       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1769       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1770       Callee = DAG.getLoad(getPointerTy(), dl,
1771                            DAG.getEntryNode(), CPAddr,
1772                            MachinePointerInfo::getConstantPool(),
1773                            false, false, false, 0);
1774       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1775       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1776                            getPointerTy(), Callee, PICLabel);
1777     } else {
1778       unsigned OpFlags = 0;
1779       // On ELF targets for PIC code, direct calls should go through the PLT
1780       if (Subtarget->isTargetELF() &&
1781                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1782         OpFlags = ARMII::MO_PLT;
1783       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1784     }
1785   }
1786
1787   // FIXME: handle tail calls differently.
1788   unsigned CallOpc;
1789   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1790       AttributeSet::FunctionIndex, Attribute::MinSize);
1791   if (Subtarget->isThumb()) {
1792     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1793       CallOpc = ARMISD::CALL_NOLINK;
1794     else
1795       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1796   } else {
1797     if (!isDirect && !Subtarget->hasV5TOps())
1798       CallOpc = ARMISD::CALL_NOLINK;
1799     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1800                // Emit regular call when code size is the priority
1801                !HasMinSizeAttr)
1802       // "mov lr, pc; b _foo" to avoid confusing the RSP
1803       CallOpc = ARMISD::CALL_NOLINK;
1804     else
1805       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1806   }
1807
1808   std::vector<SDValue> Ops;
1809   Ops.push_back(Chain);
1810   Ops.push_back(Callee);
1811
1812   // Add argument registers to the end of the list so that they are known live
1813   // into the call.
1814   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1815     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1816                                   RegsToPass[i].second.getValueType()));
1817
1818   // Add a register mask operand representing the call-preserved registers.
1819   if (!isTailCall) {
1820     const uint32_t *Mask;
1821     const TargetRegisterInfo *TRI =
1822         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1823     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1824     if (isThisReturn) {
1825       // For 'this' returns, use the R0-preserving mask if applicable
1826       Mask = ARI->getThisReturnPreservedMask(CallConv);
1827       if (!Mask) {
1828         // Set isThisReturn to false if the calling convention is not one that
1829         // allows 'returned' to be modeled in this way, so LowerCallResult does
1830         // not try to pass 'this' straight through
1831         isThisReturn = false;
1832         Mask = ARI->getCallPreservedMask(CallConv);
1833       }
1834     } else
1835       Mask = ARI->getCallPreservedMask(CallConv);
1836
1837     assert(Mask && "Missing call preserved mask for calling convention");
1838     Ops.push_back(DAG.getRegisterMask(Mask));
1839   }
1840
1841   if (InFlag.getNode())
1842     Ops.push_back(InFlag);
1843
1844   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1845   if (isTailCall)
1846     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1847
1848   // Returns a chain and a flag for retval copy to use.
1849   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1850   InFlag = Chain.getValue(1);
1851
1852   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1853                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1854   if (!Ins.empty())
1855     InFlag = Chain.getValue(1);
1856
1857   // Handle result values, copying them out of physregs into vregs that we
1858   // return.
1859   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1860                          InVals, isThisReturn,
1861                          isThisReturn ? OutVals[0] : SDValue());
1862 }
1863
1864 /// HandleByVal - Every parameter *after* a byval parameter is passed
1865 /// on the stack.  Remember the next parameter register to allocate,
1866 /// and then confiscate the rest of the parameter registers to insure
1867 /// this.
1868 void
1869 ARMTargetLowering::HandleByVal(
1870     CCState *State, unsigned &size, unsigned Align) const {
1871   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1872   assert((State->getCallOrPrologue() == Prologue ||
1873           State->getCallOrPrologue() == Call) &&
1874          "unhandled ParmContext");
1875
1876   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1877     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1878       unsigned AlignInRegs = Align / 4;
1879       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1880       for (unsigned i = 0; i < Waste; ++i)
1881         reg = State->AllocateReg(GPRArgRegs, 4);
1882     }
1883     if (reg != 0) {
1884       unsigned excess = 4 * (ARM::R4 - reg);
1885
1886       // Special case when NSAA != SP and parameter size greater than size of
1887       // all remained GPR regs. In that case we can't split parameter, we must
1888       // send it to stack. We also must set NCRN to R4, so waste all
1889       // remained registers.
1890       const unsigned NSAAOffset = State->getNextStackOffset();
1891       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1892         while (State->AllocateReg(GPRArgRegs, 4))
1893           ;
1894         return;
1895       }
1896
1897       // First register for byval parameter is the first register that wasn't
1898       // allocated before this method call, so it would be "reg".
1899       // If parameter is small enough to be saved in range [reg, r4), then
1900       // the end (first after last) register would be reg + param-size-in-regs,
1901       // else parameter would be splitted between registers and stack,
1902       // end register would be r4 in this case.
1903       unsigned ByValRegBegin = reg;
1904       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1905       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1906       // Note, first register is allocated in the beginning of function already,
1907       // allocate remained amount of registers we need.
1908       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1909         State->AllocateReg(GPRArgRegs, 4);
1910       // A byval parameter that is split between registers and memory needs its
1911       // size truncated here.
1912       // In the case where the entire structure fits in registers, we set the
1913       // size in memory to zero.
1914       if (size < excess)
1915         size = 0;
1916       else
1917         size -= excess;
1918     }
1919   }
1920 }
1921
1922 /// MatchingStackOffset - Return true if the given stack call argument is
1923 /// already available in the same position (relatively) of the caller's
1924 /// incoming argument stack.
1925 static
1926 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1927                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1928                          const TargetInstrInfo *TII) {
1929   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1930   int FI = INT_MAX;
1931   if (Arg.getOpcode() == ISD::CopyFromReg) {
1932     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1933     if (!TargetRegisterInfo::isVirtualRegister(VR))
1934       return false;
1935     MachineInstr *Def = MRI->getVRegDef(VR);
1936     if (!Def)
1937       return false;
1938     if (!Flags.isByVal()) {
1939       if (!TII->isLoadFromStackSlot(Def, FI))
1940         return false;
1941     } else {
1942       return false;
1943     }
1944   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1945     if (Flags.isByVal())
1946       // ByVal argument is passed in as a pointer but it's now being
1947       // dereferenced. e.g.
1948       // define @foo(%struct.X* %A) {
1949       //   tail call @bar(%struct.X* byval %A)
1950       // }
1951       return false;
1952     SDValue Ptr = Ld->getBasePtr();
1953     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1954     if (!FINode)
1955       return false;
1956     FI = FINode->getIndex();
1957   } else
1958     return false;
1959
1960   assert(FI != INT_MAX);
1961   if (!MFI->isFixedObjectIndex(FI))
1962     return false;
1963   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1964 }
1965
1966 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1967 /// for tail call optimization. Targets which want to do tail call
1968 /// optimization should implement this function.
1969 bool
1970 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1971                                                      CallingConv::ID CalleeCC,
1972                                                      bool isVarArg,
1973                                                      bool isCalleeStructRet,
1974                                                      bool isCallerStructRet,
1975                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                     const SmallVectorImpl<SDValue> &OutVals,
1977                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1978                                                      SelectionDAG& DAG) const {
1979   const Function *CallerF = DAG.getMachineFunction().getFunction();
1980   CallingConv::ID CallerCC = CallerF->getCallingConv();
1981   bool CCMatch = CallerCC == CalleeCC;
1982
1983   // Look for obvious safe cases to perform tail call optimization that do not
1984   // require ABI changes. This is what gcc calls sibcall.
1985
1986   // Do not sibcall optimize vararg calls unless the call site is not passing
1987   // any arguments.
1988   if (isVarArg && !Outs.empty())
1989     return false;
1990
1991   // Exception-handling functions need a special set of instructions to indicate
1992   // a return to the hardware. Tail-calling another function would probably
1993   // break this.
1994   if (CallerF->hasFnAttribute("interrupt"))
1995     return false;
1996
1997   // Also avoid sibcall optimization if either caller or callee uses struct
1998   // return semantics.
1999   if (isCalleeStructRet || isCallerStructRet)
2000     return false;
2001
2002   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
2003   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2004   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2005   // support in the assembler and linker to be used. This would need to be
2006   // fixed to fully support tail calls in Thumb1.
2007   //
2008   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2009   // LR.  This means if we need to reload LR, it takes an extra instructions,
2010   // which outweighs the value of the tail call; but here we don't know yet
2011   // whether LR is going to be used.  Probably the right approach is to
2012   // generate the tail call here and turn it back into CALL/RET in
2013   // emitEpilogue if LR is used.
2014
2015   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2016   // but we need to make sure there are enough registers; the only valid
2017   // registers are the 4 used for parameters.  We don't currently do this
2018   // case.
2019   if (Subtarget->isThumb1Only())
2020     return false;
2021
2022   // Externally-defined functions with weak linkage should not be
2023   // tail-called on ARM when the OS does not support dynamic
2024   // pre-emption of symbols, as the AAELF spec requires normal calls
2025   // to undefined weak functions to be replaced with a NOP or jump to the
2026   // next instruction. The behaviour of branch instructions in this
2027   // situation (as used for tail calls) is implementation-defined, so we
2028   // cannot rely on the linker replacing the tail call with a return.
2029   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2030     const GlobalValue *GV = G->getGlobal();
2031     if (GV->hasExternalWeakLinkage())
2032       return false;
2033   }
2034
2035   // If the calling conventions do not match, then we'd better make sure the
2036   // results are returned in the same way as what the caller expects.
2037   if (!CCMatch) {
2038     SmallVector<CCValAssign, 16> RVLocs1;
2039     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2040                        *DAG.getContext(), Call);
2041     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2042
2043     SmallVector<CCValAssign, 16> RVLocs2;
2044     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2045                        *DAG.getContext(), Call);
2046     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2047
2048     if (RVLocs1.size() != RVLocs2.size())
2049       return false;
2050     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2051       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2052         return false;
2053       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2054         return false;
2055       if (RVLocs1[i].isRegLoc()) {
2056         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2057           return false;
2058       } else {
2059         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2060           return false;
2061       }
2062     }
2063   }
2064
2065   // If Caller's vararg or byval argument has been split between registers and
2066   // stack, do not perform tail call, since part of the argument is in caller's
2067   // local frame.
2068   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2069                                       getInfo<ARMFunctionInfo>();
2070   if (AFI_Caller->getArgRegsSaveSize())
2071     return false;
2072
2073   // If the callee takes no arguments then go on to check the results of the
2074   // call.
2075   if (!Outs.empty()) {
2076     // Check if stack adjustment is needed. For now, do not do this if any
2077     // argument is passed on the stack.
2078     SmallVector<CCValAssign, 16> ArgLocs;
2079     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2080                       *DAG.getContext(), Call);
2081     CCInfo.AnalyzeCallOperands(Outs,
2082                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2083     if (CCInfo.getNextStackOffset()) {
2084       MachineFunction &MF = DAG.getMachineFunction();
2085
2086       // Check if the arguments are already laid out in the right way as
2087       // the caller's fixed stack objects.
2088       MachineFrameInfo *MFI = MF.getFrameInfo();
2089       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2090       const TargetInstrInfo *TII =
2091           getTargetMachine().getSubtargetImpl()->getInstrInfo();
2092       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2093            i != e;
2094            ++i, ++realArgIdx) {
2095         CCValAssign &VA = ArgLocs[i];
2096         EVT RegVT = VA.getLocVT();
2097         SDValue Arg = OutVals[realArgIdx];
2098         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2099         if (VA.getLocInfo() == CCValAssign::Indirect)
2100           return false;
2101         if (VA.needsCustom()) {
2102           // f64 and vector types are split into multiple registers or
2103           // register/stack-slot combinations.  The types will not match
2104           // the registers; give up on memory f64 refs until we figure
2105           // out what to do about this.
2106           if (!VA.isRegLoc())
2107             return false;
2108           if (!ArgLocs[++i].isRegLoc())
2109             return false;
2110           if (RegVT == MVT::v2f64) {
2111             if (!ArgLocs[++i].isRegLoc())
2112               return false;
2113             if (!ArgLocs[++i].isRegLoc())
2114               return false;
2115           }
2116         } else if (!VA.isRegLoc()) {
2117           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2118                                    MFI, MRI, TII))
2119             return false;
2120         }
2121       }
2122     }
2123   }
2124
2125   return true;
2126 }
2127
2128 bool
2129 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2130                                   MachineFunction &MF, bool isVarArg,
2131                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2132                                   LLVMContext &Context) const {
2133   SmallVector<CCValAssign, 16> RVLocs;
2134   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2135   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2136                                                     isVarArg));
2137 }
2138
2139 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2140                                     SDLoc DL, SelectionDAG &DAG) {
2141   const MachineFunction &MF = DAG.getMachineFunction();
2142   const Function *F = MF.getFunction();
2143
2144   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2145
2146   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2147   // version of the "preferred return address". These offsets affect the return
2148   // instruction if this is a return from PL1 without hypervisor extensions.
2149   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2150   //    SWI:     0      "subs pc, lr, #0"
2151   //    ABORT:   +4     "subs pc, lr, #4"
2152   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2153   // UNDEF varies depending on where the exception came from ARM or Thumb
2154   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2155
2156   int64_t LROffset;
2157   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2158       IntKind == "ABORT")
2159     LROffset = 4;
2160   else if (IntKind == "SWI" || IntKind == "UNDEF")
2161     LROffset = 0;
2162   else
2163     report_fatal_error("Unsupported interrupt attribute. If present, value "
2164                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2165
2166   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2167
2168   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2169 }
2170
2171 SDValue
2172 ARMTargetLowering::LowerReturn(SDValue Chain,
2173                                CallingConv::ID CallConv, bool isVarArg,
2174                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2175                                const SmallVectorImpl<SDValue> &OutVals,
2176                                SDLoc dl, SelectionDAG &DAG) const {
2177
2178   // CCValAssign - represent the assignment of the return value to a location.
2179   SmallVector<CCValAssign, 16> RVLocs;
2180
2181   // CCState - Info about the registers and stack slots.
2182   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2183                     *DAG.getContext(), Call);
2184
2185   // Analyze outgoing return values.
2186   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2187                                                isVarArg));
2188
2189   SDValue Flag;
2190   SmallVector<SDValue, 4> RetOps;
2191   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2192   bool isLittleEndian = Subtarget->isLittle();
2193
2194   MachineFunction &MF = DAG.getMachineFunction();
2195   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2196   AFI->setReturnRegsCount(RVLocs.size());
2197
2198   // Copy the result values into the output registers.
2199   for (unsigned i = 0, realRVLocIdx = 0;
2200        i != RVLocs.size();
2201        ++i, ++realRVLocIdx) {
2202     CCValAssign &VA = RVLocs[i];
2203     assert(VA.isRegLoc() && "Can only return in registers!");
2204
2205     SDValue Arg = OutVals[realRVLocIdx];
2206
2207     switch (VA.getLocInfo()) {
2208     default: llvm_unreachable("Unknown loc info!");
2209     case CCValAssign::Full: break;
2210     case CCValAssign::BCvt:
2211       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2212       break;
2213     }
2214
2215     if (VA.needsCustom()) {
2216       if (VA.getLocVT() == MVT::v2f64) {
2217         // Extract the first half and return it in two registers.
2218         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2219                                    DAG.getConstant(0, MVT::i32));
2220         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2221                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2222
2223         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2224                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2225                                  Flag);
2226         Flag = Chain.getValue(1);
2227         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2228         VA = RVLocs[++i]; // skip ahead to next loc
2229         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2230                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2231                                  Flag);
2232         Flag = Chain.getValue(1);
2233         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2234         VA = RVLocs[++i]; // skip ahead to next loc
2235
2236         // Extract the 2nd half and fall through to handle it as an f64 value.
2237         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2238                           DAG.getConstant(1, MVT::i32));
2239       }
2240       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2241       // available.
2242       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2243                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2244       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2245                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2246                                Flag);
2247       Flag = Chain.getValue(1);
2248       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2249       VA = RVLocs[++i]; // skip ahead to next loc
2250       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2251                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2252                                Flag);
2253     } else
2254       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2255
2256     // Guarantee that all emitted copies are
2257     // stuck together, avoiding something bad.
2258     Flag = Chain.getValue(1);
2259     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2260   }
2261
2262   // Update chain and glue.
2263   RetOps[0] = Chain;
2264   if (Flag.getNode())
2265     RetOps.push_back(Flag);
2266
2267   // CPUs which aren't M-class use a special sequence to return from
2268   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2269   // though we use "subs pc, lr, #N").
2270   //
2271   // M-class CPUs actually use a normal return sequence with a special
2272   // (hardware-provided) value in LR, so the normal code path works.
2273   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2274       !Subtarget->isMClass()) {
2275     if (Subtarget->isThumb1Only())
2276       report_fatal_error("interrupt attribute is not supported in Thumb1");
2277     return LowerInterruptReturn(RetOps, dl, DAG);
2278   }
2279
2280   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2281 }
2282
2283 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2284   if (N->getNumValues() != 1)
2285     return false;
2286   if (!N->hasNUsesOfValue(1, 0))
2287     return false;
2288
2289   SDValue TCChain = Chain;
2290   SDNode *Copy = *N->use_begin();
2291   if (Copy->getOpcode() == ISD::CopyToReg) {
2292     // If the copy has a glue operand, we conservatively assume it isn't safe to
2293     // perform a tail call.
2294     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2295       return false;
2296     TCChain = Copy->getOperand(0);
2297   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2298     SDNode *VMov = Copy;
2299     // f64 returned in a pair of GPRs.
2300     SmallPtrSet<SDNode*, 2> Copies;
2301     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2302          UI != UE; ++UI) {
2303       if (UI->getOpcode() != ISD::CopyToReg)
2304         return false;
2305       Copies.insert(*UI);
2306     }
2307     if (Copies.size() > 2)
2308       return false;
2309
2310     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2311          UI != UE; ++UI) {
2312       SDValue UseChain = UI->getOperand(0);
2313       if (Copies.count(UseChain.getNode()))
2314         // Second CopyToReg
2315         Copy = *UI;
2316       else
2317         // First CopyToReg
2318         TCChain = UseChain;
2319     }
2320   } else if (Copy->getOpcode() == ISD::BITCAST) {
2321     // f32 returned in a single GPR.
2322     if (!Copy->hasOneUse())
2323       return false;
2324     Copy = *Copy->use_begin();
2325     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2326       return false;
2327     TCChain = Copy->getOperand(0);
2328   } else {
2329     return false;
2330   }
2331
2332   bool HasRet = false;
2333   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2334        UI != UE; ++UI) {
2335     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2336         UI->getOpcode() != ARMISD::INTRET_FLAG)
2337       return false;
2338     HasRet = true;
2339   }
2340
2341   if (!HasRet)
2342     return false;
2343
2344   Chain = TCChain;
2345   return true;
2346 }
2347
2348 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2349   if (!Subtarget->supportsTailCall())
2350     return false;
2351
2352   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2353     return false;
2354
2355   return !Subtarget->isThumb1Only();
2356 }
2357
2358 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2359 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2360 // one of the above mentioned nodes. It has to be wrapped because otherwise
2361 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2362 // be used to form addressing mode. These wrapped nodes will be selected
2363 // into MOVi.
2364 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2365   EVT PtrVT = Op.getValueType();
2366   // FIXME there is no actual debug info here
2367   SDLoc dl(Op);
2368   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2369   SDValue Res;
2370   if (CP->isMachineConstantPoolEntry())
2371     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2372                                     CP->getAlignment());
2373   else
2374     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2375                                     CP->getAlignment());
2376   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2377 }
2378
2379 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2380   return MachineJumpTableInfo::EK_Inline;
2381 }
2382
2383 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2384                                              SelectionDAG &DAG) const {
2385   MachineFunction &MF = DAG.getMachineFunction();
2386   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2387   unsigned ARMPCLabelIndex = 0;
2388   SDLoc DL(Op);
2389   EVT PtrVT = getPointerTy();
2390   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2391   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2392   SDValue CPAddr;
2393   if (RelocM == Reloc::Static) {
2394     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2395   } else {
2396     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2397     ARMPCLabelIndex = AFI->createPICLabelUId();
2398     ARMConstantPoolValue *CPV =
2399       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2400                                       ARMCP::CPBlockAddress, PCAdj);
2401     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2402   }
2403   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2404   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2405                                MachinePointerInfo::getConstantPool(),
2406                                false, false, false, 0);
2407   if (RelocM == Reloc::Static)
2408     return Result;
2409   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2410   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2411 }
2412
2413 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2414 SDValue
2415 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2416                                                  SelectionDAG &DAG) const {
2417   SDLoc dl(GA);
2418   EVT PtrVT = getPointerTy();
2419   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2420   MachineFunction &MF = DAG.getMachineFunction();
2421   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2422   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2423   ARMConstantPoolValue *CPV =
2424     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2425                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2426   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2428   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2429                          MachinePointerInfo::getConstantPool(),
2430                          false, false, false, 0);
2431   SDValue Chain = Argument.getValue(1);
2432
2433   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2434   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2435
2436   // call __tls_get_addr.
2437   ArgListTy Args;
2438   ArgListEntry Entry;
2439   Entry.Node = Argument;
2440   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2441   Args.push_back(Entry);
2442
2443   // FIXME: is there useful debug info available here?
2444   TargetLowering::CallLoweringInfo CLI(DAG);
2445   CLI.setDebugLoc(dl).setChain(Chain)
2446     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2447                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2448                0);
2449
2450   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2451   return CallResult.first;
2452 }
2453
2454 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2455 // "local exec" model.
2456 SDValue
2457 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2458                                         SelectionDAG &DAG,
2459                                         TLSModel::Model model) const {
2460   const GlobalValue *GV = GA->getGlobal();
2461   SDLoc dl(GA);
2462   SDValue Offset;
2463   SDValue Chain = DAG.getEntryNode();
2464   EVT PtrVT = getPointerTy();
2465   // Get the Thread Pointer
2466   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2467
2468   if (model == TLSModel::InitialExec) {
2469     MachineFunction &MF = DAG.getMachineFunction();
2470     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2471     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2472     // Initial exec model.
2473     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2474     ARMConstantPoolValue *CPV =
2475       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2476                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2477                                       true);
2478     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2479     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2480     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2481                          MachinePointerInfo::getConstantPool(),
2482                          false, false, false, 0);
2483     Chain = Offset.getValue(1);
2484
2485     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2486     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2487
2488     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2489                          MachinePointerInfo::getConstantPool(),
2490                          false, false, false, 0);
2491   } else {
2492     // local exec model
2493     assert(model == TLSModel::LocalExec);
2494     ARMConstantPoolValue *CPV =
2495       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2496     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2497     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2498     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2499                          MachinePointerInfo::getConstantPool(),
2500                          false, false, false, 0);
2501   }
2502
2503   // The address of the thread local variable is the add of the thread
2504   // pointer with the offset of the variable.
2505   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2506 }
2507
2508 SDValue
2509 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2510   // TODO: implement the "local dynamic" model
2511   assert(Subtarget->isTargetELF() &&
2512          "TLS not implemented for non-ELF targets");
2513   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2514
2515   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2516
2517   switch (model) {
2518     case TLSModel::GeneralDynamic:
2519     case TLSModel::LocalDynamic:
2520       return LowerToTLSGeneralDynamicModel(GA, DAG);
2521     case TLSModel::InitialExec:
2522     case TLSModel::LocalExec:
2523       return LowerToTLSExecModels(GA, DAG, model);
2524   }
2525   llvm_unreachable("bogus TLS model");
2526 }
2527
2528 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2529                                                  SelectionDAG &DAG) const {
2530   EVT PtrVT = getPointerTy();
2531   SDLoc dl(Op);
2532   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2533   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2534     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2535     ARMConstantPoolValue *CPV =
2536       ARMConstantPoolConstant::Create(GV,
2537                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2538     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2539     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2540     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2541                                  CPAddr,
2542                                  MachinePointerInfo::getConstantPool(),
2543                                  false, false, false, 0);
2544     SDValue Chain = Result.getValue(1);
2545     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2546     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2547     if (!UseGOTOFF)
2548       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2549                            MachinePointerInfo::getGOT(),
2550                            false, false, false, 0);
2551     return Result;
2552   }
2553
2554   // If we have T2 ops, we can materialize the address directly via movt/movw
2555   // pair. This is always cheaper.
2556   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2557     ++NumMovwMovt;
2558     // FIXME: Once remat is capable of dealing with instructions with register
2559     // operands, expand this into two nodes.
2560     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2561                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2562   } else {
2563     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2564     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2565     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2566                        MachinePointerInfo::getConstantPool(),
2567                        false, false, false, 0);
2568   }
2569 }
2570
2571 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2572                                                     SelectionDAG &DAG) const {
2573   EVT PtrVT = getPointerTy();
2574   SDLoc dl(Op);
2575   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2576   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2577
2578   if (Subtarget->useMovt(DAG.getMachineFunction()))
2579     ++NumMovwMovt;
2580
2581   // FIXME: Once remat is capable of dealing with instructions with register
2582   // operands, expand this into multiple nodes
2583   unsigned Wrapper =
2584       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2585
2586   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2587   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2588
2589   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2590     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2591                          MachinePointerInfo::getGOT(), false, false, false, 0);
2592   return Result;
2593 }
2594
2595 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2596                                                      SelectionDAG &DAG) const {
2597   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2598   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2599          "Windows on ARM expects to use movw/movt");
2600
2601   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2602   const ARMII::TOF TargetFlags =
2603     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2604   EVT PtrVT = getPointerTy();
2605   SDValue Result;
2606   SDLoc DL(Op);
2607
2608   ++NumMovwMovt;
2609
2610   // FIXME: Once remat is capable of dealing with instructions with register
2611   // operands, expand this into two nodes.
2612   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2613                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2614                                                   TargetFlags));
2615   if (GV->hasDLLImportStorageClass())
2616     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2617                          MachinePointerInfo::getGOT(), false, false, false, 0);
2618   return Result;
2619 }
2620
2621 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2622                                                     SelectionDAG &DAG) const {
2623   assert(Subtarget->isTargetELF() &&
2624          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2625   MachineFunction &MF = DAG.getMachineFunction();
2626   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2627   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2628   EVT PtrVT = getPointerTy();
2629   SDLoc dl(Op);
2630   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2631   ARMConstantPoolValue *CPV =
2632     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2633                                   ARMPCLabelIndex, PCAdj);
2634   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2635   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2636   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2637                                MachinePointerInfo::getConstantPool(),
2638                                false, false, false, 0);
2639   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2640   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2641 }
2642
2643 SDValue
2644 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2645   SDLoc dl(Op);
2646   SDValue Val = DAG.getConstant(0, MVT::i32);
2647   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2648                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2649                      Op.getOperand(1), Val);
2650 }
2651
2652 SDValue
2653 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2654   SDLoc dl(Op);
2655   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2656                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2657 }
2658
2659 SDValue
2660 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2661                                           const ARMSubtarget *Subtarget) const {
2662   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2663   SDLoc dl(Op);
2664   switch (IntNo) {
2665   default: return SDValue();    // Don't custom lower most intrinsics.
2666   case Intrinsic::arm_rbit: {
2667     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2668            "RBIT intrinsic must have i32 type!");
2669     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2670   }
2671   case Intrinsic::arm_thread_pointer: {
2672     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2673     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2674   }
2675   case Intrinsic::eh_sjlj_lsda: {
2676     MachineFunction &MF = DAG.getMachineFunction();
2677     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2678     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2679     EVT PtrVT = getPointerTy();
2680     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2681     SDValue CPAddr;
2682     unsigned PCAdj = (RelocM != Reloc::PIC_)
2683       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2684     ARMConstantPoolValue *CPV =
2685       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2686                                       ARMCP::CPLSDA, PCAdj);
2687     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2688     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2689     SDValue Result =
2690       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2691                   MachinePointerInfo::getConstantPool(),
2692                   false, false, false, 0);
2693
2694     if (RelocM == Reloc::PIC_) {
2695       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2696       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2697     }
2698     return Result;
2699   }
2700   case Intrinsic::arm_neon_vmulls:
2701   case Intrinsic::arm_neon_vmullu: {
2702     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2703       ? ARMISD::VMULLs : ARMISD::VMULLu;
2704     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2705                        Op.getOperand(1), Op.getOperand(2));
2706   }
2707   }
2708 }
2709
2710 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2711                                  const ARMSubtarget *Subtarget) {
2712   // FIXME: handle "fence singlethread" more efficiently.
2713   SDLoc dl(Op);
2714   if (!Subtarget->hasDataBarrier()) {
2715     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2716     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2717     // here.
2718     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2719            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2720     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2721                        DAG.getConstant(0, MVT::i32));
2722   }
2723
2724   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2725   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2726   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2727   if (Subtarget->isMClass()) {
2728     // Only a full system barrier exists in the M-class architectures.
2729     Domain = ARM_MB::SY;
2730   } else if (Subtarget->isSwift() && Ord == Release) {
2731     // Swift happens to implement ISHST barriers in a way that's compatible with
2732     // Release semantics but weaker than ISH so we'd be fools not to use
2733     // it. Beware: other processors probably don't!
2734     Domain = ARM_MB::ISHST;
2735   }
2736
2737   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2738                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2739                      DAG.getConstant(Domain, MVT::i32));
2740 }
2741
2742 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2743                              const ARMSubtarget *Subtarget) {
2744   // ARM pre v5TE and Thumb1 does not have preload instructions.
2745   if (!(Subtarget->isThumb2() ||
2746         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2747     // Just preserve the chain.
2748     return Op.getOperand(0);
2749
2750   SDLoc dl(Op);
2751   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2752   if (!isRead &&
2753       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2754     // ARMv7 with MP extension has PLDW.
2755     return Op.getOperand(0);
2756
2757   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2758   if (Subtarget->isThumb()) {
2759     // Invert the bits.
2760     isRead = ~isRead & 1;
2761     isData = ~isData & 1;
2762   }
2763
2764   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2765                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2766                      DAG.getConstant(isData, MVT::i32));
2767 }
2768
2769 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2770   MachineFunction &MF = DAG.getMachineFunction();
2771   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2772
2773   // vastart just stores the address of the VarArgsFrameIndex slot into the
2774   // memory location argument.
2775   SDLoc dl(Op);
2776   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2777   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2778   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2779   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2780                       MachinePointerInfo(SV), false, false, 0);
2781 }
2782
2783 SDValue
2784 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2785                                         SDValue &Root, SelectionDAG &DAG,
2786                                         SDLoc dl) const {
2787   MachineFunction &MF = DAG.getMachineFunction();
2788   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2789
2790   const TargetRegisterClass *RC;
2791   if (AFI->isThumb1OnlyFunction())
2792     RC = &ARM::tGPRRegClass;
2793   else
2794     RC = &ARM::GPRRegClass;
2795
2796   // Transform the arguments stored in physical registers into virtual ones.
2797   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2798   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2799
2800   SDValue ArgValue2;
2801   if (NextVA.isMemLoc()) {
2802     MachineFrameInfo *MFI = MF.getFrameInfo();
2803     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2804
2805     // Create load node to retrieve arguments from the stack.
2806     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2807     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2808                             MachinePointerInfo::getFixedStack(FI),
2809                             false, false, false, 0);
2810   } else {
2811     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2812     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2813   }
2814   if (!Subtarget->isLittle())
2815     std::swap (ArgValue, ArgValue2);
2816   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2817 }
2818
2819 void
2820 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2821                                   unsigned InRegsParamRecordIdx,
2822                                   unsigned ArgSize,
2823                                   unsigned &ArgRegsSize,
2824                                   unsigned &ArgRegsSaveSize)
2825   const {
2826   unsigned NumGPRs;
2827   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2828     unsigned RBegin, REnd;
2829     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2830     NumGPRs = REnd - RBegin;
2831   } else {
2832     unsigned int firstUnalloced;
2833     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2834                                                 sizeof(GPRArgRegs) /
2835                                                 sizeof(GPRArgRegs[0]));
2836     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2837   }
2838
2839   unsigned Align = MF.getTarget()
2840                        .getSubtargetImpl()
2841                        ->getFrameLowering()
2842                        ->getStackAlignment();
2843   ArgRegsSize = NumGPRs * 4;
2844
2845   // If parameter is split between stack and GPRs...
2846   if (NumGPRs && Align > 4 &&
2847       (ArgRegsSize < ArgSize ||
2848         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2849     // Add padding for part of param recovered from GPRs.  For example,
2850     // if Align == 8, its last byte must be at address K*8 - 1.
2851     // We need to do it, since remained (stack) part of parameter has
2852     // stack alignment, and we need to "attach" "GPRs head" without gaps
2853     // to it:
2854     // Stack:
2855     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2856     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2857     //
2858     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2859     unsigned Padding =
2860         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2861     ArgRegsSaveSize = ArgRegsSize + Padding;
2862   } else
2863     // We don't need to extend regs save size for byval parameters if they
2864     // are passed via GPRs only.
2865     ArgRegsSaveSize = ArgRegsSize;
2866 }
2867
2868 // The remaining GPRs hold either the beginning of variable-argument
2869 // data, or the beginning of an aggregate passed by value (usually
2870 // byval).  Either way, we allocate stack slots adjacent to the data
2871 // provided by our caller, and store the unallocated registers there.
2872 // If this is a variadic function, the va_list pointer will begin with
2873 // these values; otherwise, this reassembles a (byval) structure that
2874 // was split between registers and memory.
2875 // Return: The frame index registers were stored into.
2876 int
2877 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2878                                   SDLoc dl, SDValue &Chain,
2879                                   const Value *OrigArg,
2880                                   unsigned InRegsParamRecordIdx,
2881                                   unsigned OffsetFromOrigArg,
2882                                   unsigned ArgOffset,
2883                                   unsigned ArgSize,
2884                                   bool ForceMutable,
2885                                   unsigned ByValStoreOffset,
2886                                   unsigned TotalArgRegsSaveSize) const {
2887
2888   // Currently, two use-cases possible:
2889   // Case #1. Non-var-args function, and we meet first byval parameter.
2890   //          Setup first unallocated register as first byval register;
2891   //          eat all remained registers
2892   //          (these two actions are performed by HandleByVal method).
2893   //          Then, here, we initialize stack frame with
2894   //          "store-reg" instructions.
2895   // Case #2. Var-args function, that doesn't contain byval parameters.
2896   //          The same: eat all remained unallocated registers,
2897   //          initialize stack frame.
2898
2899   MachineFunction &MF = DAG.getMachineFunction();
2900   MachineFrameInfo *MFI = MF.getFrameInfo();
2901   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2902   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2903   unsigned RBegin, REnd;
2904   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2905     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2906     firstRegToSaveIndex = RBegin - ARM::R0;
2907     lastRegToSaveIndex = REnd - ARM::R0;
2908   } else {
2909     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2910       (GPRArgRegs, array_lengthof(GPRArgRegs));
2911     lastRegToSaveIndex = 4;
2912   }
2913
2914   unsigned ArgRegsSize, ArgRegsSaveSize;
2915   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2916                  ArgRegsSize, ArgRegsSaveSize);
2917
2918   // Store any by-val regs to their spots on the stack so that they may be
2919   // loaded by deferencing the result of formal parameter pointer or va_next.
2920   // Note: once stack area for byval/varargs registers
2921   // was initialized, it can't be initialized again.
2922   if (ArgRegsSaveSize) {
2923     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2924
2925     if (Padding) {
2926       assert(AFI->getStoredByValParamsPadding() == 0 &&
2927              "The only parameter may be padded.");
2928       AFI->setStoredByValParamsPadding(Padding);
2929     }
2930
2931     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2932                                             Padding +
2933                                               ByValStoreOffset -
2934                                               (int64_t)TotalArgRegsSaveSize,
2935                                             false);
2936     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2937     if (Padding) {
2938        MFI->CreateFixedObject(Padding,
2939                               ArgOffset + ByValStoreOffset -
2940                                 (int64_t)ArgRegsSaveSize,
2941                               false);
2942     }
2943
2944     SmallVector<SDValue, 4> MemOps;
2945     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2946          ++firstRegToSaveIndex, ++i) {
2947       const TargetRegisterClass *RC;
2948       if (AFI->isThumb1OnlyFunction())
2949         RC = &ARM::tGPRRegClass;
2950       else
2951         RC = &ARM::GPRRegClass;
2952
2953       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2954       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2955       SDValue Store =
2956         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2957                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2958                      false, false, 0);
2959       MemOps.push_back(Store);
2960       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2961                         DAG.getConstant(4, getPointerTy()));
2962     }
2963
2964     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2965
2966     if (!MemOps.empty())
2967       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2968     return FrameIndex;
2969   } else {
2970     if (ArgSize == 0) {
2971       // We cannot allocate a zero-byte object for the first variadic argument,
2972       // so just make up a size.
2973       ArgSize = 4;
2974     }
2975     // This will point to the next argument passed via stack.
2976     return MFI->CreateFixedObject(
2977       ArgSize, ArgOffset, !ForceMutable);
2978   }
2979 }
2980
2981 // Setup stack frame, the va_list pointer will start from.
2982 void
2983 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2984                                         SDLoc dl, SDValue &Chain,
2985                                         unsigned ArgOffset,
2986                                         unsigned TotalArgRegsSaveSize,
2987                                         bool ForceMutable) const {
2988   MachineFunction &MF = DAG.getMachineFunction();
2989   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2990
2991   // Try to store any remaining integer argument regs
2992   // to their spots on the stack so that they may be loaded by deferencing
2993   // the result of va_next.
2994   // If there is no regs to be stored, just point address after last
2995   // argument passed via stack.
2996   int FrameIndex =
2997     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2998                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2999                    0, TotalArgRegsSaveSize);
3000
3001   AFI->setVarArgsFrameIndex(FrameIndex);
3002 }
3003
3004 SDValue
3005 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3006                                         CallingConv::ID CallConv, bool isVarArg,
3007                                         const SmallVectorImpl<ISD::InputArg>
3008                                           &Ins,
3009                                         SDLoc dl, SelectionDAG &DAG,
3010                                         SmallVectorImpl<SDValue> &InVals)
3011                                           const {
3012   MachineFunction &MF = DAG.getMachineFunction();
3013   MachineFrameInfo *MFI = MF.getFrameInfo();
3014
3015   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3016
3017   // Assign locations to all of the incoming arguments.
3018   SmallVector<CCValAssign, 16> ArgLocs;
3019   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3020                     *DAG.getContext(), Prologue);
3021   CCInfo.AnalyzeFormalArguments(Ins,
3022                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3023                                                   isVarArg));
3024
3025   SmallVector<SDValue, 16> ArgValues;
3026   int lastInsIndex = -1;
3027   SDValue ArgValue;
3028   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3029   unsigned CurArgIdx = 0;
3030
3031   // Initially ArgRegsSaveSize is zero.
3032   // Then we increase this value each time we meet byval parameter.
3033   // We also increase this value in case of varargs function.
3034   AFI->setArgRegsSaveSize(0);
3035
3036   unsigned ByValStoreOffset = 0;
3037   unsigned TotalArgRegsSaveSize = 0;
3038   unsigned ArgRegsSaveSizeMaxAlign = 4;
3039
3040   // Calculate the amount of stack space that we need to allocate to store
3041   // byval and variadic arguments that are passed in registers.
3042   // We need to know this before we allocate the first byval or variadic
3043   // argument, as they will be allocated a stack slot below the CFA (Canonical
3044   // Frame Address, the stack pointer at entry to the function).
3045   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3046     CCValAssign &VA = ArgLocs[i];
3047     if (VA.isMemLoc()) {
3048       int index = VA.getValNo();
3049       if (index != lastInsIndex) {
3050         ISD::ArgFlagsTy Flags = Ins[index].Flags;
3051         if (Flags.isByVal()) {
3052           unsigned ExtraArgRegsSize;
3053           unsigned ExtraArgRegsSaveSize;
3054           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
3055                          Flags.getByValSize(),
3056                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
3057
3058           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3059           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
3060               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
3061           CCInfo.nextInRegsParam();
3062         }
3063         lastInsIndex = index;
3064       }
3065     }
3066   }
3067   CCInfo.rewindByValRegsInfo();
3068   lastInsIndex = -1;
3069   if (isVarArg && MFI->hasVAStart()) {
3070     unsigned ExtraArgRegsSize;
3071     unsigned ExtraArgRegsSaveSize;
3072     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
3073                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
3074     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
3075   }
3076   // If the arg regs save area contains N-byte aligned values, the
3077   // bottom of it must be at least N-byte aligned.
3078   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
3079   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
3080
3081   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3082     CCValAssign &VA = ArgLocs[i];
3083     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
3084     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
3085     // Arguments stored in registers.
3086     if (VA.isRegLoc()) {
3087       EVT RegVT = VA.getLocVT();
3088
3089       if (VA.needsCustom()) {
3090         // f64 and vector types are split up into multiple registers or
3091         // combinations of registers and stack slots.
3092         if (VA.getLocVT() == MVT::v2f64) {
3093           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3094                                                    Chain, DAG, dl);
3095           VA = ArgLocs[++i]; // skip ahead to next loc
3096           SDValue ArgValue2;
3097           if (VA.isMemLoc()) {
3098             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3099             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3100             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3101                                     MachinePointerInfo::getFixedStack(FI),
3102                                     false, false, false, 0);
3103           } else {
3104             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3105                                              Chain, DAG, dl);
3106           }
3107           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3108           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3109                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3110           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3111                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3112         } else
3113           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3114
3115       } else {
3116         const TargetRegisterClass *RC;
3117
3118         if (RegVT == MVT::f32)
3119           RC = &ARM::SPRRegClass;
3120         else if (RegVT == MVT::f64)
3121           RC = &ARM::DPRRegClass;
3122         else if (RegVT == MVT::v2f64)
3123           RC = &ARM::QPRRegClass;
3124         else if (RegVT == MVT::i32)
3125           RC = AFI->isThumb1OnlyFunction() ?
3126             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3127             (const TargetRegisterClass*)&ARM::GPRRegClass;
3128         else
3129           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3130
3131         // Transform the arguments in physical registers into virtual ones.
3132         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3133         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3134       }
3135
3136       // If this is an 8 or 16-bit value, it is really passed promoted
3137       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3138       // truncate to the right size.
3139       switch (VA.getLocInfo()) {
3140       default: llvm_unreachable("Unknown loc info!");
3141       case CCValAssign::Full: break;
3142       case CCValAssign::BCvt:
3143         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3144         break;
3145       case CCValAssign::SExt:
3146         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3147                                DAG.getValueType(VA.getValVT()));
3148         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3149         break;
3150       case CCValAssign::ZExt:
3151         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3152                                DAG.getValueType(VA.getValVT()));
3153         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3154         break;
3155       }
3156
3157       InVals.push_back(ArgValue);
3158
3159     } else { // VA.isRegLoc()
3160
3161       // sanity check
3162       assert(VA.isMemLoc());
3163       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3164
3165       int index = ArgLocs[i].getValNo();
3166
3167       // Some Ins[] entries become multiple ArgLoc[] entries.
3168       // Process them only once.
3169       if (index != lastInsIndex)
3170         {
3171           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3172           // FIXME: For now, all byval parameter objects are marked mutable.
3173           // This can be changed with more analysis.
3174           // In case of tail call optimization mark all arguments mutable.
3175           // Since they could be overwritten by lowering of arguments in case of
3176           // a tail call.
3177           if (Flags.isByVal()) {
3178             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3179
3180             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3181             int FrameIndex = StoreByValRegs(
3182                 CCInfo, DAG, dl, Chain, CurOrigArg,
3183                 CurByValIndex,
3184                 Ins[VA.getValNo()].PartOffset,
3185                 VA.getLocMemOffset(),
3186                 Flags.getByValSize(),
3187                 true /*force mutable frames*/,
3188                 ByValStoreOffset,
3189                 TotalArgRegsSaveSize);
3190             ByValStoreOffset += Flags.getByValSize();
3191             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3192             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3193             CCInfo.nextInRegsParam();
3194           } else {
3195             unsigned FIOffset = VA.getLocMemOffset();
3196             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3197                                             FIOffset, true);
3198
3199             // Create load nodes to retrieve arguments from the stack.
3200             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3201             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3202                                          MachinePointerInfo::getFixedStack(FI),
3203                                          false, false, false, 0));
3204           }
3205           lastInsIndex = index;
3206         }
3207     }
3208   }
3209
3210   // varargs
3211   if (isVarArg && MFI->hasVAStart())
3212     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3213                          CCInfo.getNextStackOffset(),
3214                          TotalArgRegsSaveSize);
3215
3216   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3217
3218   return Chain;
3219 }
3220
3221 /// isFloatingPointZero - Return true if this is +0.0.
3222 static bool isFloatingPointZero(SDValue Op) {
3223   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3224     return CFP->getValueAPF().isPosZero();
3225   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3226     // Maybe this has already been legalized into the constant pool?
3227     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3228       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3229       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3230         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3231           return CFP->getValueAPF().isPosZero();
3232     }
3233   }
3234   return false;
3235 }
3236
3237 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3238 /// the given operands.
3239 SDValue
3240 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3241                              SDValue &ARMcc, SelectionDAG &DAG,
3242                              SDLoc dl) const {
3243   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3244     unsigned C = RHSC->getZExtValue();
3245     if (!isLegalICmpImmediate(C)) {
3246       // Constant does not fit, try adjusting it by one?
3247       switch (CC) {
3248       default: break;
3249       case ISD::SETLT:
3250       case ISD::SETGE:
3251         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3252           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3253           RHS = DAG.getConstant(C-1, MVT::i32);
3254         }
3255         break;
3256       case ISD::SETULT:
3257       case ISD::SETUGE:
3258         if (C != 0 && isLegalICmpImmediate(C-1)) {
3259           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3260           RHS = DAG.getConstant(C-1, MVT::i32);
3261         }
3262         break;
3263       case ISD::SETLE:
3264       case ISD::SETGT:
3265         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3266           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3267           RHS = DAG.getConstant(C+1, MVT::i32);
3268         }
3269         break;
3270       case ISD::SETULE:
3271       case ISD::SETUGT:
3272         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3273           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3274           RHS = DAG.getConstant(C+1, MVT::i32);
3275         }
3276         break;
3277       }
3278     }
3279   }
3280
3281   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3282   ARMISD::NodeType CompareType;
3283   switch (CondCode) {
3284   default:
3285     CompareType = ARMISD::CMP;
3286     break;
3287   case ARMCC::EQ:
3288   case ARMCC::NE:
3289     // Uses only Z Flag
3290     CompareType = ARMISD::CMPZ;
3291     break;
3292   }
3293   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3294   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3295 }
3296
3297 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3298 SDValue
3299 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3300                              SDLoc dl) const {
3301   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3302   SDValue Cmp;
3303   if (!isFloatingPointZero(RHS))
3304     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3305   else
3306     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3307   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3308 }
3309
3310 /// duplicateCmp - Glue values can have only one use, so this function
3311 /// duplicates a comparison node.
3312 SDValue
3313 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3314   unsigned Opc = Cmp.getOpcode();
3315   SDLoc DL(Cmp);
3316   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3317     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3318
3319   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3320   Cmp = Cmp.getOperand(0);
3321   Opc = Cmp.getOpcode();
3322   if (Opc == ARMISD::CMPFP)
3323     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3324   else {
3325     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3326     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3327   }
3328   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3329 }
3330
3331 std::pair<SDValue, SDValue>
3332 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3333                                  SDValue &ARMcc) const {
3334   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3335
3336   SDValue Value, OverflowCmp;
3337   SDValue LHS = Op.getOperand(0);
3338   SDValue RHS = Op.getOperand(1);
3339
3340
3341   // FIXME: We are currently always generating CMPs because we don't support
3342   // generating CMN through the backend. This is not as good as the natural
3343   // CMP case because it causes a register dependency and cannot be folded
3344   // later.
3345
3346   switch (Op.getOpcode()) {
3347   default:
3348     llvm_unreachable("Unknown overflow instruction!");
3349   case ISD::SADDO:
3350     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3351     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3352     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3353     break;
3354   case ISD::UADDO:
3355     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3356     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3357     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3358     break;
3359   case ISD::SSUBO:
3360     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3361     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3362     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3363     break;
3364   case ISD::USUBO:
3365     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3366     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3367     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3368     break;
3369   } // switch (...)
3370
3371   return std::make_pair(Value, OverflowCmp);
3372 }
3373
3374
3375 SDValue
3376 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3377   // Let legalize expand this if it isn't a legal type yet.
3378   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3379     return SDValue();
3380
3381   SDValue Value, OverflowCmp;
3382   SDValue ARMcc;
3383   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3384   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3385   // We use 0 and 1 as false and true values.
3386   SDValue TVal = DAG.getConstant(1, MVT::i32);
3387   SDValue FVal = DAG.getConstant(0, MVT::i32);
3388   EVT VT = Op.getValueType();
3389
3390   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3391                                  ARMcc, CCR, OverflowCmp);
3392
3393   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3394   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3395 }
3396
3397
3398 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3399   SDValue Cond = Op.getOperand(0);
3400   SDValue SelectTrue = Op.getOperand(1);
3401   SDValue SelectFalse = Op.getOperand(2);
3402   SDLoc dl(Op);
3403   unsigned Opc = Cond.getOpcode();
3404
3405   if (Cond.getResNo() == 1 &&
3406       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3407        Opc == ISD::USUBO)) {
3408     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3409       return SDValue();
3410
3411     SDValue Value, OverflowCmp;
3412     SDValue ARMcc;
3413     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3414     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3415     EVT VT = Op.getValueType();
3416
3417     return getCMOV(SDLoc(Op), VT, SelectTrue, SelectFalse, ARMcc, CCR,
3418                    OverflowCmp, DAG);
3419   }
3420
3421   // Convert:
3422   //
3423   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3424   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3425   //
3426   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3427     const ConstantSDNode *CMOVTrue =
3428       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3429     const ConstantSDNode *CMOVFalse =
3430       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3431
3432     if (CMOVTrue && CMOVFalse) {
3433       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3434       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3435
3436       SDValue True;
3437       SDValue False;
3438       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3439         True = SelectTrue;
3440         False = SelectFalse;
3441       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3442         True = SelectFalse;
3443         False = SelectTrue;
3444       }
3445
3446       if (True.getNode() && False.getNode()) {
3447         EVT VT = Op.getValueType();
3448         SDValue ARMcc = Cond.getOperand(2);
3449         SDValue CCR = Cond.getOperand(3);
3450         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3451         assert(True.getValueType() == VT);
3452         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3453       }
3454     }
3455   }
3456
3457   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3458   // undefined bits before doing a full-word comparison with zero.
3459   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3460                      DAG.getConstant(1, Cond.getValueType()));
3461
3462   return DAG.getSelectCC(dl, Cond,
3463                          DAG.getConstant(0, Cond.getValueType()),
3464                          SelectTrue, SelectFalse, ISD::SETNE);
3465 }
3466
3467 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3468   if (CC == ISD::SETNE)
3469     return ISD::SETEQ;
3470   return ISD::getSetCCInverse(CC, true);
3471 }
3472
3473 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3474                                  bool &swpCmpOps, bool &swpVselOps) {
3475   // Start by selecting the GE condition code for opcodes that return true for
3476   // 'equality'
3477   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3478       CC == ISD::SETULE)
3479     CondCode = ARMCC::GE;
3480
3481   // and GT for opcodes that return false for 'equality'.
3482   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3483            CC == ISD::SETULT)
3484     CondCode = ARMCC::GT;
3485
3486   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3487   // to swap the compare operands.
3488   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3489       CC == ISD::SETULT)
3490     swpCmpOps = true;
3491
3492   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3493   // If we have an unordered opcode, we need to swap the operands to the VSEL
3494   // instruction (effectively negating the condition).
3495   //
3496   // This also has the effect of swapping which one of 'less' or 'greater'
3497   // returns true, so we also swap the compare operands. It also switches
3498   // whether we return true for 'equality', so we compensate by picking the
3499   // opposite condition code to our original choice.
3500   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3501       CC == ISD::SETUGT) {
3502     swpCmpOps = !swpCmpOps;
3503     swpVselOps = !swpVselOps;
3504     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3505   }
3506
3507   // 'ordered' is 'anything but unordered', so use the VS condition code and
3508   // swap the VSEL operands.
3509   if (CC == ISD::SETO) {
3510     CondCode = ARMCC::VS;
3511     swpVselOps = true;
3512   }
3513
3514   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3515   // code and swap the VSEL operands.
3516   if (CC == ISD::SETUNE) {
3517     CondCode = ARMCC::EQ;
3518     swpVselOps = true;
3519   }
3520 }
3521
3522 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3523                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3524                                    SDValue Cmp, SelectionDAG &DAG) const {
3525   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3526     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3527                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3528     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3529                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3530
3531     SDValue TrueLow = TrueVal.getValue(0);
3532     SDValue TrueHigh = TrueVal.getValue(1);
3533     SDValue FalseLow = FalseVal.getValue(0);
3534     SDValue FalseHigh = FalseVal.getValue(1);
3535
3536     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3537                               ARMcc, CCR, Cmp);
3538     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3539                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3540
3541     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3542   } else {
3543     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3544                        Cmp);
3545   }
3546 }
3547
3548 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3549   EVT VT = Op.getValueType();
3550   SDValue LHS = Op.getOperand(0);
3551   SDValue RHS = Op.getOperand(1);
3552   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3553   SDValue TrueVal = Op.getOperand(2);
3554   SDValue FalseVal = Op.getOperand(3);
3555   SDLoc dl(Op);
3556
3557   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3558     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3559                                                     dl);
3560
3561     // If softenSetCCOperands only returned one value, we should compare it to
3562     // zero.
3563     if (!RHS.getNode()) {
3564       RHS = DAG.getConstant(0, LHS.getValueType());
3565       CC = ISD::SETNE;
3566     }
3567   }
3568
3569   if (LHS.getValueType() == MVT::i32) {
3570     // Try to generate VSEL on ARMv8.
3571     // The VSEL instruction can't use all the usual ARM condition
3572     // codes: it only has two bits to select the condition code, so it's
3573     // constrained to use only GE, GT, VS and EQ.
3574     //
3575     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3576     // swap the operands of the previous compare instruction (effectively
3577     // inverting the compare condition, swapping 'less' and 'greater') and
3578     // sometimes need to swap the operands to the VSEL (which inverts the
3579     // condition in the sense of firing whenever the previous condition didn't)
3580     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3581                                       TrueVal.getValueType() == MVT::f64)) {
3582       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3583       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3584           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3585         CC = getInverseCCForVSEL(CC);
3586         std::swap(TrueVal, FalseVal);
3587       }
3588     }
3589
3590     SDValue ARMcc;
3591     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3592     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3593     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3594   }
3595
3596   ARMCC::CondCodes CondCode, CondCode2;
3597   FPCCToARMCC(CC, CondCode, CondCode2);
3598
3599   // Try to generate VSEL on ARMv8.
3600   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3601                                     TrueVal.getValueType() == MVT::f64)) {
3602     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3603     // same operands, as follows:
3604     //   c = fcmp [ogt, olt, ugt, ult] a, b
3605     //   select c, a, b
3606     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3607     // handled differently than the original code sequence.
3608     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3609         RHS == FalseVal) {
3610       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3611         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3612       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3613         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3614     }
3615
3616     bool swpCmpOps = false;
3617     bool swpVselOps = false;
3618     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3619
3620     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3621         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3622       if (swpCmpOps)
3623         std::swap(LHS, RHS);
3624       if (swpVselOps)
3625         std::swap(TrueVal, FalseVal);
3626     }
3627   }
3628
3629   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3630   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3631   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3632   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3633   if (CondCode2 != ARMCC::AL) {
3634     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3635     // FIXME: Needs another CMP because flag can have but one use.
3636     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3637     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3638   }
3639   return Result;
3640 }
3641
3642 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3643 /// to morph to an integer compare sequence.
3644 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3645                            const ARMSubtarget *Subtarget) {
3646   SDNode *N = Op.getNode();
3647   if (!N->hasOneUse())
3648     // Otherwise it requires moving the value from fp to integer registers.
3649     return false;
3650   if (!N->getNumValues())
3651     return false;
3652   EVT VT = Op.getValueType();
3653   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3654     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3655     // vmrs are very slow, e.g. cortex-a8.
3656     return false;
3657
3658   if (isFloatingPointZero(Op)) {
3659     SeenZero = true;
3660     return true;
3661   }
3662   return ISD::isNormalLoad(N);
3663 }
3664
3665 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3666   if (isFloatingPointZero(Op))
3667     return DAG.getConstant(0, MVT::i32);
3668
3669   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3670     return DAG.getLoad(MVT::i32, SDLoc(Op),
3671                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3672                        Ld->isVolatile(), Ld->isNonTemporal(),
3673                        Ld->isInvariant(), Ld->getAlignment());
3674
3675   llvm_unreachable("Unknown VFP cmp argument!");
3676 }
3677
3678 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3679                            SDValue &RetVal1, SDValue &RetVal2) {
3680   if (isFloatingPointZero(Op)) {
3681     RetVal1 = DAG.getConstant(0, MVT::i32);
3682     RetVal2 = DAG.getConstant(0, MVT::i32);
3683     return;
3684   }
3685
3686   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3687     SDValue Ptr = Ld->getBasePtr();
3688     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3689                           Ld->getChain(), Ptr,
3690                           Ld->getPointerInfo(),
3691                           Ld->isVolatile(), Ld->isNonTemporal(),
3692                           Ld->isInvariant(), Ld->getAlignment());
3693
3694     EVT PtrType = Ptr.getValueType();
3695     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3696     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3697                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3698     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3699                           Ld->getChain(), NewPtr,
3700                           Ld->getPointerInfo().getWithOffset(4),
3701                           Ld->isVolatile(), Ld->isNonTemporal(),
3702                           Ld->isInvariant(), NewAlign);
3703     return;
3704   }
3705
3706   llvm_unreachable("Unknown VFP cmp argument!");
3707 }
3708
3709 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3710 /// f32 and even f64 comparisons to integer ones.
3711 SDValue
3712 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3713   SDValue Chain = Op.getOperand(0);
3714   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3715   SDValue LHS = Op.getOperand(2);
3716   SDValue RHS = Op.getOperand(3);
3717   SDValue Dest = Op.getOperand(4);
3718   SDLoc dl(Op);
3719
3720   bool LHSSeenZero = false;
3721   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3722   bool RHSSeenZero = false;
3723   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3724   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3725     // If unsafe fp math optimization is enabled and there are no other uses of
3726     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3727     // to an integer comparison.
3728     if (CC == ISD::SETOEQ)
3729       CC = ISD::SETEQ;
3730     else if (CC == ISD::SETUNE)
3731       CC = ISD::SETNE;
3732
3733     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3734     SDValue ARMcc;
3735     if (LHS.getValueType() == MVT::f32) {
3736       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3737                         bitcastf32Toi32(LHS, DAG), Mask);
3738       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3739                         bitcastf32Toi32(RHS, DAG), Mask);
3740       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3741       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3742       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3743                          Chain, Dest, ARMcc, CCR, Cmp);
3744     }
3745
3746     SDValue LHS1, LHS2;
3747     SDValue RHS1, RHS2;
3748     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3749     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3750     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3751     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3752     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3753     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3754     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3755     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3756     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3757   }
3758
3759   return SDValue();
3760 }
3761
3762 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3763   SDValue Chain = Op.getOperand(0);
3764   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3765   SDValue LHS = Op.getOperand(2);
3766   SDValue RHS = Op.getOperand(3);
3767   SDValue Dest = Op.getOperand(4);
3768   SDLoc dl(Op);
3769
3770   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3771     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3772                                                     dl);
3773
3774     // If softenSetCCOperands only returned one value, we should compare it to
3775     // zero.
3776     if (!RHS.getNode()) {
3777       RHS = DAG.getConstant(0, LHS.getValueType());
3778       CC = ISD::SETNE;
3779     }
3780   }
3781
3782   if (LHS.getValueType() == MVT::i32) {
3783     SDValue ARMcc;
3784     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3785     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3786     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3787                        Chain, Dest, ARMcc, CCR, Cmp);
3788   }
3789
3790   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3791
3792   if (getTargetMachine().Options.UnsafeFPMath &&
3793       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3794        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3795     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3796     if (Result.getNode())
3797       return Result;
3798   }
3799
3800   ARMCC::CondCodes CondCode, CondCode2;
3801   FPCCToARMCC(CC, CondCode, CondCode2);
3802
3803   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3804   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3805   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3806   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3807   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3808   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3809   if (CondCode2 != ARMCC::AL) {
3810     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3811     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3812     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3813   }
3814   return Res;
3815 }
3816
3817 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3818   SDValue Chain = Op.getOperand(0);
3819   SDValue Table = Op.getOperand(1);
3820   SDValue Index = Op.getOperand(2);
3821   SDLoc dl(Op);
3822
3823   EVT PTy = getPointerTy();
3824   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3825   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3826   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3827   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3828   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3829   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3830   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3831   if (Subtarget->isThumb2()) {
3832     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3833     // which does another jump to the destination. This also makes it easier
3834     // to translate it to TBB / TBH later.
3835     // FIXME: This might not work if the function is extremely large.
3836     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3837                        Addr, Op.getOperand(2), JTI, UId);
3838   }
3839   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3840     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3841                        MachinePointerInfo::getJumpTable(),
3842                        false, false, false, 0);
3843     Chain = Addr.getValue(1);
3844     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3845     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3846   } else {
3847     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3848                        MachinePointerInfo::getJumpTable(),
3849                        false, false, false, 0);
3850     Chain = Addr.getValue(1);
3851     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3852   }
3853 }
3854
3855 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3856   EVT VT = Op.getValueType();
3857   SDLoc dl(Op);
3858
3859   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3860     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3861       return Op;
3862     return DAG.UnrollVectorOp(Op.getNode());
3863   }
3864
3865   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3866          "Invalid type for custom lowering!");
3867   if (VT != MVT::v4i16)
3868     return DAG.UnrollVectorOp(Op.getNode());
3869
3870   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3871   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3872 }
3873
3874 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3875   EVT VT = Op.getValueType();
3876   if (VT.isVector())
3877     return LowerVectorFP_TO_INT(Op, DAG);
3878
3879   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3880     RTLIB::Libcall LC;
3881     if (Op.getOpcode() == ISD::FP_TO_SINT)
3882       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3883                               Op.getValueType());
3884     else
3885       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3886                               Op.getValueType());
3887     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3888                        /*isSigned*/ false, SDLoc(Op)).first;
3889   }
3890
3891   SDLoc dl(Op);
3892   unsigned Opc;
3893
3894   switch (Op.getOpcode()) {
3895   default: llvm_unreachable("Invalid opcode!");
3896   case ISD::FP_TO_SINT:
3897     Opc = ARMISD::FTOSI;
3898     break;
3899   case ISD::FP_TO_UINT:
3900     Opc = ARMISD::FTOUI;
3901     break;
3902   }
3903   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3904   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3905 }
3906
3907 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3908   EVT VT = Op.getValueType();
3909   SDLoc dl(Op);
3910
3911   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3912     if (VT.getVectorElementType() == MVT::f32)
3913       return Op;
3914     return DAG.UnrollVectorOp(Op.getNode());
3915   }
3916
3917   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3918          "Invalid type for custom lowering!");
3919   if (VT != MVT::v4f32)
3920     return DAG.UnrollVectorOp(Op.getNode());
3921
3922   unsigned CastOpc;
3923   unsigned Opc;
3924   switch (Op.getOpcode()) {
3925   default: llvm_unreachable("Invalid opcode!");
3926   case ISD::SINT_TO_FP:
3927     CastOpc = ISD::SIGN_EXTEND;
3928     Opc = ISD::SINT_TO_FP;
3929     break;
3930   case ISD::UINT_TO_FP:
3931     CastOpc = ISD::ZERO_EXTEND;
3932     Opc = ISD::UINT_TO_FP;
3933     break;
3934   }
3935
3936   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3937   return DAG.getNode(Opc, dl, VT, Op);
3938 }
3939
3940 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
3941   EVT VT = Op.getValueType();
3942   if (VT.isVector())
3943     return LowerVectorINT_TO_FP(Op, DAG);
3944
3945   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
3946     RTLIB::Libcall LC;
3947     if (Op.getOpcode() == ISD::SINT_TO_FP)
3948       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
3949                               Op.getValueType());
3950     else
3951       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
3952                               Op.getValueType());
3953     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3954                        /*isSigned*/ false, SDLoc(Op)).first;
3955   }
3956
3957   SDLoc dl(Op);
3958   unsigned Opc;
3959
3960   switch (Op.getOpcode()) {
3961   default: llvm_unreachable("Invalid opcode!");
3962   case ISD::SINT_TO_FP:
3963     Opc = ARMISD::SITOF;
3964     break;
3965   case ISD::UINT_TO_FP:
3966     Opc = ARMISD::UITOF;
3967     break;
3968   }
3969
3970   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3971   return DAG.getNode(Opc, dl, VT, Op);
3972 }
3973
3974 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3975   // Implement fcopysign with a fabs and a conditional fneg.
3976   SDValue Tmp0 = Op.getOperand(0);
3977   SDValue Tmp1 = Op.getOperand(1);
3978   SDLoc dl(Op);
3979   EVT VT = Op.getValueType();
3980   EVT SrcVT = Tmp1.getValueType();
3981   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3982     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3983   bool UseNEON = !InGPR && Subtarget->hasNEON();
3984
3985   if (UseNEON) {
3986     // Use VBSL to copy the sign bit.
3987     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3988     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3989                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3990     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3991     if (VT == MVT::f64)
3992       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3993                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3994                          DAG.getConstant(32, MVT::i32));
3995     else /*if (VT == MVT::f32)*/
3996       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3997     if (SrcVT == MVT::f32) {
3998       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3999       if (VT == MVT::f64)
4000         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4001                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4002                            DAG.getConstant(32, MVT::i32));
4003     } else if (VT == MVT::f32)
4004       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4005                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4006                          DAG.getConstant(32, MVT::i32));
4007     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4008     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4009
4010     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4011                                             MVT::i32);
4012     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4013     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4014                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4015
4016     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4017                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4018                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4019     if (VT == MVT::f32) {
4020       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4021       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4022                         DAG.getConstant(0, MVT::i32));
4023     } else {
4024       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4025     }
4026
4027     return Res;
4028   }
4029
4030   // Bitcast operand 1 to i32.
4031   if (SrcVT == MVT::f64)
4032     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4033                        Tmp1).getValue(1);
4034   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4035
4036   // Or in the signbit with integer operations.
4037   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
4038   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
4039   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4040   if (VT == MVT::f32) {
4041     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4042                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4043     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4044                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4045   }
4046
4047   // f64: Or the high part with signbit and then combine two parts.
4048   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4049                      Tmp0);
4050   SDValue Lo = Tmp0.getValue(0);
4051   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4052   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4053   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4054 }
4055
4056 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4057   MachineFunction &MF = DAG.getMachineFunction();
4058   MachineFrameInfo *MFI = MF.getFrameInfo();
4059   MFI->setReturnAddressIsTaken(true);
4060
4061   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4062     return SDValue();
4063
4064   EVT VT = Op.getValueType();
4065   SDLoc dl(Op);
4066   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4067   if (Depth) {
4068     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4069     SDValue Offset = DAG.getConstant(4, MVT::i32);
4070     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4071                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4072                        MachinePointerInfo(), false, false, false, 0);
4073   }
4074
4075   // Return LR, which contains the return address. Mark it an implicit live-in.
4076   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4077   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4078 }
4079
4080 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4081   const ARMBaseRegisterInfo &ARI =
4082     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4083   MachineFunction &MF = DAG.getMachineFunction();
4084   MachineFrameInfo *MFI = MF.getFrameInfo();
4085   MFI->setFrameAddressIsTaken(true);
4086
4087   EVT VT = Op.getValueType();
4088   SDLoc dl(Op);  // FIXME probably not meaningful
4089   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4090   unsigned FrameReg = ARI.getFrameRegister(MF);
4091   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4092   while (Depth--)
4093     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4094                             MachinePointerInfo(),
4095                             false, false, false, 0);
4096   return FrameAddr;
4097 }
4098
4099 // FIXME? Maybe this could be a TableGen attribute on some registers and
4100 // this table could be generated automatically from RegInfo.
4101 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
4102                                               EVT VT) const {
4103   unsigned Reg = StringSwitch<unsigned>(RegName)
4104                        .Case("sp", ARM::SP)
4105                        .Default(0);
4106   if (Reg)
4107     return Reg;
4108   report_fatal_error("Invalid register name global variable");
4109 }
4110
4111 /// ExpandBITCAST - If the target supports VFP, this function is called to
4112 /// expand a bit convert where either the source or destination type is i64 to
4113 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4114 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4115 /// vectors), since the legalizer won't know what to do with that.
4116 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4117   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4118   SDLoc dl(N);
4119   SDValue Op = N->getOperand(0);
4120
4121   // This function is only supposed to be called for i64 types, either as the
4122   // source or destination of the bit convert.
4123   EVT SrcVT = Op.getValueType();
4124   EVT DstVT = N->getValueType(0);
4125   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4126          "ExpandBITCAST called for non-i64 type");
4127
4128   // Turn i64->f64 into VMOVDRR.
4129   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4130     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4131                              DAG.getConstant(0, MVT::i32));
4132     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4133                              DAG.getConstant(1, MVT::i32));
4134     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4135                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4136   }
4137
4138   // Turn f64->i64 into VMOVRRD.
4139   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4140     SDValue Cvt;
4141     if (TLI.isBigEndian() && SrcVT.isVector() &&
4142         SrcVT.getVectorNumElements() > 1)
4143       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4144                         DAG.getVTList(MVT::i32, MVT::i32),
4145                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4146     else
4147       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4148                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4149     // Merge the pieces into a single i64 value.
4150     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4151   }
4152
4153   return SDValue();
4154 }
4155
4156 /// getZeroVector - Returns a vector of specified type with all zero elements.
4157 /// Zero vectors are used to represent vector negation and in those cases
4158 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4159 /// not support i64 elements, so sometimes the zero vectors will need to be
4160 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4161 /// zero vector.
4162 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4163   assert(VT.isVector() && "Expected a vector type");
4164   // The canonical modified immediate encoding of a zero vector is....0!
4165   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4166   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4167   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4168   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4169 }
4170
4171 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4172 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4173 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4174                                                 SelectionDAG &DAG) const {
4175   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4176   EVT VT = Op.getValueType();
4177   unsigned VTBits = VT.getSizeInBits();
4178   SDLoc dl(Op);
4179   SDValue ShOpLo = Op.getOperand(0);
4180   SDValue ShOpHi = Op.getOperand(1);
4181   SDValue ShAmt  = Op.getOperand(2);
4182   SDValue ARMcc;
4183   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4184
4185   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4186
4187   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4188                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4189   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4190   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4191                                    DAG.getConstant(VTBits, MVT::i32));
4192   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4193   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4194   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4195
4196   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4197   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4198                           ARMcc, DAG, dl);
4199   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4200   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4201                            CCR, Cmp);
4202
4203   SDValue Ops[2] = { Lo, Hi };
4204   return DAG.getMergeValues(Ops, dl);
4205 }
4206
4207 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4208 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4209 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4210                                                SelectionDAG &DAG) const {
4211   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4212   EVT VT = Op.getValueType();
4213   unsigned VTBits = VT.getSizeInBits();
4214   SDLoc dl(Op);
4215   SDValue ShOpLo = Op.getOperand(0);
4216   SDValue ShOpHi = Op.getOperand(1);
4217   SDValue ShAmt  = Op.getOperand(2);
4218   SDValue ARMcc;
4219
4220   assert(Op.getOpcode() == ISD::SHL_PARTS);
4221   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4222                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4223   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4224   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4225                                    DAG.getConstant(VTBits, MVT::i32));
4226   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4227   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4228
4229   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4230   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4231   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4232                           ARMcc, DAG, dl);
4233   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4234   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4235                            CCR, Cmp);
4236
4237   SDValue Ops[2] = { Lo, Hi };
4238   return DAG.getMergeValues(Ops, dl);
4239 }
4240
4241 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4242                                             SelectionDAG &DAG) const {
4243   // The rounding mode is in bits 23:22 of the FPSCR.
4244   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4245   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4246   // so that the shift + and get folded into a bitfield extract.
4247   SDLoc dl(Op);
4248   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4249                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4250                                               MVT::i32));
4251   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4252                                   DAG.getConstant(1U << 22, MVT::i32));
4253   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4254                               DAG.getConstant(22, MVT::i32));
4255   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4256                      DAG.getConstant(3, MVT::i32));
4257 }
4258
4259 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4260                          const ARMSubtarget *ST) {
4261   EVT VT = N->getValueType(0);
4262   SDLoc dl(N);
4263
4264   if (!ST->hasV6T2Ops())
4265     return SDValue();
4266
4267   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4268   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4269 }
4270
4271 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4272 /// for each 16-bit element from operand, repeated.  The basic idea is to
4273 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4274 ///
4275 /// Trace for v4i16:
4276 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4277 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4278 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4279 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4280 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4281 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4282 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4283 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4284 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4285   EVT VT = N->getValueType(0);
4286   SDLoc DL(N);
4287
4288   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4289   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4290   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4291   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4292   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4293   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4294 }
4295
4296 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4297 /// bit-count for each 16-bit element from the operand.  We need slightly
4298 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4299 /// 64/128-bit registers.
4300 ///
4301 /// Trace for v4i16:
4302 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4303 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4304 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4305 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4306 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4307   EVT VT = N->getValueType(0);
4308   SDLoc DL(N);
4309
4310   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4311   if (VT.is64BitVector()) {
4312     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4313     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4314                        DAG.getIntPtrConstant(0));
4315   } else {
4316     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4317                                     BitCounts, DAG.getIntPtrConstant(0));
4318     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4319   }
4320 }
4321
4322 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4323 /// bit-count for each 32-bit element from the operand.  The idea here is
4324 /// to split the vector into 16-bit elements, leverage the 16-bit count
4325 /// routine, and then combine the results.
4326 ///
4327 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4328 /// input    = [v0    v1    ] (vi: 32-bit elements)
4329 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4330 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4331 /// vrev: N0 = [k1 k0 k3 k2 ]
4332 ///            [k0 k1 k2 k3 ]
4333 ///       N1 =+[k1 k0 k3 k2 ]
4334 ///            [k0 k2 k1 k3 ]
4335 ///       N2 =+[k1 k3 k0 k2 ]
4336 ///            [k0    k2    k1    k3    ]
4337 /// Extended =+[k1    k3    k0    k2    ]
4338 ///            [k0    k2    ]
4339 /// Extracted=+[k1    k3    ]
4340 ///
4341 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4342   EVT VT = N->getValueType(0);
4343   SDLoc DL(N);
4344
4345   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4346
4347   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4348   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4349   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4350   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4351   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4352
4353   if (VT.is64BitVector()) {
4354     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4355     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4356                        DAG.getIntPtrConstant(0));
4357   } else {
4358     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4359                                     DAG.getIntPtrConstant(0));
4360     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4361   }
4362 }
4363
4364 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4365                           const ARMSubtarget *ST) {
4366   EVT VT = N->getValueType(0);
4367
4368   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4369   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4370           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4371          "Unexpected type for custom ctpop lowering");
4372
4373   if (VT.getVectorElementType() == MVT::i32)
4374     return lowerCTPOP32BitElements(N, DAG);
4375   else
4376     return lowerCTPOP16BitElements(N, DAG);
4377 }
4378
4379 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4380                           const ARMSubtarget *ST) {
4381   EVT VT = N->getValueType(0);
4382   SDLoc dl(N);
4383
4384   if (!VT.isVector())
4385     return SDValue();
4386
4387   // Lower vector shifts on NEON to use VSHL.
4388   assert(ST->hasNEON() && "unexpected vector shift");
4389
4390   // Left shifts translate directly to the vshiftu intrinsic.
4391   if (N->getOpcode() == ISD::SHL)
4392     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4393                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4394                        N->getOperand(0), N->getOperand(1));
4395
4396   assert((N->getOpcode() == ISD::SRA ||
4397           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4398
4399   // NEON uses the same intrinsics for both left and right shifts.  For
4400   // right shifts, the shift amounts are negative, so negate the vector of
4401   // shift amounts.
4402   EVT ShiftVT = N->getOperand(1).getValueType();
4403   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4404                                      getZeroVector(ShiftVT, DAG, dl),
4405                                      N->getOperand(1));
4406   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4407                              Intrinsic::arm_neon_vshifts :
4408                              Intrinsic::arm_neon_vshiftu);
4409   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4410                      DAG.getConstant(vshiftInt, MVT::i32),
4411                      N->getOperand(0), NegatedCount);
4412 }
4413
4414 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4415                                 const ARMSubtarget *ST) {
4416   EVT VT = N->getValueType(0);
4417   SDLoc dl(N);
4418
4419   // We can get here for a node like i32 = ISD::SHL i32, i64
4420   if (VT != MVT::i64)
4421     return SDValue();
4422
4423   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4424          "Unknown shift to lower!");
4425
4426   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4427   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4428       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4429     return SDValue();
4430
4431   // If we are in thumb mode, we don't have RRX.
4432   if (ST->isThumb1Only()) return SDValue();
4433
4434   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4435   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4436                            DAG.getConstant(0, MVT::i32));
4437   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4438                            DAG.getConstant(1, MVT::i32));
4439
4440   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4441   // captures the result into a carry flag.
4442   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4443   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4444
4445   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4446   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4447
4448   // Merge the pieces into a single i64 value.
4449  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4450 }
4451
4452 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4453   SDValue TmpOp0, TmpOp1;
4454   bool Invert = false;
4455   bool Swap = false;
4456   unsigned Opc = 0;
4457
4458   SDValue Op0 = Op.getOperand(0);
4459   SDValue Op1 = Op.getOperand(1);
4460   SDValue CC = Op.getOperand(2);
4461   EVT VT = Op.getValueType();
4462   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4463   SDLoc dl(Op);
4464
4465   if (Op1.getValueType().isFloatingPoint()) {
4466     switch (SetCCOpcode) {
4467     default: llvm_unreachable("Illegal FP comparison");
4468     case ISD::SETUNE:
4469     case ISD::SETNE:  Invert = true; // Fallthrough
4470     case ISD::SETOEQ:
4471     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4472     case ISD::SETOLT:
4473     case ISD::SETLT: Swap = true; // Fallthrough
4474     case ISD::SETOGT:
4475     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4476     case ISD::SETOLE:
4477     case ISD::SETLE:  Swap = true; // Fallthrough
4478     case ISD::SETOGE:
4479     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4480     case ISD::SETUGE: Swap = true; // Fallthrough
4481     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4482     case ISD::SETUGT: Swap = true; // Fallthrough
4483     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4484     case ISD::SETUEQ: Invert = true; // Fallthrough
4485     case ISD::SETONE:
4486       // Expand this to (OLT | OGT).
4487       TmpOp0 = Op0;
4488       TmpOp1 = Op1;
4489       Opc = ISD::OR;
4490       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4491       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4492       break;
4493     case ISD::SETUO: Invert = true; // Fallthrough
4494     case ISD::SETO:
4495       // Expand this to (OLT | OGE).
4496       TmpOp0 = Op0;
4497       TmpOp1 = Op1;
4498       Opc = ISD::OR;
4499       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4500       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4501       break;
4502     }
4503   } else {
4504     // Integer comparisons.
4505     switch (SetCCOpcode) {
4506     default: llvm_unreachable("Illegal integer comparison");
4507     case ISD::SETNE:  Invert = true;
4508     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4509     case ISD::SETLT:  Swap = true;
4510     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4511     case ISD::SETLE:  Swap = true;
4512     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4513     case ISD::SETULT: Swap = true;
4514     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4515     case ISD::SETULE: Swap = true;
4516     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4517     }
4518
4519     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4520     if (Opc == ARMISD::VCEQ) {
4521
4522       SDValue AndOp;
4523       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4524         AndOp = Op0;
4525       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4526         AndOp = Op1;
4527
4528       // Ignore bitconvert.
4529       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4530         AndOp = AndOp.getOperand(0);
4531
4532       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4533         Opc = ARMISD::VTST;
4534         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4535         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4536         Invert = !Invert;
4537       }
4538     }
4539   }
4540
4541   if (Swap)
4542     std::swap(Op0, Op1);
4543
4544   // If one of the operands is a constant vector zero, attempt to fold the
4545   // comparison to a specialized compare-against-zero form.
4546   SDValue SingleOp;
4547   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4548     SingleOp = Op0;
4549   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4550     if (Opc == ARMISD::VCGE)
4551       Opc = ARMISD::VCLEZ;
4552     else if (Opc == ARMISD::VCGT)
4553       Opc = ARMISD::VCLTZ;
4554     SingleOp = Op1;
4555   }
4556
4557   SDValue Result;
4558   if (SingleOp.getNode()) {
4559     switch (Opc) {
4560     case ARMISD::VCEQ:
4561       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4562     case ARMISD::VCGE:
4563       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4564     case ARMISD::VCLEZ:
4565       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4566     case ARMISD::VCGT:
4567       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4568     case ARMISD::VCLTZ:
4569       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4570     default:
4571       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4572     }
4573   } else {
4574      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4575   }
4576
4577   if (Invert)
4578     Result = DAG.getNOT(dl, Result, VT);
4579
4580   return Result;
4581 }
4582
4583 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4584 /// valid vector constant for a NEON instruction with a "modified immediate"
4585 /// operand (e.g., VMOV).  If so, return the encoded value.
4586 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4587                                  unsigned SplatBitSize, SelectionDAG &DAG,
4588                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4589   unsigned OpCmode, Imm;
4590
4591   // SplatBitSize is set to the smallest size that splats the vector, so a
4592   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4593   // immediate instructions others than VMOV do not support the 8-bit encoding
4594   // of a zero vector, and the default encoding of zero is supposed to be the
4595   // 32-bit version.
4596   if (SplatBits == 0)
4597     SplatBitSize = 32;
4598
4599   switch (SplatBitSize) {
4600   case 8:
4601     if (type != VMOVModImm)
4602       return SDValue();
4603     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4604     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4605     OpCmode = 0xe;
4606     Imm = SplatBits;
4607     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4608     break;
4609
4610   case 16:
4611     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4612     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4613     if ((SplatBits & ~0xff) == 0) {
4614       // Value = 0x00nn: Op=x, Cmode=100x.
4615       OpCmode = 0x8;
4616       Imm = SplatBits;
4617       break;
4618     }
4619     if ((SplatBits & ~0xff00) == 0) {
4620       // Value = 0xnn00: Op=x, Cmode=101x.
4621       OpCmode = 0xa;
4622       Imm = SplatBits >> 8;
4623       break;
4624     }
4625     return SDValue();
4626
4627   case 32:
4628     // NEON's 32-bit VMOV supports splat values where:
4629     // * only one byte is nonzero, or
4630     // * the least significant byte is 0xff and the second byte is nonzero, or
4631     // * the least significant 2 bytes are 0xff and the third is nonzero.
4632     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4633     if ((SplatBits & ~0xff) == 0) {
4634       // Value = 0x000000nn: Op=x, Cmode=000x.
4635       OpCmode = 0;
4636       Imm = SplatBits;
4637       break;
4638     }
4639     if ((SplatBits & ~0xff00) == 0) {
4640       // Value = 0x0000nn00: Op=x, Cmode=001x.
4641       OpCmode = 0x2;
4642       Imm = SplatBits >> 8;
4643       break;
4644     }
4645     if ((SplatBits & ~0xff0000) == 0) {
4646       // Value = 0x00nn0000: Op=x, Cmode=010x.
4647       OpCmode = 0x4;
4648       Imm = SplatBits >> 16;
4649       break;
4650     }
4651     if ((SplatBits & ~0xff000000) == 0) {
4652       // Value = 0xnn000000: Op=x, Cmode=011x.
4653       OpCmode = 0x6;
4654       Imm = SplatBits >> 24;
4655       break;
4656     }
4657
4658     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4659     if (type == OtherModImm) return SDValue();
4660
4661     if ((SplatBits & ~0xffff) == 0 &&
4662         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4663       // Value = 0x0000nnff: Op=x, Cmode=1100.
4664       OpCmode = 0xc;
4665       Imm = SplatBits >> 8;
4666       break;
4667     }
4668
4669     if ((SplatBits & ~0xffffff) == 0 &&
4670         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4671       // Value = 0x00nnffff: Op=x, Cmode=1101.
4672       OpCmode = 0xd;
4673       Imm = SplatBits >> 16;
4674       break;
4675     }
4676
4677     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4678     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4679     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4680     // and fall through here to test for a valid 64-bit splat.  But, then the
4681     // caller would also need to check and handle the change in size.
4682     return SDValue();
4683
4684   case 64: {
4685     if (type != VMOVModImm)
4686       return SDValue();
4687     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4688     uint64_t BitMask = 0xff;
4689     uint64_t Val = 0;
4690     unsigned ImmMask = 1;
4691     Imm = 0;
4692     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4693       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4694         Val |= BitMask;
4695         Imm |= ImmMask;
4696       } else if ((SplatBits & BitMask) != 0) {
4697         return SDValue();
4698       }
4699       BitMask <<= 8;
4700       ImmMask <<= 1;
4701     }
4702
4703     if (DAG.getTargetLoweringInfo().isBigEndian())
4704       // swap higher and lower 32 bit word
4705       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4706
4707     // Op=1, Cmode=1110.
4708     OpCmode = 0x1e;
4709     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4710     break;
4711   }
4712
4713   default:
4714     llvm_unreachable("unexpected size for isNEONModifiedImm");
4715   }
4716
4717   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4718   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4719 }
4720
4721 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4722                                            const ARMSubtarget *ST) const {
4723   if (!ST->hasVFP3())
4724     return SDValue();
4725
4726   bool IsDouble = Op.getValueType() == MVT::f64;
4727   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4728
4729   // Use the default (constant pool) lowering for double constants when we have
4730   // an SP-only FPU
4731   if (IsDouble && Subtarget->isFPOnlySP())
4732     return SDValue();
4733
4734   // Try splatting with a VMOV.f32...
4735   APFloat FPVal = CFP->getValueAPF();
4736   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4737
4738   if (ImmVal != -1) {
4739     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4740       // We have code in place to select a valid ConstantFP already, no need to
4741       // do any mangling.
4742       return Op;
4743     }
4744
4745     // It's a float and we are trying to use NEON operations where
4746     // possible. Lower it to a splat followed by an extract.
4747     SDLoc DL(Op);
4748     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4749     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4750                                       NewVal);
4751     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4752                        DAG.getConstant(0, MVT::i32));
4753   }
4754
4755   // The rest of our options are NEON only, make sure that's allowed before
4756   // proceeding..
4757   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4758     return SDValue();
4759
4760   EVT VMovVT;
4761   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4762
4763   // It wouldn't really be worth bothering for doubles except for one very
4764   // important value, which does happen to match: 0.0. So make sure we don't do
4765   // anything stupid.
4766   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4767     return SDValue();
4768
4769   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4770   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4771                                      false, VMOVModImm);
4772   if (NewVal != SDValue()) {
4773     SDLoc DL(Op);
4774     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4775                                       NewVal);
4776     if (IsDouble)
4777       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4778
4779     // It's a float: cast and extract a vector element.
4780     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4781                                        VecConstant);
4782     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4783                        DAG.getConstant(0, MVT::i32));
4784   }
4785
4786   // Finally, try a VMVN.i32
4787   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4788                              false, VMVNModImm);
4789   if (NewVal != SDValue()) {
4790     SDLoc DL(Op);
4791     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4792
4793     if (IsDouble)
4794       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4795
4796     // It's a float: cast and extract a vector element.
4797     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4798                                        VecConstant);
4799     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4800                        DAG.getConstant(0, MVT::i32));
4801   }
4802
4803   return SDValue();
4804 }
4805
4806 // check if an VEXT instruction can handle the shuffle mask when the
4807 // vector sources of the shuffle are the same.
4808 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4809   unsigned NumElts = VT.getVectorNumElements();
4810
4811   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4812   if (M[0] < 0)
4813     return false;
4814
4815   Imm = M[0];
4816
4817   // If this is a VEXT shuffle, the immediate value is the index of the first
4818   // element.  The other shuffle indices must be the successive elements after
4819   // the first one.
4820   unsigned ExpectedElt = Imm;
4821   for (unsigned i = 1; i < NumElts; ++i) {
4822     // Increment the expected index.  If it wraps around, just follow it
4823     // back to index zero and keep going.
4824     ++ExpectedElt;
4825     if (ExpectedElt == NumElts)
4826       ExpectedElt = 0;
4827
4828     if (M[i] < 0) continue; // ignore UNDEF indices
4829     if (ExpectedElt != static_cast<unsigned>(M[i]))
4830       return false;
4831   }
4832
4833   return true;
4834 }
4835
4836
4837 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4838                        bool &ReverseVEXT, unsigned &Imm) {
4839   unsigned NumElts = VT.getVectorNumElements();
4840   ReverseVEXT = false;
4841
4842   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4843   if (M[0] < 0)
4844     return false;
4845
4846   Imm = M[0];
4847
4848   // If this is a VEXT shuffle, the immediate value is the index of the first
4849   // element.  The other shuffle indices must be the successive elements after
4850   // the first one.
4851   unsigned ExpectedElt = Imm;
4852   for (unsigned i = 1; i < NumElts; ++i) {
4853     // Increment the expected index.  If it wraps around, it may still be
4854     // a VEXT but the source vectors must be swapped.
4855     ExpectedElt += 1;
4856     if (ExpectedElt == NumElts * 2) {
4857       ExpectedElt = 0;
4858       ReverseVEXT = true;
4859     }
4860
4861     if (M[i] < 0) continue; // ignore UNDEF indices
4862     if (ExpectedElt != static_cast<unsigned>(M[i]))
4863       return false;
4864   }
4865
4866   // Adjust the index value if the source operands will be swapped.
4867   if (ReverseVEXT)
4868     Imm -= NumElts;
4869
4870   return true;
4871 }
4872
4873 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4874 /// instruction with the specified blocksize.  (The order of the elements
4875 /// within each block of the vector is reversed.)
4876 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4877   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4878          "Only possible block sizes for VREV are: 16, 32, 64");
4879
4880   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4881   if (EltSz == 64)
4882     return false;
4883
4884   unsigned NumElts = VT.getVectorNumElements();
4885   unsigned BlockElts = M[0] + 1;
4886   // If the first shuffle index is UNDEF, be optimistic.
4887   if (M[0] < 0)
4888     BlockElts = BlockSize / EltSz;
4889
4890   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4891     return false;
4892
4893   for (unsigned i = 0; i < NumElts; ++i) {
4894     if (M[i] < 0) continue; // ignore UNDEF indices
4895     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4896       return false;
4897   }
4898
4899   return true;
4900 }
4901
4902 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4903   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4904   // range, then 0 is placed into the resulting vector. So pretty much any mask
4905   // of 8 elements can work here.
4906   return VT == MVT::v8i8 && M.size() == 8;
4907 }
4908
4909 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4910   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4911   if (EltSz == 64)
4912     return false;
4913
4914   unsigned NumElts = VT.getVectorNumElements();
4915   WhichResult = (M[0] == 0 ? 0 : 1);
4916   for (unsigned i = 0; i < NumElts; i += 2) {
4917     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4918         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4919       return false;
4920   }
4921   return true;
4922 }
4923
4924 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4925 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4926 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4927 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4928   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4929   if (EltSz == 64)
4930     return false;
4931
4932   unsigned NumElts = VT.getVectorNumElements();
4933   WhichResult = (M[0] == 0 ? 0 : 1);
4934   for (unsigned i = 0; i < NumElts; i += 2) {
4935     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4936         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4937       return false;
4938   }
4939   return true;
4940 }
4941
4942 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4943   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4944   if (EltSz == 64)
4945     return false;
4946
4947   unsigned NumElts = VT.getVectorNumElements();
4948   WhichResult = (M[0] == 0 ? 0 : 1);
4949   for (unsigned i = 0; i != NumElts; ++i) {
4950     if (M[i] < 0) continue; // ignore UNDEF indices
4951     if ((unsigned) M[i] != 2 * i + WhichResult)
4952       return false;
4953   }
4954
4955   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4956   if (VT.is64BitVector() && EltSz == 32)
4957     return false;
4958
4959   return true;
4960 }
4961
4962 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4963 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4964 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4965 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4966   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4967   if (EltSz == 64)
4968     return false;
4969
4970   unsigned Half = VT.getVectorNumElements() / 2;
4971   WhichResult = (M[0] == 0 ? 0 : 1);
4972   for (unsigned j = 0; j != 2; ++j) {
4973     unsigned Idx = WhichResult;
4974     for (unsigned i = 0; i != Half; ++i) {
4975       int MIdx = M[i + j * Half];
4976       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4977         return false;
4978       Idx += 2;
4979     }
4980   }
4981
4982   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4983   if (VT.is64BitVector() && EltSz == 32)
4984     return false;
4985
4986   return true;
4987 }
4988
4989 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4990   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4991   if (EltSz == 64)
4992     return false;
4993
4994   unsigned NumElts = VT.getVectorNumElements();
4995   WhichResult = (M[0] == 0 ? 0 : 1);
4996   unsigned Idx = WhichResult * NumElts / 2;
4997   for (unsigned i = 0; i != NumElts; i += 2) {
4998     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4999         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
5000       return false;
5001     Idx += 1;
5002   }
5003
5004   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5005   if (VT.is64BitVector() && EltSz == 32)
5006     return false;
5007
5008   return true;
5009 }
5010
5011 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5012 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5013 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5014 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5015   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5016   if (EltSz == 64)
5017     return false;
5018
5019   unsigned NumElts = VT.getVectorNumElements();
5020   WhichResult = (M[0] == 0 ? 0 : 1);
5021   unsigned Idx = WhichResult * NumElts / 2;
5022   for (unsigned i = 0; i != NumElts; i += 2) {
5023     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
5024         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
5025       return false;
5026     Idx += 1;
5027   }
5028
5029   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5030   if (VT.is64BitVector() && EltSz == 32)
5031     return false;
5032
5033   return true;
5034 }
5035
5036 /// \return true if this is a reverse operation on an vector.
5037 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5038   unsigned NumElts = VT.getVectorNumElements();
5039   // Make sure the mask has the right size.
5040   if (NumElts != M.size())
5041       return false;
5042
5043   // Look for <15, ..., 3, -1, 1, 0>.
5044   for (unsigned i = 0; i != NumElts; ++i)
5045     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5046       return false;
5047
5048   return true;
5049 }
5050
5051 // If N is an integer constant that can be moved into a register in one
5052 // instruction, return an SDValue of such a constant (will become a MOV
5053 // instruction).  Otherwise return null.
5054 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5055                                      const ARMSubtarget *ST, SDLoc dl) {
5056   uint64_t Val;
5057   if (!isa<ConstantSDNode>(N))
5058     return SDValue();
5059   Val = cast<ConstantSDNode>(N)->getZExtValue();
5060
5061   if (ST->isThumb1Only()) {
5062     if (Val <= 255 || ~Val <= 255)
5063       return DAG.getConstant(Val, MVT::i32);
5064   } else {
5065     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5066       return DAG.getConstant(Val, MVT::i32);
5067   }
5068   return SDValue();
5069 }
5070
5071 // If this is a case we can't handle, return null and let the default
5072 // expansion code take care of it.
5073 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5074                                              const ARMSubtarget *ST) const {
5075   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5076   SDLoc dl(Op);
5077   EVT VT = Op.getValueType();
5078
5079   APInt SplatBits, SplatUndef;
5080   unsigned SplatBitSize;
5081   bool HasAnyUndefs;
5082   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5083     if (SplatBitSize <= 64) {
5084       // Check if an immediate VMOV works.
5085       EVT VmovVT;
5086       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5087                                       SplatUndef.getZExtValue(), SplatBitSize,
5088                                       DAG, VmovVT, VT.is128BitVector(),
5089                                       VMOVModImm);
5090       if (Val.getNode()) {
5091         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5092         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5093       }
5094
5095       // Try an immediate VMVN.
5096       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5097       Val = isNEONModifiedImm(NegatedImm,
5098                                       SplatUndef.getZExtValue(), SplatBitSize,
5099                                       DAG, VmovVT, VT.is128BitVector(),
5100                                       VMVNModImm);
5101       if (Val.getNode()) {
5102         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5103         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5104       }
5105
5106       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5107       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5108         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5109         if (ImmVal != -1) {
5110           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
5111           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5112         }
5113       }
5114     }
5115   }
5116
5117   // Scan through the operands to see if only one value is used.
5118   //
5119   // As an optimisation, even if more than one value is used it may be more
5120   // profitable to splat with one value then change some lanes.
5121   //
5122   // Heuristically we decide to do this if the vector has a "dominant" value,
5123   // defined as splatted to more than half of the lanes.
5124   unsigned NumElts = VT.getVectorNumElements();
5125   bool isOnlyLowElement = true;
5126   bool usesOnlyOneValue = true;
5127   bool hasDominantValue = false;
5128   bool isConstant = true;
5129
5130   // Map of the number of times a particular SDValue appears in the
5131   // element list.
5132   DenseMap<SDValue, unsigned> ValueCounts;
5133   SDValue Value;
5134   for (unsigned i = 0; i < NumElts; ++i) {
5135     SDValue V = Op.getOperand(i);
5136     if (V.getOpcode() == ISD::UNDEF)
5137       continue;
5138     if (i > 0)
5139       isOnlyLowElement = false;
5140     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5141       isConstant = false;
5142
5143     ValueCounts.insert(std::make_pair(V, 0));
5144     unsigned &Count = ValueCounts[V];
5145
5146     // Is this value dominant? (takes up more than half of the lanes)
5147     if (++Count > (NumElts / 2)) {
5148       hasDominantValue = true;
5149       Value = V;
5150     }
5151   }
5152   if (ValueCounts.size() != 1)
5153     usesOnlyOneValue = false;
5154   if (!Value.getNode() && ValueCounts.size() > 0)
5155     Value = ValueCounts.begin()->first;
5156
5157   if (ValueCounts.size() == 0)
5158     return DAG.getUNDEF(VT);
5159
5160   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5161   // Keep going if we are hitting this case.
5162   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5163     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5164
5165   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5166
5167   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5168   // i32 and try again.
5169   if (hasDominantValue && EltSize <= 32) {
5170     if (!isConstant) {
5171       SDValue N;
5172
5173       // If we are VDUPing a value that comes directly from a vector, that will
5174       // cause an unnecessary move to and from a GPR, where instead we could
5175       // just use VDUPLANE. We can only do this if the lane being extracted
5176       // is at a constant index, as the VDUP from lane instructions only have
5177       // constant-index forms.
5178       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5179           isa<ConstantSDNode>(Value->getOperand(1))) {
5180         // We need to create a new undef vector to use for the VDUPLANE if the
5181         // size of the vector from which we get the value is different than the
5182         // size of the vector that we need to create. We will insert the element
5183         // such that the register coalescer will remove unnecessary copies.
5184         if (VT != Value->getOperand(0).getValueType()) {
5185           ConstantSDNode *constIndex;
5186           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5187           assert(constIndex && "The index is not a constant!");
5188           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5189                              VT.getVectorNumElements();
5190           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5191                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5192                         Value, DAG.getConstant(index, MVT::i32)),
5193                            DAG.getConstant(index, MVT::i32));
5194         } else
5195           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5196                         Value->getOperand(0), Value->getOperand(1));
5197       } else
5198         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5199
5200       if (!usesOnlyOneValue) {
5201         // The dominant value was splatted as 'N', but we now have to insert
5202         // all differing elements.
5203         for (unsigned I = 0; I < NumElts; ++I) {
5204           if (Op.getOperand(I) == Value)
5205             continue;
5206           SmallVector<SDValue, 3> Ops;
5207           Ops.push_back(N);
5208           Ops.push_back(Op.getOperand(I));
5209           Ops.push_back(DAG.getConstant(I, MVT::i32));
5210           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5211         }
5212       }
5213       return N;
5214     }
5215     if (VT.getVectorElementType().isFloatingPoint()) {
5216       SmallVector<SDValue, 8> Ops;
5217       for (unsigned i = 0; i < NumElts; ++i)
5218         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5219                                   Op.getOperand(i)));
5220       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5221       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5222       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5223       if (Val.getNode())
5224         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5225     }
5226     if (usesOnlyOneValue) {
5227       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5228       if (isConstant && Val.getNode())
5229         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5230     }
5231   }
5232
5233   // If all elements are constants and the case above didn't get hit, fall back
5234   // to the default expansion, which will generate a load from the constant
5235   // pool.
5236   if (isConstant)
5237     return SDValue();
5238
5239   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5240   if (NumElts >= 4) {
5241     SDValue shuffle = ReconstructShuffle(Op, DAG);
5242     if (shuffle != SDValue())
5243       return shuffle;
5244   }
5245
5246   // Vectors with 32- or 64-bit elements can be built by directly assigning
5247   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5248   // will be legalized.
5249   if (EltSize >= 32) {
5250     // Do the expansion with floating-point types, since that is what the VFP
5251     // registers are defined to use, and since i64 is not legal.
5252     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5253     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5254     SmallVector<SDValue, 8> Ops;
5255     for (unsigned i = 0; i < NumElts; ++i)
5256       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5257     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5258     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5259   }
5260
5261   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5262   // know the default expansion would otherwise fall back on something even
5263   // worse. For a vector with one or two non-undef values, that's
5264   // scalar_to_vector for the elements followed by a shuffle (provided the
5265   // shuffle is valid for the target) and materialization element by element
5266   // on the stack followed by a load for everything else.
5267   if (!isConstant && !usesOnlyOneValue) {
5268     SDValue Vec = DAG.getUNDEF(VT);
5269     for (unsigned i = 0 ; i < NumElts; ++i) {
5270       SDValue V = Op.getOperand(i);
5271       if (V.getOpcode() == ISD::UNDEF)
5272         continue;
5273       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5274       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5275     }
5276     return Vec;
5277   }
5278
5279   return SDValue();
5280 }
5281
5282 // Gather data to see if the operation can be modelled as a
5283 // shuffle in combination with VEXTs.
5284 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5285                                               SelectionDAG &DAG) const {
5286   SDLoc dl(Op);
5287   EVT VT = Op.getValueType();
5288   unsigned NumElts = VT.getVectorNumElements();
5289
5290   SmallVector<SDValue, 2> SourceVecs;
5291   SmallVector<unsigned, 2> MinElts;
5292   SmallVector<unsigned, 2> MaxElts;
5293
5294   for (unsigned i = 0; i < NumElts; ++i) {
5295     SDValue V = Op.getOperand(i);
5296     if (V.getOpcode() == ISD::UNDEF)
5297       continue;
5298     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5299       // A shuffle can only come from building a vector from various
5300       // elements of other vectors.
5301       return SDValue();
5302     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5303                VT.getVectorElementType()) {
5304       // This code doesn't know how to handle shuffles where the vector
5305       // element types do not match (this happens because type legalization
5306       // promotes the return type of EXTRACT_VECTOR_ELT).
5307       // FIXME: It might be appropriate to extend this code to handle
5308       // mismatched types.
5309       return SDValue();
5310     }
5311
5312     // Record this extraction against the appropriate vector if possible...
5313     SDValue SourceVec = V.getOperand(0);
5314     // If the element number isn't a constant, we can't effectively
5315     // analyze what's going on.
5316     if (!isa<ConstantSDNode>(V.getOperand(1)))
5317       return SDValue();
5318     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5319     bool FoundSource = false;
5320     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5321       if (SourceVecs[j] == SourceVec) {
5322         if (MinElts[j] > EltNo)
5323           MinElts[j] = EltNo;
5324         if (MaxElts[j] < EltNo)
5325           MaxElts[j] = EltNo;
5326         FoundSource = true;
5327         break;
5328       }
5329     }
5330
5331     // Or record a new source if not...
5332     if (!FoundSource) {
5333       SourceVecs.push_back(SourceVec);
5334       MinElts.push_back(EltNo);
5335       MaxElts.push_back(EltNo);
5336     }
5337   }
5338
5339   // Currently only do something sane when at most two source vectors
5340   // involved.
5341   if (SourceVecs.size() > 2)
5342     return SDValue();
5343
5344   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5345   int VEXTOffsets[2] = {0, 0};
5346
5347   // This loop extracts the usage patterns of the source vectors
5348   // and prepares appropriate SDValues for a shuffle if possible.
5349   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5350     if (SourceVecs[i].getValueType() == VT) {
5351       // No VEXT necessary
5352       ShuffleSrcs[i] = SourceVecs[i];
5353       VEXTOffsets[i] = 0;
5354       continue;
5355     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5356       // It probably isn't worth padding out a smaller vector just to
5357       // break it down again in a shuffle.
5358       return SDValue();
5359     }
5360
5361     // Since only 64-bit and 128-bit vectors are legal on ARM and
5362     // we've eliminated the other cases...
5363     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5364            "unexpected vector sizes in ReconstructShuffle");
5365
5366     if (MaxElts[i] - MinElts[i] >= NumElts) {
5367       // Span too large for a VEXT to cope
5368       return SDValue();
5369     }
5370
5371     if (MinElts[i] >= NumElts) {
5372       // The extraction can just take the second half
5373       VEXTOffsets[i] = NumElts;
5374       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5375                                    SourceVecs[i],
5376                                    DAG.getIntPtrConstant(NumElts));
5377     } else if (MaxElts[i] < NumElts) {
5378       // The extraction can just take the first half
5379       VEXTOffsets[i] = 0;
5380       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5381                                    SourceVecs[i],
5382                                    DAG.getIntPtrConstant(0));
5383     } else {
5384       // An actual VEXT is needed
5385       VEXTOffsets[i] = MinElts[i];
5386       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5387                                      SourceVecs[i],
5388                                      DAG.getIntPtrConstant(0));
5389       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5390                                      SourceVecs[i],
5391                                      DAG.getIntPtrConstant(NumElts));
5392       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5393                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5394     }
5395   }
5396
5397   SmallVector<int, 8> Mask;
5398
5399   for (unsigned i = 0; i < NumElts; ++i) {
5400     SDValue Entry = Op.getOperand(i);
5401     if (Entry.getOpcode() == ISD::UNDEF) {
5402       Mask.push_back(-1);
5403       continue;
5404     }
5405
5406     SDValue ExtractVec = Entry.getOperand(0);
5407     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5408                                           .getOperand(1))->getSExtValue();
5409     if (ExtractVec == SourceVecs[0]) {
5410       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5411     } else {
5412       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5413     }
5414   }
5415
5416   // Final check before we try to produce nonsense...
5417   if (isShuffleMaskLegal(Mask, VT))
5418     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5419                                 &Mask[0]);
5420
5421   return SDValue();
5422 }
5423
5424 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5425 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5426 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5427 /// are assumed to be legal.
5428 bool
5429 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5430                                       EVT VT) const {
5431   if (VT.getVectorNumElements() == 4 &&
5432       (VT.is128BitVector() || VT.is64BitVector())) {
5433     unsigned PFIndexes[4];
5434     for (unsigned i = 0; i != 4; ++i) {
5435       if (M[i] < 0)
5436         PFIndexes[i] = 8;
5437       else
5438         PFIndexes[i] = M[i];
5439     }
5440
5441     // Compute the index in the perfect shuffle table.
5442     unsigned PFTableIndex =
5443       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5444     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5445     unsigned Cost = (PFEntry >> 30);
5446
5447     if (Cost <= 4)
5448       return true;
5449   }
5450
5451   bool ReverseVEXT;
5452   unsigned Imm, WhichResult;
5453
5454   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5455   return (EltSize >= 32 ||
5456           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5457           isVREVMask(M, VT, 64) ||
5458           isVREVMask(M, VT, 32) ||
5459           isVREVMask(M, VT, 16) ||
5460           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5461           isVTBLMask(M, VT) ||
5462           isVTRNMask(M, VT, WhichResult) ||
5463           isVUZPMask(M, VT, WhichResult) ||
5464           isVZIPMask(M, VT, WhichResult) ||
5465           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5466           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5467           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5468           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5469 }
5470
5471 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5472 /// the specified operations to build the shuffle.
5473 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5474                                       SDValue RHS, SelectionDAG &DAG,
5475                                       SDLoc dl) {
5476   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5477   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5478   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5479
5480   enum {
5481     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5482     OP_VREV,
5483     OP_VDUP0,
5484     OP_VDUP1,
5485     OP_VDUP2,
5486     OP_VDUP3,
5487     OP_VEXT1,
5488     OP_VEXT2,
5489     OP_VEXT3,
5490     OP_VUZPL, // VUZP, left result
5491     OP_VUZPR, // VUZP, right result
5492     OP_VZIPL, // VZIP, left result
5493     OP_VZIPR, // VZIP, right result
5494     OP_VTRNL, // VTRN, left result
5495     OP_VTRNR  // VTRN, right result
5496   };
5497
5498   if (OpNum == OP_COPY) {
5499     if (LHSID == (1*9+2)*9+3) return LHS;
5500     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5501     return RHS;
5502   }
5503
5504   SDValue OpLHS, OpRHS;
5505   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5506   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5507   EVT VT = OpLHS.getValueType();
5508
5509   switch (OpNum) {
5510   default: llvm_unreachable("Unknown shuffle opcode!");
5511   case OP_VREV:
5512     // VREV divides the vector in half and swaps within the half.
5513     if (VT.getVectorElementType() == MVT::i32 ||
5514         VT.getVectorElementType() == MVT::f32)
5515       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5516     // vrev <4 x i16> -> VREV32
5517     if (VT.getVectorElementType() == MVT::i16)
5518       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5519     // vrev <4 x i8> -> VREV16
5520     assert(VT.getVectorElementType() == MVT::i8);
5521     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5522   case OP_VDUP0:
5523   case OP_VDUP1:
5524   case OP_VDUP2:
5525   case OP_VDUP3:
5526     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5527                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5528   case OP_VEXT1:
5529   case OP_VEXT2:
5530   case OP_VEXT3:
5531     return DAG.getNode(ARMISD::VEXT, dl, VT,
5532                        OpLHS, OpRHS,
5533                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5534   case OP_VUZPL:
5535   case OP_VUZPR:
5536     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5537                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5538   case OP_VZIPL:
5539   case OP_VZIPR:
5540     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5541                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5542   case OP_VTRNL:
5543   case OP_VTRNR:
5544     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5545                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5546   }
5547 }
5548
5549 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5550                                        ArrayRef<int> ShuffleMask,
5551                                        SelectionDAG &DAG) {
5552   // Check to see if we can use the VTBL instruction.
5553   SDValue V1 = Op.getOperand(0);
5554   SDValue V2 = Op.getOperand(1);
5555   SDLoc DL(Op);
5556
5557   SmallVector<SDValue, 8> VTBLMask;
5558   for (ArrayRef<int>::iterator
5559          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5560     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5561
5562   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5563     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5564                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5565
5566   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5567                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5568 }
5569
5570 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5571                                                       SelectionDAG &DAG) {
5572   SDLoc DL(Op);
5573   SDValue OpLHS = Op.getOperand(0);
5574   EVT VT = OpLHS.getValueType();
5575
5576   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5577          "Expect an v8i16/v16i8 type");
5578   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5579   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5580   // extract the first 8 bytes into the top double word and the last 8 bytes
5581   // into the bottom double word. The v8i16 case is similar.
5582   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5583   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5584                      DAG.getConstant(ExtractNum, MVT::i32));
5585 }
5586
5587 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5588   SDValue V1 = Op.getOperand(0);
5589   SDValue V2 = Op.getOperand(1);
5590   SDLoc dl(Op);
5591   EVT VT = Op.getValueType();
5592   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5593
5594   // Convert shuffles that are directly supported on NEON to target-specific
5595   // DAG nodes, instead of keeping them as shuffles and matching them again
5596   // during code selection.  This is more efficient and avoids the possibility
5597   // of inconsistencies between legalization and selection.
5598   // FIXME: floating-point vectors should be canonicalized to integer vectors
5599   // of the same time so that they get CSEd properly.
5600   ArrayRef<int> ShuffleMask = SVN->getMask();
5601
5602   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5603   if (EltSize <= 32) {
5604     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5605       int Lane = SVN->getSplatIndex();
5606       // If this is undef splat, generate it via "just" vdup, if possible.
5607       if (Lane == -1) Lane = 0;
5608
5609       // Test if V1 is a SCALAR_TO_VECTOR.
5610       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5611         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5612       }
5613       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5614       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5615       // reaches it).
5616       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5617           !isa<ConstantSDNode>(V1.getOperand(0))) {
5618         bool IsScalarToVector = true;
5619         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5620           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5621             IsScalarToVector = false;
5622             break;
5623           }
5624         if (IsScalarToVector)
5625           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5626       }
5627       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5628                          DAG.getConstant(Lane, MVT::i32));
5629     }
5630
5631     bool ReverseVEXT;
5632     unsigned Imm;
5633     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5634       if (ReverseVEXT)
5635         std::swap(V1, V2);
5636       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5637                          DAG.getConstant(Imm, MVT::i32));
5638     }
5639
5640     if (isVREVMask(ShuffleMask, VT, 64))
5641       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5642     if (isVREVMask(ShuffleMask, VT, 32))
5643       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5644     if (isVREVMask(ShuffleMask, VT, 16))
5645       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5646
5647     if (V2->getOpcode() == ISD::UNDEF &&
5648         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5649       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5650                          DAG.getConstant(Imm, MVT::i32));
5651     }
5652
5653     // Check for Neon shuffles that modify both input vectors in place.
5654     // If both results are used, i.e., if there are two shuffles with the same
5655     // source operands and with masks corresponding to both results of one of
5656     // these operations, DAG memoization will ensure that a single node is
5657     // used for both shuffles.
5658     unsigned WhichResult;
5659     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5660       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5661                          V1, V2).getValue(WhichResult);
5662     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5663       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5664                          V1, V2).getValue(WhichResult);
5665     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5666       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5667                          V1, V2).getValue(WhichResult);
5668
5669     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5670       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5671                          V1, V1).getValue(WhichResult);
5672     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5673       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5674                          V1, V1).getValue(WhichResult);
5675     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5676       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5677                          V1, V1).getValue(WhichResult);
5678   }
5679
5680   // If the shuffle is not directly supported and it has 4 elements, use
5681   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5682   unsigned NumElts = VT.getVectorNumElements();
5683   if (NumElts == 4) {
5684     unsigned PFIndexes[4];
5685     for (unsigned i = 0; i != 4; ++i) {
5686       if (ShuffleMask[i] < 0)
5687         PFIndexes[i] = 8;
5688       else
5689         PFIndexes[i] = ShuffleMask[i];
5690     }
5691
5692     // Compute the index in the perfect shuffle table.
5693     unsigned PFTableIndex =
5694       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5695     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5696     unsigned Cost = (PFEntry >> 30);
5697
5698     if (Cost <= 4)
5699       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5700   }
5701
5702   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5703   if (EltSize >= 32) {
5704     // Do the expansion with floating-point types, since that is what the VFP
5705     // registers are defined to use, and since i64 is not legal.
5706     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5707     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5708     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5709     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5710     SmallVector<SDValue, 8> Ops;
5711     for (unsigned i = 0; i < NumElts; ++i) {
5712       if (ShuffleMask[i] < 0)
5713         Ops.push_back(DAG.getUNDEF(EltVT));
5714       else
5715         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5716                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5717                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5718                                                   MVT::i32)));
5719     }
5720     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5721     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5722   }
5723
5724   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5725     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5726
5727   if (VT == MVT::v8i8) {
5728     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5729     if (NewOp.getNode())
5730       return NewOp;
5731   }
5732
5733   return SDValue();
5734 }
5735
5736 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5737   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5738   SDValue Lane = Op.getOperand(2);
5739   if (!isa<ConstantSDNode>(Lane))
5740     return SDValue();
5741
5742   return Op;
5743 }
5744
5745 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5746   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5747   SDValue Lane = Op.getOperand(1);
5748   if (!isa<ConstantSDNode>(Lane))
5749     return SDValue();
5750
5751   SDValue Vec = Op.getOperand(0);
5752   if (Op.getValueType() == MVT::i32 &&
5753       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5754     SDLoc dl(Op);
5755     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5756   }
5757
5758   return Op;
5759 }
5760
5761 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5762   // The only time a CONCAT_VECTORS operation can have legal types is when
5763   // two 64-bit vectors are concatenated to a 128-bit vector.
5764   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5765          "unexpected CONCAT_VECTORS");
5766   SDLoc dl(Op);
5767   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5768   SDValue Op0 = Op.getOperand(0);
5769   SDValue Op1 = Op.getOperand(1);
5770   if (Op0.getOpcode() != ISD::UNDEF)
5771     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5772                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5773                       DAG.getIntPtrConstant(0));
5774   if (Op1.getOpcode() != ISD::UNDEF)
5775     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5776                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5777                       DAG.getIntPtrConstant(1));
5778   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5779 }
5780
5781 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5782 /// element has been zero/sign-extended, depending on the isSigned parameter,
5783 /// from an integer type half its size.
5784 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5785                                    bool isSigned) {
5786   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5787   EVT VT = N->getValueType(0);
5788   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5789     SDNode *BVN = N->getOperand(0).getNode();
5790     if (BVN->getValueType(0) != MVT::v4i32 ||
5791         BVN->getOpcode() != ISD::BUILD_VECTOR)
5792       return false;
5793     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5794     unsigned HiElt = 1 - LoElt;
5795     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5796     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5797     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5798     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5799     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5800       return false;
5801     if (isSigned) {
5802       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5803           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5804         return true;
5805     } else {
5806       if (Hi0->isNullValue() && Hi1->isNullValue())
5807         return true;
5808     }
5809     return false;
5810   }
5811
5812   if (N->getOpcode() != ISD::BUILD_VECTOR)
5813     return false;
5814
5815   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5816     SDNode *Elt = N->getOperand(i).getNode();
5817     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5818       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5819       unsigned HalfSize = EltSize / 2;
5820       if (isSigned) {
5821         if (!isIntN(HalfSize, C->getSExtValue()))
5822           return false;
5823       } else {
5824         if (!isUIntN(HalfSize, C->getZExtValue()))
5825           return false;
5826       }
5827       continue;
5828     }
5829     return false;
5830   }
5831
5832   return true;
5833 }
5834
5835 /// isSignExtended - Check if a node is a vector value that is sign-extended
5836 /// or a constant BUILD_VECTOR with sign-extended elements.
5837 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5838   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5839     return true;
5840   if (isExtendedBUILD_VECTOR(N, DAG, true))
5841     return true;
5842   return false;
5843 }
5844
5845 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5846 /// or a constant BUILD_VECTOR with zero-extended elements.
5847 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5848   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5849     return true;
5850   if (isExtendedBUILD_VECTOR(N, DAG, false))
5851     return true;
5852   return false;
5853 }
5854
5855 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5856   if (OrigVT.getSizeInBits() >= 64)
5857     return OrigVT;
5858
5859   assert(OrigVT.isSimple() && "Expecting a simple value type");
5860
5861   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5862   switch (OrigSimpleTy) {
5863   default: llvm_unreachable("Unexpected Vector Type");
5864   case MVT::v2i8:
5865   case MVT::v2i16:
5866      return MVT::v2i32;
5867   case MVT::v4i8:
5868     return  MVT::v4i16;
5869   }
5870 }
5871
5872 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5873 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5874 /// We insert the required extension here to get the vector to fill a D register.
5875 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5876                                             const EVT &OrigTy,
5877                                             const EVT &ExtTy,
5878                                             unsigned ExtOpcode) {
5879   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5880   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5881   // 64-bits we need to insert a new extension so that it will be 64-bits.
5882   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5883   if (OrigTy.getSizeInBits() >= 64)
5884     return N;
5885
5886   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5887   EVT NewVT = getExtensionTo64Bits(OrigTy);
5888
5889   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5890 }
5891
5892 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5893 /// does not do any sign/zero extension. If the original vector is less
5894 /// than 64 bits, an appropriate extension will be added after the load to
5895 /// reach a total size of 64 bits. We have to add the extension separately
5896 /// because ARM does not have a sign/zero extending load for vectors.
5897 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5898   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5899
5900   // The load already has the right type.
5901   if (ExtendedTy == LD->getMemoryVT())
5902     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5903                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5904                 LD->isNonTemporal(), LD->isInvariant(),
5905                 LD->getAlignment());
5906
5907   // We need to create a zextload/sextload. We cannot just create a load
5908   // followed by a zext/zext node because LowerMUL is also run during normal
5909   // operation legalization where we can't create illegal types.
5910   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5911                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5912                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5913                         LD->isNonTemporal(), LD->getAlignment());
5914 }
5915
5916 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5917 /// extending load, or BUILD_VECTOR with extended elements, return the
5918 /// unextended value. The unextended vector should be 64 bits so that it can
5919 /// be used as an operand to a VMULL instruction. If the original vector size
5920 /// before extension is less than 64 bits we add a an extension to resize
5921 /// the vector to 64 bits.
5922 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5923   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5924     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5925                                         N->getOperand(0)->getValueType(0),
5926                                         N->getValueType(0),
5927                                         N->getOpcode());
5928
5929   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5930     return SkipLoadExtensionForVMULL(LD, DAG);
5931
5932   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5933   // have been legalized as a BITCAST from v4i32.
5934   if (N->getOpcode() == ISD::BITCAST) {
5935     SDNode *BVN = N->getOperand(0).getNode();
5936     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5937            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5938     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5939     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5940                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5941   }
5942   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5943   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5944   EVT VT = N->getValueType(0);
5945   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5946   unsigned NumElts = VT.getVectorNumElements();
5947   MVT TruncVT = MVT::getIntegerVT(EltSize);
5948   SmallVector<SDValue, 8> Ops;
5949   for (unsigned i = 0; i != NumElts; ++i) {
5950     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5951     const APInt &CInt = C->getAPIntValue();
5952     // Element types smaller than 32 bits are not legal, so use i32 elements.
5953     // The values are implicitly truncated so sext vs. zext doesn't matter.
5954     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5955   }
5956   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5957                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5958 }
5959
5960 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5961   unsigned Opcode = N->getOpcode();
5962   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5963     SDNode *N0 = N->getOperand(0).getNode();
5964     SDNode *N1 = N->getOperand(1).getNode();
5965     return N0->hasOneUse() && N1->hasOneUse() &&
5966       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5967   }
5968   return false;
5969 }
5970
5971 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5972   unsigned Opcode = N->getOpcode();
5973   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5974     SDNode *N0 = N->getOperand(0).getNode();
5975     SDNode *N1 = N->getOperand(1).getNode();
5976     return N0->hasOneUse() && N1->hasOneUse() &&
5977       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5978   }
5979   return false;
5980 }
5981
5982 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5983   // Multiplications are only custom-lowered for 128-bit vectors so that
5984   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5985   EVT VT = Op.getValueType();
5986   assert(VT.is128BitVector() && VT.isInteger() &&
5987          "unexpected type for custom-lowering ISD::MUL");
5988   SDNode *N0 = Op.getOperand(0).getNode();
5989   SDNode *N1 = Op.getOperand(1).getNode();
5990   unsigned NewOpc = 0;
5991   bool isMLA = false;
5992   bool isN0SExt = isSignExtended(N0, DAG);
5993   bool isN1SExt = isSignExtended(N1, DAG);
5994   if (isN0SExt && isN1SExt)
5995     NewOpc = ARMISD::VMULLs;
5996   else {
5997     bool isN0ZExt = isZeroExtended(N0, DAG);
5998     bool isN1ZExt = isZeroExtended(N1, DAG);
5999     if (isN0ZExt && isN1ZExt)
6000       NewOpc = ARMISD::VMULLu;
6001     else if (isN1SExt || isN1ZExt) {
6002       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6003       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6004       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6005         NewOpc = ARMISD::VMULLs;
6006         isMLA = true;
6007       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6008         NewOpc = ARMISD::VMULLu;
6009         isMLA = true;
6010       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6011         std::swap(N0, N1);
6012         NewOpc = ARMISD::VMULLu;
6013         isMLA = true;
6014       }
6015     }
6016
6017     if (!NewOpc) {
6018       if (VT == MVT::v2i64)
6019         // Fall through to expand this.  It is not legal.
6020         return SDValue();
6021       else
6022         // Other vector multiplications are legal.
6023         return Op;
6024     }
6025   }
6026
6027   // Legalize to a VMULL instruction.
6028   SDLoc DL(Op);
6029   SDValue Op0;
6030   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6031   if (!isMLA) {
6032     Op0 = SkipExtensionForVMULL(N0, DAG);
6033     assert(Op0.getValueType().is64BitVector() &&
6034            Op1.getValueType().is64BitVector() &&
6035            "unexpected types for extended operands to VMULL");
6036     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6037   }
6038
6039   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6040   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6041   //   vmull q0, d4, d6
6042   //   vmlal q0, d5, d6
6043   // is faster than
6044   //   vaddl q0, d4, d5
6045   //   vmovl q1, d6
6046   //   vmul  q0, q0, q1
6047   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6048   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6049   EVT Op1VT = Op1.getValueType();
6050   return DAG.getNode(N0->getOpcode(), DL, VT,
6051                      DAG.getNode(NewOpc, DL, VT,
6052                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6053                      DAG.getNode(NewOpc, DL, VT,
6054                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6055 }
6056
6057 static SDValue
6058 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6059   // Convert to float
6060   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6061   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6062   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6063   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6064   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6065   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6066   // Get reciprocal estimate.
6067   // float4 recip = vrecpeq_f32(yf);
6068   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6069                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
6070   // Because char has a smaller range than uchar, we can actually get away
6071   // without any newton steps.  This requires that we use a weird bias
6072   // of 0xb000, however (again, this has been exhaustively tested).
6073   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6074   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6075   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6076   Y = DAG.getConstant(0xb000, MVT::i32);
6077   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6078   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6079   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6080   // Convert back to short.
6081   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6082   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6083   return X;
6084 }
6085
6086 static SDValue
6087 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6088   SDValue N2;
6089   // Convert to float.
6090   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6091   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6092   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6093   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6094   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6095   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6096
6097   // Use reciprocal estimate and one refinement step.
6098   // float4 recip = vrecpeq_f32(yf);
6099   // recip *= vrecpsq_f32(yf, recip);
6100   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6101                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
6102   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6103                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6104                    N1, N2);
6105   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6106   // Because short has a smaller range than ushort, we can actually get away
6107   // with only a single newton step.  This requires that we use a weird bias
6108   // of 89, however (again, this has been exhaustively tested).
6109   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6110   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6111   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6112   N1 = DAG.getConstant(0x89, MVT::i32);
6113   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6114   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6115   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6116   // Convert back to integer and return.
6117   // return vmovn_s32(vcvt_s32_f32(result));
6118   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6119   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6120   return N0;
6121 }
6122
6123 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6124   EVT VT = Op.getValueType();
6125   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6126          "unexpected type for custom-lowering ISD::SDIV");
6127
6128   SDLoc dl(Op);
6129   SDValue N0 = Op.getOperand(0);
6130   SDValue N1 = Op.getOperand(1);
6131   SDValue N2, N3;
6132
6133   if (VT == MVT::v8i8) {
6134     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6135     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6136
6137     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6138                      DAG.getIntPtrConstant(4));
6139     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6140                      DAG.getIntPtrConstant(4));
6141     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6142                      DAG.getIntPtrConstant(0));
6143     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6144                      DAG.getIntPtrConstant(0));
6145
6146     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6147     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6148
6149     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6150     N0 = LowerCONCAT_VECTORS(N0, DAG);
6151
6152     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6153     return N0;
6154   }
6155   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6156 }
6157
6158 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6159   EVT VT = Op.getValueType();
6160   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6161          "unexpected type for custom-lowering ISD::UDIV");
6162
6163   SDLoc dl(Op);
6164   SDValue N0 = Op.getOperand(0);
6165   SDValue N1 = Op.getOperand(1);
6166   SDValue N2, N3;
6167
6168   if (VT == MVT::v8i8) {
6169     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6170     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6171
6172     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6173                      DAG.getIntPtrConstant(4));
6174     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6175                      DAG.getIntPtrConstant(4));
6176     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6177                      DAG.getIntPtrConstant(0));
6178     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6179                      DAG.getIntPtrConstant(0));
6180
6181     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6182     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6183
6184     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6185     N0 = LowerCONCAT_VECTORS(N0, DAG);
6186
6187     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6188                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6189                      N0);
6190     return N0;
6191   }
6192
6193   // v4i16 sdiv ... Convert to float.
6194   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6195   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6196   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6197   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6198   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6199   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6200
6201   // Use reciprocal estimate and two refinement steps.
6202   // float4 recip = vrecpeq_f32(yf);
6203   // recip *= vrecpsq_f32(yf, recip);
6204   // recip *= vrecpsq_f32(yf, recip);
6205   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6206                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6207   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6208                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6209                    BN1, N2);
6210   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6211   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6212                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6213                    BN1, N2);
6214   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6215   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6216   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6217   // and that it will never cause us to return an answer too large).
6218   // float4 result = as_float4(as_int4(xf*recip) + 2);
6219   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6220   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6221   N1 = DAG.getConstant(2, MVT::i32);
6222   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6223   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6224   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6225   // Convert back to integer and return.
6226   // return vmovn_u32(vcvt_s32_f32(result));
6227   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6228   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6229   return N0;
6230 }
6231
6232 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6233   EVT VT = Op.getNode()->getValueType(0);
6234   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6235
6236   unsigned Opc;
6237   bool ExtraOp = false;
6238   switch (Op.getOpcode()) {
6239   default: llvm_unreachable("Invalid code");
6240   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6241   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6242   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6243   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6244   }
6245
6246   if (!ExtraOp)
6247     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6248                        Op.getOperand(1));
6249   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6250                      Op.getOperand(1), Op.getOperand(2));
6251 }
6252
6253 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6254   assert(Subtarget->isTargetDarwin());
6255
6256   // For iOS, we want to call an alternative entry point: __sincos_stret,
6257   // return values are passed via sret.
6258   SDLoc dl(Op);
6259   SDValue Arg = Op.getOperand(0);
6260   EVT ArgVT = Arg.getValueType();
6261   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6262
6263   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6265
6266   // Pair of floats / doubles used to pass the result.
6267   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6268
6269   // Create stack object for sret.
6270   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6271   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6272   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6273   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6274
6275   ArgListTy Args;
6276   ArgListEntry Entry;
6277
6278   Entry.Node = SRet;
6279   Entry.Ty = RetTy->getPointerTo();
6280   Entry.isSExt = false;
6281   Entry.isZExt = false;
6282   Entry.isSRet = true;
6283   Args.push_back(Entry);
6284
6285   Entry.Node = Arg;
6286   Entry.Ty = ArgTy;
6287   Entry.isSExt = false;
6288   Entry.isZExt = false;
6289   Args.push_back(Entry);
6290
6291   const char *LibcallName  = (ArgVT == MVT::f64)
6292   ? "__sincos_stret" : "__sincosf_stret";
6293   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6294
6295   TargetLowering::CallLoweringInfo CLI(DAG);
6296   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6297     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6298                std::move(Args), 0)
6299     .setDiscardResult();
6300
6301   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6302
6303   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6304                                 MachinePointerInfo(), false, false, false, 0);
6305
6306   // Address of cos field.
6307   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6308                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6309   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6310                                 MachinePointerInfo(), false, false, false, 0);
6311
6312   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6313   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6314                      LoadSin.getValue(0), LoadCos.getValue(0));
6315 }
6316
6317 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6318   // Monotonic load/store is legal for all targets
6319   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6320     return Op;
6321
6322   // Acquire/Release load/store is not legal for targets without a
6323   // dmb or equivalent available.
6324   return SDValue();
6325 }
6326
6327 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6328                                     SmallVectorImpl<SDValue> &Results,
6329                                     SelectionDAG &DAG,
6330                                     const ARMSubtarget *Subtarget) {
6331   SDLoc DL(N);
6332   SDValue Cycles32, OutChain;
6333
6334   if (Subtarget->hasPerfMon()) {
6335     // Under Power Management extensions, the cycle-count is:
6336     //    mrc p15, #0, <Rt>, c9, c13, #0
6337     SDValue Ops[] = { N->getOperand(0), // Chain
6338                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6339                       DAG.getConstant(15, MVT::i32),
6340                       DAG.getConstant(0, MVT::i32),
6341                       DAG.getConstant(9, MVT::i32),
6342                       DAG.getConstant(13, MVT::i32),
6343                       DAG.getConstant(0, MVT::i32)
6344     };
6345
6346     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6347                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6348     OutChain = Cycles32.getValue(1);
6349   } else {
6350     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6351     // there are older ARM CPUs that have implementation-specific ways of
6352     // obtaining this information (FIXME!).
6353     Cycles32 = DAG.getConstant(0, MVT::i32);
6354     OutChain = DAG.getEntryNode();
6355   }
6356
6357
6358   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6359                                  Cycles32, DAG.getConstant(0, MVT::i32));
6360   Results.push_back(Cycles64);
6361   Results.push_back(OutChain);
6362 }
6363
6364 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6365   switch (Op.getOpcode()) {
6366   default: llvm_unreachable("Don't know how to custom lower this!");
6367   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6368   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6369   case ISD::GlobalAddress:
6370     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6371     default: llvm_unreachable("unknown object format");
6372     case Triple::COFF:
6373       return LowerGlobalAddressWindows(Op, DAG);
6374     case Triple::ELF:
6375       return LowerGlobalAddressELF(Op, DAG);
6376     case Triple::MachO:
6377       return LowerGlobalAddressDarwin(Op, DAG);
6378     }
6379   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6380   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6381   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6382   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6383   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6384   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6385   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6386   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6387   case ISD::SINT_TO_FP:
6388   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6389   case ISD::FP_TO_SINT:
6390   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6391   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6392   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6393   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6394   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6395   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6396   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6397   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6398                                                                Subtarget);
6399   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6400   case ISD::SHL:
6401   case ISD::SRL:
6402   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6403   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6404   case ISD::SRL_PARTS:
6405   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6406   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6407   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6408   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6409   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6410   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6411   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6412   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6413   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6414   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6415   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6416   case ISD::MUL:           return LowerMUL(Op, DAG);
6417   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6418   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6419   case ISD::ADDC:
6420   case ISD::ADDE:
6421   case ISD::SUBC:
6422   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6423   case ISD::SADDO:
6424   case ISD::UADDO:
6425   case ISD::SSUBO:
6426   case ISD::USUBO:
6427     return LowerXALUO(Op, DAG);
6428   case ISD::ATOMIC_LOAD:
6429   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6430   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6431   case ISD::SDIVREM:
6432   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6433   case ISD::DYNAMIC_STACKALLOC:
6434     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6435       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6436     llvm_unreachable("Don't know how to custom lower this!");
6437   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6438   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6439   }
6440 }
6441
6442 /// ReplaceNodeResults - Replace the results of node with an illegal result
6443 /// type with new values built out of custom code.
6444 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6445                                            SmallVectorImpl<SDValue>&Results,
6446                                            SelectionDAG &DAG) const {
6447   SDValue Res;
6448   switch (N->getOpcode()) {
6449   default:
6450     llvm_unreachable("Don't know how to custom expand this!");
6451   case ISD::BITCAST:
6452     Res = ExpandBITCAST(N, DAG);
6453     break;
6454   case ISD::SRL:
6455   case ISD::SRA:
6456     Res = Expand64BitShift(N, DAG, Subtarget);
6457     break;
6458   case ISD::READCYCLECOUNTER:
6459     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6460     return;
6461   }
6462   if (Res.getNode())
6463     Results.push_back(Res);
6464 }
6465
6466 //===----------------------------------------------------------------------===//
6467 //                           ARM Scheduler Hooks
6468 //===----------------------------------------------------------------------===//
6469
6470 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6471 /// registers the function context.
6472 void ARMTargetLowering::
6473 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6474                        MachineBasicBlock *DispatchBB, int FI) const {
6475   const TargetInstrInfo *TII =
6476       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6477   DebugLoc dl = MI->getDebugLoc();
6478   MachineFunction *MF = MBB->getParent();
6479   MachineRegisterInfo *MRI = &MF->getRegInfo();
6480   MachineConstantPool *MCP = MF->getConstantPool();
6481   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6482   const Function *F = MF->getFunction();
6483
6484   bool isThumb = Subtarget->isThumb();
6485   bool isThumb2 = Subtarget->isThumb2();
6486
6487   unsigned PCLabelId = AFI->createPICLabelUId();
6488   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6489   ARMConstantPoolValue *CPV =
6490     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6491   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6492
6493   const TargetRegisterClass *TRC = isThumb ?
6494     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6495     (const TargetRegisterClass*)&ARM::GPRRegClass;
6496
6497   // Grab constant pool and fixed stack memory operands.
6498   MachineMemOperand *CPMMO =
6499     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6500                              MachineMemOperand::MOLoad, 4, 4);
6501
6502   MachineMemOperand *FIMMOSt =
6503     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6504                              MachineMemOperand::MOStore, 4, 4);
6505
6506   // Load the address of the dispatch MBB into the jump buffer.
6507   if (isThumb2) {
6508     // Incoming value: jbuf
6509     //   ldr.n  r5, LCPI1_1
6510     //   orr    r5, r5, #1
6511     //   add    r5, pc
6512     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6513     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6514     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6515                    .addConstantPoolIndex(CPI)
6516                    .addMemOperand(CPMMO));
6517     // Set the low bit because of thumb mode.
6518     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6519     AddDefaultCC(
6520       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6521                      .addReg(NewVReg1, RegState::Kill)
6522                      .addImm(0x01)));
6523     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6524     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6525       .addReg(NewVReg2, RegState::Kill)
6526       .addImm(PCLabelId);
6527     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6528                    .addReg(NewVReg3, RegState::Kill)
6529                    .addFrameIndex(FI)
6530                    .addImm(36)  // &jbuf[1] :: pc
6531                    .addMemOperand(FIMMOSt));
6532   } else if (isThumb) {
6533     // Incoming value: jbuf
6534     //   ldr.n  r1, LCPI1_4
6535     //   add    r1, pc
6536     //   mov    r2, #1
6537     //   orrs   r1, r2
6538     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6539     //   str    r1, [r2]
6540     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6541     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6542                    .addConstantPoolIndex(CPI)
6543                    .addMemOperand(CPMMO));
6544     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6545     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6546       .addReg(NewVReg1, RegState::Kill)
6547       .addImm(PCLabelId);
6548     // Set the low bit because of thumb mode.
6549     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6551                    .addReg(ARM::CPSR, RegState::Define)
6552                    .addImm(1));
6553     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6554     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6555                    .addReg(ARM::CPSR, RegState::Define)
6556                    .addReg(NewVReg2, RegState::Kill)
6557                    .addReg(NewVReg3, RegState::Kill));
6558     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6559     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6560                    .addFrameIndex(FI)
6561                    .addImm(36)); // &jbuf[1] :: pc
6562     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6563                    .addReg(NewVReg4, RegState::Kill)
6564                    .addReg(NewVReg5, RegState::Kill)
6565                    .addImm(0)
6566                    .addMemOperand(FIMMOSt));
6567   } else {
6568     // Incoming value: jbuf
6569     //   ldr  r1, LCPI1_1
6570     //   add  r1, pc, r1
6571     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6572     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6573     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6574                    .addConstantPoolIndex(CPI)
6575                    .addImm(0)
6576                    .addMemOperand(CPMMO));
6577     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6578     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6579                    .addReg(NewVReg1, RegState::Kill)
6580                    .addImm(PCLabelId));
6581     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6582                    .addReg(NewVReg2, RegState::Kill)
6583                    .addFrameIndex(FI)
6584                    .addImm(36)  // &jbuf[1] :: pc
6585                    .addMemOperand(FIMMOSt));
6586   }
6587 }
6588
6589 MachineBasicBlock *ARMTargetLowering::
6590 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6591   const TargetInstrInfo *TII =
6592       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6593   DebugLoc dl = MI->getDebugLoc();
6594   MachineFunction *MF = MBB->getParent();
6595   MachineRegisterInfo *MRI = &MF->getRegInfo();
6596   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6597   MachineFrameInfo *MFI = MF->getFrameInfo();
6598   int FI = MFI->getFunctionContextIndex();
6599
6600   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6601     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6602     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6603
6604   // Get a mapping of the call site numbers to all of the landing pads they're
6605   // associated with.
6606   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6607   unsigned MaxCSNum = 0;
6608   MachineModuleInfo &MMI = MF->getMMI();
6609   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6610        ++BB) {
6611     if (!BB->isLandingPad()) continue;
6612
6613     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6614     // pad.
6615     for (MachineBasicBlock::iterator
6616            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6617       if (!II->isEHLabel()) continue;
6618
6619       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6620       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6621
6622       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6623       for (SmallVectorImpl<unsigned>::iterator
6624              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6625            CSI != CSE; ++CSI) {
6626         CallSiteNumToLPad[*CSI].push_back(BB);
6627         MaxCSNum = std::max(MaxCSNum, *CSI);
6628       }
6629       break;
6630     }
6631   }
6632
6633   // Get an ordered list of the machine basic blocks for the jump table.
6634   std::vector<MachineBasicBlock*> LPadList;
6635   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6636   LPadList.reserve(CallSiteNumToLPad.size());
6637   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6638     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6639     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6640            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6641       LPadList.push_back(*II);
6642       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6643     }
6644   }
6645
6646   assert(!LPadList.empty() &&
6647          "No landing pad destinations for the dispatch jump table!");
6648
6649   // Create the jump table and associated information.
6650   MachineJumpTableInfo *JTI =
6651     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6652   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6653   unsigned UId = AFI->createJumpTableUId();
6654   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6655
6656   // Create the MBBs for the dispatch code.
6657
6658   // Shove the dispatch's address into the return slot in the function context.
6659   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6660   DispatchBB->setIsLandingPad();
6661
6662   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6663   unsigned trap_opcode;
6664   if (Subtarget->isThumb())
6665     trap_opcode = ARM::tTRAP;
6666   else
6667     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6668
6669   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6670   DispatchBB->addSuccessor(TrapBB);
6671
6672   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6673   DispatchBB->addSuccessor(DispContBB);
6674
6675   // Insert and MBBs.
6676   MF->insert(MF->end(), DispatchBB);
6677   MF->insert(MF->end(), DispContBB);
6678   MF->insert(MF->end(), TrapBB);
6679
6680   // Insert code into the entry block that creates and registers the function
6681   // context.
6682   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6683
6684   MachineMemOperand *FIMMOLd =
6685     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6686                              MachineMemOperand::MOLoad |
6687                              MachineMemOperand::MOVolatile, 4, 4);
6688
6689   MachineInstrBuilder MIB;
6690   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6691
6692   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6693   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6694
6695   // Add a register mask with no preserved registers.  This results in all
6696   // registers being marked as clobbered.
6697   MIB.addRegMask(RI.getNoPreservedMask());
6698
6699   unsigned NumLPads = LPadList.size();
6700   if (Subtarget->isThumb2()) {
6701     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6702     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6703                    .addFrameIndex(FI)
6704                    .addImm(4)
6705                    .addMemOperand(FIMMOLd));
6706
6707     if (NumLPads < 256) {
6708       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6709                      .addReg(NewVReg1)
6710                      .addImm(LPadList.size()));
6711     } else {
6712       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6713       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6714                      .addImm(NumLPads & 0xFFFF));
6715
6716       unsigned VReg2 = VReg1;
6717       if ((NumLPads & 0xFFFF0000) != 0) {
6718         VReg2 = MRI->createVirtualRegister(TRC);
6719         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6720                        .addReg(VReg1)
6721                        .addImm(NumLPads >> 16));
6722       }
6723
6724       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6725                      .addReg(NewVReg1)
6726                      .addReg(VReg2));
6727     }
6728
6729     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6730       .addMBB(TrapBB)
6731       .addImm(ARMCC::HI)
6732       .addReg(ARM::CPSR);
6733
6734     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6735     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6736                    .addJumpTableIndex(MJTI)
6737                    .addImm(UId));
6738
6739     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6740     AddDefaultCC(
6741       AddDefaultPred(
6742         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6743         .addReg(NewVReg3, RegState::Kill)
6744         .addReg(NewVReg1)
6745         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6746
6747     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6748       .addReg(NewVReg4, RegState::Kill)
6749       .addReg(NewVReg1)
6750       .addJumpTableIndex(MJTI)
6751       .addImm(UId);
6752   } else if (Subtarget->isThumb()) {
6753     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6754     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6755                    .addFrameIndex(FI)
6756                    .addImm(1)
6757                    .addMemOperand(FIMMOLd));
6758
6759     if (NumLPads < 256) {
6760       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6761                      .addReg(NewVReg1)
6762                      .addImm(NumLPads));
6763     } else {
6764       MachineConstantPool *ConstantPool = MF->getConstantPool();
6765       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6766       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6767
6768       // MachineConstantPool wants an explicit alignment.
6769       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6770       if (Align == 0)
6771         Align = getDataLayout()->getTypeAllocSize(C->getType());
6772       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6773
6774       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6775       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6776                      .addReg(VReg1, RegState::Define)
6777                      .addConstantPoolIndex(Idx));
6778       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6779                      .addReg(NewVReg1)
6780                      .addReg(VReg1));
6781     }
6782
6783     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6784       .addMBB(TrapBB)
6785       .addImm(ARMCC::HI)
6786       .addReg(ARM::CPSR);
6787
6788     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6789     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6790                    .addReg(ARM::CPSR, RegState::Define)
6791                    .addReg(NewVReg1)
6792                    .addImm(2));
6793
6794     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6795     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6796                    .addJumpTableIndex(MJTI)
6797                    .addImm(UId));
6798
6799     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6800     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6801                    .addReg(ARM::CPSR, RegState::Define)
6802                    .addReg(NewVReg2, RegState::Kill)
6803                    .addReg(NewVReg3));
6804
6805     MachineMemOperand *JTMMOLd =
6806       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6807                                MachineMemOperand::MOLoad, 4, 4);
6808
6809     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6810     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6811                    .addReg(NewVReg4, RegState::Kill)
6812                    .addImm(0)
6813                    .addMemOperand(JTMMOLd));
6814
6815     unsigned NewVReg6 = NewVReg5;
6816     if (RelocM == Reloc::PIC_) {
6817       NewVReg6 = MRI->createVirtualRegister(TRC);
6818       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6819                      .addReg(ARM::CPSR, RegState::Define)
6820                      .addReg(NewVReg5, RegState::Kill)
6821                      .addReg(NewVReg3));
6822     }
6823
6824     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6825       .addReg(NewVReg6, RegState::Kill)
6826       .addJumpTableIndex(MJTI)
6827       .addImm(UId);
6828   } else {
6829     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6830     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6831                    .addFrameIndex(FI)
6832                    .addImm(4)
6833                    .addMemOperand(FIMMOLd));
6834
6835     if (NumLPads < 256) {
6836       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6837                      .addReg(NewVReg1)
6838                      .addImm(NumLPads));
6839     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6840       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6841       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6842                      .addImm(NumLPads & 0xFFFF));
6843
6844       unsigned VReg2 = VReg1;
6845       if ((NumLPads & 0xFFFF0000) != 0) {
6846         VReg2 = MRI->createVirtualRegister(TRC);
6847         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6848                        .addReg(VReg1)
6849                        .addImm(NumLPads >> 16));
6850       }
6851
6852       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6853                      .addReg(NewVReg1)
6854                      .addReg(VReg2));
6855     } else {
6856       MachineConstantPool *ConstantPool = MF->getConstantPool();
6857       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6858       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6859
6860       // MachineConstantPool wants an explicit alignment.
6861       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6862       if (Align == 0)
6863         Align = getDataLayout()->getTypeAllocSize(C->getType());
6864       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6865
6866       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6867       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6868                      .addReg(VReg1, RegState::Define)
6869                      .addConstantPoolIndex(Idx)
6870                      .addImm(0));
6871       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6872                      .addReg(NewVReg1)
6873                      .addReg(VReg1, RegState::Kill));
6874     }
6875
6876     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6877       .addMBB(TrapBB)
6878       .addImm(ARMCC::HI)
6879       .addReg(ARM::CPSR);
6880
6881     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6882     AddDefaultCC(
6883       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6884                      .addReg(NewVReg1)
6885                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6886     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6887     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6888                    .addJumpTableIndex(MJTI)
6889                    .addImm(UId));
6890
6891     MachineMemOperand *JTMMOLd =
6892       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6893                                MachineMemOperand::MOLoad, 4, 4);
6894     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6895     AddDefaultPred(
6896       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6897       .addReg(NewVReg3, RegState::Kill)
6898       .addReg(NewVReg4)
6899       .addImm(0)
6900       .addMemOperand(JTMMOLd));
6901
6902     if (RelocM == Reloc::PIC_) {
6903       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6904         .addReg(NewVReg5, RegState::Kill)
6905         .addReg(NewVReg4)
6906         .addJumpTableIndex(MJTI)
6907         .addImm(UId);
6908     } else {
6909       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6910         .addReg(NewVReg5, RegState::Kill)
6911         .addJumpTableIndex(MJTI)
6912         .addImm(UId);
6913     }
6914   }
6915
6916   // Add the jump table entries as successors to the MBB.
6917   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6918   for (std::vector<MachineBasicBlock*>::iterator
6919          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6920     MachineBasicBlock *CurMBB = *I;
6921     if (SeenMBBs.insert(CurMBB))
6922       DispContBB->addSuccessor(CurMBB);
6923   }
6924
6925   // N.B. the order the invoke BBs are processed in doesn't matter here.
6926   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6927   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6928   for (MachineBasicBlock *BB : InvokeBBs) {
6929
6930     // Remove the landing pad successor from the invoke block and replace it
6931     // with the new dispatch block.
6932     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6933                                                   BB->succ_end());
6934     while (!Successors.empty()) {
6935       MachineBasicBlock *SMBB = Successors.pop_back_val();
6936       if (SMBB->isLandingPad()) {
6937         BB->removeSuccessor(SMBB);
6938         MBBLPads.push_back(SMBB);
6939       }
6940     }
6941
6942     BB->addSuccessor(DispatchBB);
6943
6944     // Find the invoke call and mark all of the callee-saved registers as
6945     // 'implicit defined' so that they're spilled. This prevents code from
6946     // moving instructions to before the EH block, where they will never be
6947     // executed.
6948     for (MachineBasicBlock::reverse_iterator
6949            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6950       if (!II->isCall()) continue;
6951
6952       DenseMap<unsigned, bool> DefRegs;
6953       for (MachineInstr::mop_iterator
6954              OI = II->operands_begin(), OE = II->operands_end();
6955            OI != OE; ++OI) {
6956         if (!OI->isReg()) continue;
6957         DefRegs[OI->getReg()] = true;
6958       }
6959
6960       MachineInstrBuilder MIB(*MF, &*II);
6961
6962       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6963         unsigned Reg = SavedRegs[i];
6964         if (Subtarget->isThumb2() &&
6965             !ARM::tGPRRegClass.contains(Reg) &&
6966             !ARM::hGPRRegClass.contains(Reg))
6967           continue;
6968         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6969           continue;
6970         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6971           continue;
6972         if (!DefRegs[Reg])
6973           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6974       }
6975
6976       break;
6977     }
6978   }
6979
6980   // Mark all former landing pads as non-landing pads. The dispatch is the only
6981   // landing pad now.
6982   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6983          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6984     (*I)->setIsLandingPad(false);
6985
6986   // The instruction is gone now.
6987   MI->eraseFromParent();
6988
6989   return MBB;
6990 }
6991
6992 static
6993 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6994   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6995        E = MBB->succ_end(); I != E; ++I)
6996     if (*I != Succ)
6997       return *I;
6998   llvm_unreachable("Expecting a BB with two successors!");
6999 }
7000
7001 /// Return the load opcode for a given load size. If load size >= 8,
7002 /// neon opcode will be returned.
7003 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7004   if (LdSize >= 8)
7005     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7006                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7007   if (IsThumb1)
7008     return LdSize == 4 ? ARM::tLDRi
7009                        : LdSize == 2 ? ARM::tLDRHi
7010                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7011   if (IsThumb2)
7012     return LdSize == 4 ? ARM::t2LDR_POST
7013                        : LdSize == 2 ? ARM::t2LDRH_POST
7014                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7015   return LdSize == 4 ? ARM::LDR_POST_IMM
7016                      : LdSize == 2 ? ARM::LDRH_POST
7017                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7018 }
7019
7020 /// Return the store opcode for a given store size. If store size >= 8,
7021 /// neon opcode will be returned.
7022 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7023   if (StSize >= 8)
7024     return StSize == 16 ? ARM::VST1q32wb_fixed
7025                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7026   if (IsThumb1)
7027     return StSize == 4 ? ARM::tSTRi
7028                        : StSize == 2 ? ARM::tSTRHi
7029                                      : StSize == 1 ? ARM::tSTRBi : 0;
7030   if (IsThumb2)
7031     return StSize == 4 ? ARM::t2STR_POST
7032                        : StSize == 2 ? ARM::t2STRH_POST
7033                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7034   return StSize == 4 ? ARM::STR_POST_IMM
7035                      : StSize == 2 ? ARM::STRH_POST
7036                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7037 }
7038
7039 /// Emit a post-increment load operation with given size. The instructions
7040 /// will be added to BB at Pos.
7041 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7042                        const TargetInstrInfo *TII, DebugLoc dl,
7043                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7044                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7045   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7046   assert(LdOpc != 0 && "Should have a load opcode");
7047   if (LdSize >= 8) {
7048     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7049                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7050                        .addImm(0));
7051   } else if (IsThumb1) {
7052     // load + update AddrIn
7053     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7054                        .addReg(AddrIn).addImm(0));
7055     MachineInstrBuilder MIB =
7056         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7057     MIB = AddDefaultT1CC(MIB);
7058     MIB.addReg(AddrIn).addImm(LdSize);
7059     AddDefaultPred(MIB);
7060   } else if (IsThumb2) {
7061     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7062                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7063                        .addImm(LdSize));
7064   } else { // arm
7065     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7066                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7067                        .addReg(0).addImm(LdSize));
7068   }
7069 }
7070
7071 /// Emit a post-increment store operation with given size. The instructions
7072 /// will be added to BB at Pos.
7073 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7074                        const TargetInstrInfo *TII, DebugLoc dl,
7075                        unsigned StSize, unsigned Data, unsigned AddrIn,
7076                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7077   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7078   assert(StOpc != 0 && "Should have a store opcode");
7079   if (StSize >= 8) {
7080     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7081                        .addReg(AddrIn).addImm(0).addReg(Data));
7082   } else if (IsThumb1) {
7083     // store + update AddrIn
7084     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7085                        .addReg(AddrIn).addImm(0));
7086     MachineInstrBuilder MIB =
7087         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7088     MIB = AddDefaultT1CC(MIB);
7089     MIB.addReg(AddrIn).addImm(StSize);
7090     AddDefaultPred(MIB);
7091   } else if (IsThumb2) {
7092     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7093                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7094   } else { // arm
7095     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7096                        .addReg(Data).addReg(AddrIn).addReg(0)
7097                        .addImm(StSize));
7098   }
7099 }
7100
7101 MachineBasicBlock *
7102 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7103                                    MachineBasicBlock *BB) const {
7104   // This pseudo instruction has 3 operands: dst, src, size
7105   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7106   // Otherwise, we will generate unrolled scalar copies.
7107   const TargetInstrInfo *TII =
7108       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7109   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7110   MachineFunction::iterator It = BB;
7111   ++It;
7112
7113   unsigned dest = MI->getOperand(0).getReg();
7114   unsigned src = MI->getOperand(1).getReg();
7115   unsigned SizeVal = MI->getOperand(2).getImm();
7116   unsigned Align = MI->getOperand(3).getImm();
7117   DebugLoc dl = MI->getDebugLoc();
7118
7119   MachineFunction *MF = BB->getParent();
7120   MachineRegisterInfo &MRI = MF->getRegInfo();
7121   unsigned UnitSize = 0;
7122   const TargetRegisterClass *TRC = nullptr;
7123   const TargetRegisterClass *VecTRC = nullptr;
7124
7125   bool IsThumb1 = Subtarget->isThumb1Only();
7126   bool IsThumb2 = Subtarget->isThumb2();
7127
7128   if (Align & 1) {
7129     UnitSize = 1;
7130   } else if (Align & 2) {
7131     UnitSize = 2;
7132   } else {
7133     // Check whether we can use NEON instructions.
7134     if (!MF->getFunction()->getAttributes().
7135           hasAttribute(AttributeSet::FunctionIndex,
7136                        Attribute::NoImplicitFloat) &&
7137         Subtarget->hasNEON()) {
7138       if ((Align % 16 == 0) && SizeVal >= 16)
7139         UnitSize = 16;
7140       else if ((Align % 8 == 0) && SizeVal >= 8)
7141         UnitSize = 8;
7142     }
7143     // Can't use NEON instructions.
7144     if (UnitSize == 0)
7145       UnitSize = 4;
7146   }
7147
7148   // Select the correct opcode and register class for unit size load/store
7149   bool IsNeon = UnitSize >= 8;
7150   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
7151                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
7152   if (IsNeon)
7153     VecTRC = UnitSize == 16
7154                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
7155                  : UnitSize == 8
7156                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
7157                        : nullptr;
7158
7159   unsigned BytesLeft = SizeVal % UnitSize;
7160   unsigned LoopSize = SizeVal - BytesLeft;
7161
7162   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7163     // Use LDR and STR to copy.
7164     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7165     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7166     unsigned srcIn = src;
7167     unsigned destIn = dest;
7168     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7169       unsigned srcOut = MRI.createVirtualRegister(TRC);
7170       unsigned destOut = MRI.createVirtualRegister(TRC);
7171       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7172       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7173                  IsThumb1, IsThumb2);
7174       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7175                  IsThumb1, IsThumb2);
7176       srcIn = srcOut;
7177       destIn = destOut;
7178     }
7179
7180     // Handle the leftover bytes with LDRB and STRB.
7181     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7182     // [destOut] = STRB_POST(scratch, destIn, 1)
7183     for (unsigned i = 0; i < BytesLeft; i++) {
7184       unsigned srcOut = MRI.createVirtualRegister(TRC);
7185       unsigned destOut = MRI.createVirtualRegister(TRC);
7186       unsigned scratch = MRI.createVirtualRegister(TRC);
7187       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7188                  IsThumb1, IsThumb2);
7189       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7190                  IsThumb1, IsThumb2);
7191       srcIn = srcOut;
7192       destIn = destOut;
7193     }
7194     MI->eraseFromParent();   // The instruction is gone now.
7195     return BB;
7196   }
7197
7198   // Expand the pseudo op to a loop.
7199   // thisMBB:
7200   //   ...
7201   //   movw varEnd, # --> with thumb2
7202   //   movt varEnd, #
7203   //   ldrcp varEnd, idx --> without thumb2
7204   //   fallthrough --> loopMBB
7205   // loopMBB:
7206   //   PHI varPhi, varEnd, varLoop
7207   //   PHI srcPhi, src, srcLoop
7208   //   PHI destPhi, dst, destLoop
7209   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7210   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7211   //   subs varLoop, varPhi, #UnitSize
7212   //   bne loopMBB
7213   //   fallthrough --> exitMBB
7214   // exitMBB:
7215   //   epilogue to handle left-over bytes
7216   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7217   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7218   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7219   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7220   MF->insert(It, loopMBB);
7221   MF->insert(It, exitMBB);
7222
7223   // Transfer the remainder of BB and its successor edges to exitMBB.
7224   exitMBB->splice(exitMBB->begin(), BB,
7225                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7226   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7227
7228   // Load an immediate to varEnd.
7229   unsigned varEnd = MRI.createVirtualRegister(TRC);
7230   if (IsThumb2) {
7231     unsigned Vtmp = varEnd;
7232     if ((LoopSize & 0xFFFF0000) != 0)
7233       Vtmp = MRI.createVirtualRegister(TRC);
7234     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7235                        .addImm(LoopSize & 0xFFFF));
7236
7237     if ((LoopSize & 0xFFFF0000) != 0)
7238       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7239                          .addReg(Vtmp).addImm(LoopSize >> 16));
7240   } else {
7241     MachineConstantPool *ConstantPool = MF->getConstantPool();
7242     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7243     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7244
7245     // MachineConstantPool wants an explicit alignment.
7246     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7247     if (Align == 0)
7248       Align = getDataLayout()->getTypeAllocSize(C->getType());
7249     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7250
7251     if (IsThumb1)
7252       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7253           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7254     else
7255       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7256           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7257   }
7258   BB->addSuccessor(loopMBB);
7259
7260   // Generate the loop body:
7261   //   varPhi = PHI(varLoop, varEnd)
7262   //   srcPhi = PHI(srcLoop, src)
7263   //   destPhi = PHI(destLoop, dst)
7264   MachineBasicBlock *entryBB = BB;
7265   BB = loopMBB;
7266   unsigned varLoop = MRI.createVirtualRegister(TRC);
7267   unsigned varPhi = MRI.createVirtualRegister(TRC);
7268   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7269   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7270   unsigned destLoop = MRI.createVirtualRegister(TRC);
7271   unsigned destPhi = MRI.createVirtualRegister(TRC);
7272
7273   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7274     .addReg(varLoop).addMBB(loopMBB)
7275     .addReg(varEnd).addMBB(entryBB);
7276   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7277     .addReg(srcLoop).addMBB(loopMBB)
7278     .addReg(src).addMBB(entryBB);
7279   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7280     .addReg(destLoop).addMBB(loopMBB)
7281     .addReg(dest).addMBB(entryBB);
7282
7283   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7284   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7285   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7286   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7287              IsThumb1, IsThumb2);
7288   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7289              IsThumb1, IsThumb2);
7290
7291   // Decrement loop variable by UnitSize.
7292   if (IsThumb1) {
7293     MachineInstrBuilder MIB =
7294         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7295     MIB = AddDefaultT1CC(MIB);
7296     MIB.addReg(varPhi).addImm(UnitSize);
7297     AddDefaultPred(MIB);
7298   } else {
7299     MachineInstrBuilder MIB =
7300         BuildMI(*BB, BB->end(), dl,
7301                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7302     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7303     MIB->getOperand(5).setReg(ARM::CPSR);
7304     MIB->getOperand(5).setIsDef(true);
7305   }
7306   BuildMI(*BB, BB->end(), dl,
7307           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7308       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7309
7310   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7311   BB->addSuccessor(loopMBB);
7312   BB->addSuccessor(exitMBB);
7313
7314   // Add epilogue to handle BytesLeft.
7315   BB = exitMBB;
7316   MachineInstr *StartOfExit = exitMBB->begin();
7317
7318   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7319   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7320   unsigned srcIn = srcLoop;
7321   unsigned destIn = destLoop;
7322   for (unsigned i = 0; i < BytesLeft; i++) {
7323     unsigned srcOut = MRI.createVirtualRegister(TRC);
7324     unsigned destOut = MRI.createVirtualRegister(TRC);
7325     unsigned scratch = MRI.createVirtualRegister(TRC);
7326     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7327                IsThumb1, IsThumb2);
7328     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7329                IsThumb1, IsThumb2);
7330     srcIn = srcOut;
7331     destIn = destOut;
7332   }
7333
7334   MI->eraseFromParent();   // The instruction is gone now.
7335   return BB;
7336 }
7337
7338 MachineBasicBlock *
7339 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7340                                        MachineBasicBlock *MBB) const {
7341   const TargetMachine &TM = getTargetMachine();
7342   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
7343   DebugLoc DL = MI->getDebugLoc();
7344
7345   assert(Subtarget->isTargetWindows() &&
7346          "__chkstk is only supported on Windows");
7347   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7348
7349   // __chkstk takes the number of words to allocate on the stack in R4, and
7350   // returns the stack adjustment in number of bytes in R4.  This will not
7351   // clober any other registers (other than the obvious lr).
7352   //
7353   // Although, technically, IP should be considered a register which may be
7354   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7355   // thumb-2 environment, so there is no interworking required.  As a result, we
7356   // do not expect a veneer to be emitted by the linker, clobbering IP.
7357   //
7358   // Each module receives its own copy of __chkstk, so no import thunk is
7359   // required, again, ensuring that IP is not clobbered.
7360   //
7361   // Finally, although some linkers may theoretically provide a trampoline for
7362   // out of range calls (which is quite common due to a 32M range limitation of
7363   // branches for Thumb), we can generate the long-call version via
7364   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7365   // IP.
7366
7367   switch (TM.getCodeModel()) {
7368   case CodeModel::Small:
7369   case CodeModel::Medium:
7370   case CodeModel::Default:
7371   case CodeModel::Kernel:
7372     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7373       .addImm((unsigned)ARMCC::AL).addReg(0)
7374       .addExternalSymbol("__chkstk")
7375       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7376       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7377       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7378     break;
7379   case CodeModel::Large:
7380   case CodeModel::JITDefault: {
7381     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7382     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7383
7384     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7385       .addExternalSymbol("__chkstk");
7386     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7387       .addImm((unsigned)ARMCC::AL).addReg(0)
7388       .addReg(Reg, RegState::Kill)
7389       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7390       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7391       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7392     break;
7393   }
7394   }
7395
7396   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7397                                       ARM::SP)
7398                               .addReg(ARM::SP).addReg(ARM::R4)));
7399
7400   MI->eraseFromParent();
7401   return MBB;
7402 }
7403
7404 MachineBasicBlock *
7405 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7406                                                MachineBasicBlock *BB) const {
7407   const TargetInstrInfo *TII =
7408       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7409   DebugLoc dl = MI->getDebugLoc();
7410   bool isThumb2 = Subtarget->isThumb2();
7411   switch (MI->getOpcode()) {
7412   default: {
7413     MI->dump();
7414     llvm_unreachable("Unexpected instr type to insert");
7415   }
7416   // The Thumb2 pre-indexed stores have the same MI operands, they just
7417   // define them differently in the .td files from the isel patterns, so
7418   // they need pseudos.
7419   case ARM::t2STR_preidx:
7420     MI->setDesc(TII->get(ARM::t2STR_PRE));
7421     return BB;
7422   case ARM::t2STRB_preidx:
7423     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7424     return BB;
7425   case ARM::t2STRH_preidx:
7426     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7427     return BB;
7428
7429   case ARM::STRi_preidx:
7430   case ARM::STRBi_preidx: {
7431     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7432       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7433     // Decode the offset.
7434     unsigned Offset = MI->getOperand(4).getImm();
7435     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7436     Offset = ARM_AM::getAM2Offset(Offset);
7437     if (isSub)
7438       Offset = -Offset;
7439
7440     MachineMemOperand *MMO = *MI->memoperands_begin();
7441     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7442       .addOperand(MI->getOperand(0))  // Rn_wb
7443       .addOperand(MI->getOperand(1))  // Rt
7444       .addOperand(MI->getOperand(2))  // Rn
7445       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7446       .addOperand(MI->getOperand(5))  // pred
7447       .addOperand(MI->getOperand(6))
7448       .addMemOperand(MMO);
7449     MI->eraseFromParent();
7450     return BB;
7451   }
7452   case ARM::STRr_preidx:
7453   case ARM::STRBr_preidx:
7454   case ARM::STRH_preidx: {
7455     unsigned NewOpc;
7456     switch (MI->getOpcode()) {
7457     default: llvm_unreachable("unexpected opcode!");
7458     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7459     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7460     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7461     }
7462     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7463     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7464       MIB.addOperand(MI->getOperand(i));
7465     MI->eraseFromParent();
7466     return BB;
7467   }
7468
7469   case ARM::tMOVCCr_pseudo: {
7470     // To "insert" a SELECT_CC instruction, we actually have to insert the
7471     // diamond control-flow pattern.  The incoming instruction knows the
7472     // destination vreg to set, the condition code register to branch on, the
7473     // true/false values to select between, and a branch opcode to use.
7474     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7475     MachineFunction::iterator It = BB;
7476     ++It;
7477
7478     //  thisMBB:
7479     //  ...
7480     //   TrueVal = ...
7481     //   cmpTY ccX, r1, r2
7482     //   bCC copy1MBB
7483     //   fallthrough --> copy0MBB
7484     MachineBasicBlock *thisMBB  = BB;
7485     MachineFunction *F = BB->getParent();
7486     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7487     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7488     F->insert(It, copy0MBB);
7489     F->insert(It, sinkMBB);
7490
7491     // Transfer the remainder of BB and its successor edges to sinkMBB.
7492     sinkMBB->splice(sinkMBB->begin(), BB,
7493                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7494     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7495
7496     BB->addSuccessor(copy0MBB);
7497     BB->addSuccessor(sinkMBB);
7498
7499     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7500       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7501
7502     //  copy0MBB:
7503     //   %FalseValue = ...
7504     //   # fallthrough to sinkMBB
7505     BB = copy0MBB;
7506
7507     // Update machine-CFG edges
7508     BB->addSuccessor(sinkMBB);
7509
7510     //  sinkMBB:
7511     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7512     //  ...
7513     BB = sinkMBB;
7514     BuildMI(*BB, BB->begin(), dl,
7515             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7516       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7517       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7518
7519     MI->eraseFromParent();   // The pseudo instruction is gone now.
7520     return BB;
7521   }
7522
7523   case ARM::BCCi64:
7524   case ARM::BCCZi64: {
7525     // If there is an unconditional branch to the other successor, remove it.
7526     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7527
7528     // Compare both parts that make up the double comparison separately for
7529     // equality.
7530     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7531
7532     unsigned LHS1 = MI->getOperand(1).getReg();
7533     unsigned LHS2 = MI->getOperand(2).getReg();
7534     if (RHSisZero) {
7535       AddDefaultPred(BuildMI(BB, dl,
7536                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7537                      .addReg(LHS1).addImm(0));
7538       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7539         .addReg(LHS2).addImm(0)
7540         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7541     } else {
7542       unsigned RHS1 = MI->getOperand(3).getReg();
7543       unsigned RHS2 = MI->getOperand(4).getReg();
7544       AddDefaultPred(BuildMI(BB, dl,
7545                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7546                      .addReg(LHS1).addReg(RHS1));
7547       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7548         .addReg(LHS2).addReg(RHS2)
7549         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7550     }
7551
7552     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7553     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7554     if (MI->getOperand(0).getImm() == ARMCC::NE)
7555       std::swap(destMBB, exitMBB);
7556
7557     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7558       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7559     if (isThumb2)
7560       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7561     else
7562       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7563
7564     MI->eraseFromParent();   // The pseudo instruction is gone now.
7565     return BB;
7566   }
7567
7568   case ARM::Int_eh_sjlj_setjmp:
7569   case ARM::Int_eh_sjlj_setjmp_nofp:
7570   case ARM::tInt_eh_sjlj_setjmp:
7571   case ARM::t2Int_eh_sjlj_setjmp:
7572   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7573     EmitSjLjDispatchBlock(MI, BB);
7574     return BB;
7575
7576   case ARM::ABS:
7577   case ARM::t2ABS: {
7578     // To insert an ABS instruction, we have to insert the
7579     // diamond control-flow pattern.  The incoming instruction knows the
7580     // source vreg to test against 0, the destination vreg to set,
7581     // the condition code register to branch on, the
7582     // true/false values to select between, and a branch opcode to use.
7583     // It transforms
7584     //     V1 = ABS V0
7585     // into
7586     //     V2 = MOVS V0
7587     //     BCC                      (branch to SinkBB if V0 >= 0)
7588     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7589     //     SinkBB: V1 = PHI(V2, V3)
7590     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7591     MachineFunction::iterator BBI = BB;
7592     ++BBI;
7593     MachineFunction *Fn = BB->getParent();
7594     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7595     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7596     Fn->insert(BBI, RSBBB);
7597     Fn->insert(BBI, SinkBB);
7598
7599     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7600     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7601     bool isThumb2 = Subtarget->isThumb2();
7602     MachineRegisterInfo &MRI = Fn->getRegInfo();
7603     // In Thumb mode S must not be specified if source register is the SP or
7604     // PC and if destination register is the SP, so restrict register class
7605     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7606       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7607       (const TargetRegisterClass*)&ARM::GPRRegClass);
7608
7609     // Transfer the remainder of BB and its successor edges to sinkMBB.
7610     SinkBB->splice(SinkBB->begin(), BB,
7611                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7612     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7613
7614     BB->addSuccessor(RSBBB);
7615     BB->addSuccessor(SinkBB);
7616
7617     // fall through to SinkMBB
7618     RSBBB->addSuccessor(SinkBB);
7619
7620     // insert a cmp at the end of BB
7621     AddDefaultPred(BuildMI(BB, dl,
7622                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7623                    .addReg(ABSSrcReg).addImm(0));
7624
7625     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7626     BuildMI(BB, dl,
7627       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7628       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7629
7630     // insert rsbri in RSBBB
7631     // Note: BCC and rsbri will be converted into predicated rsbmi
7632     // by if-conversion pass
7633     BuildMI(*RSBBB, RSBBB->begin(), dl,
7634       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7635       .addReg(ABSSrcReg, RegState::Kill)
7636       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7637
7638     // insert PHI in SinkBB,
7639     // reuse ABSDstReg to not change uses of ABS instruction
7640     BuildMI(*SinkBB, SinkBB->begin(), dl,
7641       TII->get(ARM::PHI), ABSDstReg)
7642       .addReg(NewRsbDstReg).addMBB(RSBBB)
7643       .addReg(ABSSrcReg).addMBB(BB);
7644
7645     // remove ABS instruction
7646     MI->eraseFromParent();
7647
7648     // return last added BB
7649     return SinkBB;
7650   }
7651   case ARM::COPY_STRUCT_BYVAL_I32:
7652     ++NumLoopByVals;
7653     return EmitStructByval(MI, BB);
7654   case ARM::WIN__CHKSTK:
7655     return EmitLowered__chkstk(MI, BB);
7656   }
7657 }
7658
7659 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7660                                                       SDNode *Node) const {
7661   if (!MI->hasPostISelHook()) {
7662     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7663            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7664     return;
7665   }
7666
7667   const MCInstrDesc *MCID = &MI->getDesc();
7668   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7669   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7670   // operand is still set to noreg. If needed, set the optional operand's
7671   // register to CPSR, and remove the redundant implicit def.
7672   //
7673   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7674
7675   // Rename pseudo opcodes.
7676   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7677   if (NewOpc) {
7678     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
7679         getTargetMachine().getSubtargetImpl()->getInstrInfo());
7680     MCID = &TII->get(NewOpc);
7681
7682     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7683            "converted opcode should be the same except for cc_out");
7684
7685     MI->setDesc(*MCID);
7686
7687     // Add the optional cc_out operand
7688     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7689   }
7690   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7691
7692   // Any ARM instruction that sets the 's' bit should specify an optional
7693   // "cc_out" operand in the last operand position.
7694   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7695     assert(!NewOpc && "Optional cc_out operand required");
7696     return;
7697   }
7698   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7699   // since we already have an optional CPSR def.
7700   bool definesCPSR = false;
7701   bool deadCPSR = false;
7702   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7703        i != e; ++i) {
7704     const MachineOperand &MO = MI->getOperand(i);
7705     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7706       definesCPSR = true;
7707       if (MO.isDead())
7708         deadCPSR = true;
7709       MI->RemoveOperand(i);
7710       break;
7711     }
7712   }
7713   if (!definesCPSR) {
7714     assert(!NewOpc && "Optional cc_out operand required");
7715     return;
7716   }
7717   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7718   if (deadCPSR) {
7719     assert(!MI->getOperand(ccOutIdx).getReg() &&
7720            "expect uninitialized optional cc_out operand");
7721     return;
7722   }
7723
7724   // If this instruction was defined with an optional CPSR def and its dag node
7725   // had a live implicit CPSR def, then activate the optional CPSR def.
7726   MachineOperand &MO = MI->getOperand(ccOutIdx);
7727   MO.setReg(ARM::CPSR);
7728   MO.setIsDef(true);
7729 }
7730
7731 //===----------------------------------------------------------------------===//
7732 //                           ARM Optimization Hooks
7733 //===----------------------------------------------------------------------===//
7734
7735 // Helper function that checks if N is a null or all ones constant.
7736 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7737   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7738   if (!C)
7739     return false;
7740   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7741 }
7742
7743 // Return true if N is conditionally 0 or all ones.
7744 // Detects these expressions where cc is an i1 value:
7745 //
7746 //   (select cc 0, y)   [AllOnes=0]
7747 //   (select cc y, 0)   [AllOnes=0]
7748 //   (zext cc)          [AllOnes=0]
7749 //   (sext cc)          [AllOnes=0/1]
7750 //   (select cc -1, y)  [AllOnes=1]
7751 //   (select cc y, -1)  [AllOnes=1]
7752 //
7753 // Invert is set when N is the null/all ones constant when CC is false.
7754 // OtherOp is set to the alternative value of N.
7755 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7756                                        SDValue &CC, bool &Invert,
7757                                        SDValue &OtherOp,
7758                                        SelectionDAG &DAG) {
7759   switch (N->getOpcode()) {
7760   default: return false;
7761   case ISD::SELECT: {
7762     CC = N->getOperand(0);
7763     SDValue N1 = N->getOperand(1);
7764     SDValue N2 = N->getOperand(2);
7765     if (isZeroOrAllOnes(N1, AllOnes)) {
7766       Invert = false;
7767       OtherOp = N2;
7768       return true;
7769     }
7770     if (isZeroOrAllOnes(N2, AllOnes)) {
7771       Invert = true;
7772       OtherOp = N1;
7773       return true;
7774     }
7775     return false;
7776   }
7777   case ISD::ZERO_EXTEND:
7778     // (zext cc) can never be the all ones value.
7779     if (AllOnes)
7780       return false;
7781     // Fall through.
7782   case ISD::SIGN_EXTEND: {
7783     EVT VT = N->getValueType(0);
7784     CC = N->getOperand(0);
7785     if (CC.getValueType() != MVT::i1)
7786       return false;
7787     Invert = !AllOnes;
7788     if (AllOnes)
7789       // When looking for an AllOnes constant, N is an sext, and the 'other'
7790       // value is 0.
7791       OtherOp = DAG.getConstant(0, VT);
7792     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7793       // When looking for a 0 constant, N can be zext or sext.
7794       OtherOp = DAG.getConstant(1, VT);
7795     else
7796       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7797     return true;
7798   }
7799   }
7800 }
7801
7802 // Combine a constant select operand into its use:
7803 //
7804 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7805 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7806 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7807 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7808 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7809 //
7810 // The transform is rejected if the select doesn't have a constant operand that
7811 // is null, or all ones when AllOnes is set.
7812 //
7813 // Also recognize sext/zext from i1:
7814 //
7815 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7816 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7817 //
7818 // These transformations eventually create predicated instructions.
7819 //
7820 // @param N       The node to transform.
7821 // @param Slct    The N operand that is a select.
7822 // @param OtherOp The other N operand (x above).
7823 // @param DCI     Context.
7824 // @param AllOnes Require the select constant to be all ones instead of null.
7825 // @returns The new node, or SDValue() on failure.
7826 static
7827 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7828                             TargetLowering::DAGCombinerInfo &DCI,
7829                             bool AllOnes = false) {
7830   SelectionDAG &DAG = DCI.DAG;
7831   EVT VT = N->getValueType(0);
7832   SDValue NonConstantVal;
7833   SDValue CCOp;
7834   bool SwapSelectOps;
7835   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7836                                   NonConstantVal, DAG))
7837     return SDValue();
7838
7839   // Slct is now know to be the desired identity constant when CC is true.
7840   SDValue TrueVal = OtherOp;
7841   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7842                                  OtherOp, NonConstantVal);
7843   // Unless SwapSelectOps says CC should be false.
7844   if (SwapSelectOps)
7845     std::swap(TrueVal, FalseVal);
7846
7847   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7848                      CCOp, TrueVal, FalseVal);
7849 }
7850
7851 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7852 static
7853 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7854                                        TargetLowering::DAGCombinerInfo &DCI) {
7855   SDValue N0 = N->getOperand(0);
7856   SDValue N1 = N->getOperand(1);
7857   if (N0.getNode()->hasOneUse()) {
7858     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7859     if (Result.getNode())
7860       return Result;
7861   }
7862   if (N1.getNode()->hasOneUse()) {
7863     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7864     if (Result.getNode())
7865       return Result;
7866   }
7867   return SDValue();
7868 }
7869
7870 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7871 // (only after legalization).
7872 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7873                                  TargetLowering::DAGCombinerInfo &DCI,
7874                                  const ARMSubtarget *Subtarget) {
7875
7876   // Only perform optimization if after legalize, and if NEON is available. We
7877   // also expected both operands to be BUILD_VECTORs.
7878   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7879       || N0.getOpcode() != ISD::BUILD_VECTOR
7880       || N1.getOpcode() != ISD::BUILD_VECTOR)
7881     return SDValue();
7882
7883   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7884   EVT VT = N->getValueType(0);
7885   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7886     return SDValue();
7887
7888   // Check that the vector operands are of the right form.
7889   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7890   // operands, where N is the size of the formed vector.
7891   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7892   // index such that we have a pair wise add pattern.
7893
7894   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7895   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7896     return SDValue();
7897   SDValue Vec = N0->getOperand(0)->getOperand(0);
7898   SDNode *V = Vec.getNode();
7899   unsigned nextIndex = 0;
7900
7901   // For each operands to the ADD which are BUILD_VECTORs,
7902   // check to see if each of their operands are an EXTRACT_VECTOR with
7903   // the same vector and appropriate index.
7904   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7905     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7906         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7907
7908       SDValue ExtVec0 = N0->getOperand(i);
7909       SDValue ExtVec1 = N1->getOperand(i);
7910
7911       // First operand is the vector, verify its the same.
7912       if (V != ExtVec0->getOperand(0).getNode() ||
7913           V != ExtVec1->getOperand(0).getNode())
7914         return SDValue();
7915
7916       // Second is the constant, verify its correct.
7917       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7918       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7919
7920       // For the constant, we want to see all the even or all the odd.
7921       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7922           || C1->getZExtValue() != nextIndex+1)
7923         return SDValue();
7924
7925       // Increment index.
7926       nextIndex+=2;
7927     } else
7928       return SDValue();
7929   }
7930
7931   // Create VPADDL node.
7932   SelectionDAG &DAG = DCI.DAG;
7933   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7934
7935   // Build operand list.
7936   SmallVector<SDValue, 8> Ops;
7937   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7938                                 TLI.getPointerTy()));
7939
7940   // Input is the vector.
7941   Ops.push_back(Vec);
7942
7943   // Get widened type and narrowed type.
7944   MVT widenType;
7945   unsigned numElem = VT.getVectorNumElements();
7946   
7947   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7948   switch (inputLaneType.getSimpleVT().SimpleTy) {
7949     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7950     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7951     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7952     default:
7953       llvm_unreachable("Invalid vector element type for padd optimization.");
7954   }
7955
7956   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7957   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7958   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7959 }
7960
7961 static SDValue findMUL_LOHI(SDValue V) {
7962   if (V->getOpcode() == ISD::UMUL_LOHI ||
7963       V->getOpcode() == ISD::SMUL_LOHI)
7964     return V;
7965   return SDValue();
7966 }
7967
7968 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7969                                      TargetLowering::DAGCombinerInfo &DCI,
7970                                      const ARMSubtarget *Subtarget) {
7971
7972   if (Subtarget->isThumb1Only()) return SDValue();
7973
7974   // Only perform the checks after legalize when the pattern is available.
7975   if (DCI.isBeforeLegalize()) return SDValue();
7976
7977   // Look for multiply add opportunities.
7978   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7979   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7980   // a glue link from the first add to the second add.
7981   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7982   // a S/UMLAL instruction.
7983   //          loAdd   UMUL_LOHI
7984   //            \    / :lo    \ :hi
7985   //             \  /          \          [no multiline comment]
7986   //              ADDC         |  hiAdd
7987   //                 \ :glue  /  /
7988   //                  \      /  /
7989   //                    ADDE
7990   //
7991   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7992   SDValue AddcOp0 = AddcNode->getOperand(0);
7993   SDValue AddcOp1 = AddcNode->getOperand(1);
7994
7995   // Check if the two operands are from the same mul_lohi node.
7996   if (AddcOp0.getNode() == AddcOp1.getNode())
7997     return SDValue();
7998
7999   assert(AddcNode->getNumValues() == 2 &&
8000          AddcNode->getValueType(0) == MVT::i32 &&
8001          "Expect ADDC with two result values. First: i32");
8002
8003   // Check that we have a glued ADDC node.
8004   if (AddcNode->getValueType(1) != MVT::Glue)
8005     return SDValue();
8006
8007   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8008   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8009       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8010       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8011       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8012     return SDValue();
8013
8014   // Look for the glued ADDE.
8015   SDNode* AddeNode = AddcNode->getGluedUser();
8016   if (!AddeNode)
8017     return SDValue();
8018
8019   // Make sure it is really an ADDE.
8020   if (AddeNode->getOpcode() != ISD::ADDE)
8021     return SDValue();
8022
8023   assert(AddeNode->getNumOperands() == 3 &&
8024          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8025          "ADDE node has the wrong inputs");
8026
8027   // Check for the triangle shape.
8028   SDValue AddeOp0 = AddeNode->getOperand(0);
8029   SDValue AddeOp1 = AddeNode->getOperand(1);
8030
8031   // Make sure that the ADDE operands are not coming from the same node.
8032   if (AddeOp0.getNode() == AddeOp1.getNode())
8033     return SDValue();
8034
8035   // Find the MUL_LOHI node walking up ADDE's operands.
8036   bool IsLeftOperandMUL = false;
8037   SDValue MULOp = findMUL_LOHI(AddeOp0);
8038   if (MULOp == SDValue())
8039    MULOp = findMUL_LOHI(AddeOp1);
8040   else
8041     IsLeftOperandMUL = true;
8042   if (MULOp == SDValue())
8043      return SDValue();
8044
8045   // Figure out the right opcode.
8046   unsigned Opc = MULOp->getOpcode();
8047   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8048
8049   // Figure out the high and low input values to the MLAL node.
8050   SDValue* HiMul = &MULOp;
8051   SDValue* HiAdd = nullptr;
8052   SDValue* LoMul = nullptr;
8053   SDValue* LowAdd = nullptr;
8054
8055   if (IsLeftOperandMUL)
8056     HiAdd = &AddeOp1;
8057   else
8058     HiAdd = &AddeOp0;
8059
8060
8061   if (AddcOp0->getOpcode() == Opc) {
8062     LoMul = &AddcOp0;
8063     LowAdd = &AddcOp1;
8064   }
8065   if (AddcOp1->getOpcode() == Opc) {
8066     LoMul = &AddcOp1;
8067     LowAdd = &AddcOp0;
8068   }
8069
8070   if (!LoMul)
8071     return SDValue();
8072
8073   if (LoMul->getNode() != HiMul->getNode())
8074     return SDValue();
8075
8076   // Create the merged node.
8077   SelectionDAG &DAG = DCI.DAG;
8078
8079   // Build operand list.
8080   SmallVector<SDValue, 8> Ops;
8081   Ops.push_back(LoMul->getOperand(0));
8082   Ops.push_back(LoMul->getOperand(1));
8083   Ops.push_back(*LowAdd);
8084   Ops.push_back(*HiAdd);
8085
8086   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8087                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8088
8089   // Replace the ADDs' nodes uses by the MLA node's values.
8090   SDValue HiMLALResult(MLALNode.getNode(), 1);
8091   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8092
8093   SDValue LoMLALResult(MLALNode.getNode(), 0);
8094   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8095
8096   // Return original node to notify the driver to stop replacing.
8097   SDValue resNode(AddcNode, 0);
8098   return resNode;
8099 }
8100
8101 /// PerformADDCCombine - Target-specific dag combine transform from
8102 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8103 static SDValue PerformADDCCombine(SDNode *N,
8104                                  TargetLowering::DAGCombinerInfo &DCI,
8105                                  const ARMSubtarget *Subtarget) {
8106
8107   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8108
8109 }
8110
8111 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8112 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8113 /// called with the default operands, and if that fails, with commuted
8114 /// operands.
8115 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8116                                           TargetLowering::DAGCombinerInfo &DCI,
8117                                           const ARMSubtarget *Subtarget){
8118
8119   // Attempt to create vpaddl for this add.
8120   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8121   if (Result.getNode())
8122     return Result;
8123
8124   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8125   if (N0.getNode()->hasOneUse()) {
8126     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8127     if (Result.getNode()) return Result;
8128   }
8129   return SDValue();
8130 }
8131
8132 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8133 ///
8134 static SDValue PerformADDCombine(SDNode *N,
8135                                  TargetLowering::DAGCombinerInfo &DCI,
8136                                  const ARMSubtarget *Subtarget) {
8137   SDValue N0 = N->getOperand(0);
8138   SDValue N1 = N->getOperand(1);
8139
8140   // First try with the default operand order.
8141   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8142   if (Result.getNode())
8143     return Result;
8144
8145   // If that didn't work, try again with the operands commuted.
8146   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8147 }
8148
8149 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8150 ///
8151 static SDValue PerformSUBCombine(SDNode *N,
8152                                  TargetLowering::DAGCombinerInfo &DCI) {
8153   SDValue N0 = N->getOperand(0);
8154   SDValue N1 = N->getOperand(1);
8155
8156   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8157   if (N1.getNode()->hasOneUse()) {
8158     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8159     if (Result.getNode()) return Result;
8160   }
8161
8162   return SDValue();
8163 }
8164
8165 /// PerformVMULCombine
8166 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8167 /// special multiplier accumulator forwarding.
8168 ///   vmul d3, d0, d2
8169 ///   vmla d3, d1, d2
8170 /// is faster than
8171 ///   vadd d3, d0, d1
8172 ///   vmul d3, d3, d2
8173 //  However, for (A + B) * (A + B),
8174 //    vadd d2, d0, d1
8175 //    vmul d3, d0, d2
8176 //    vmla d3, d1, d2
8177 //  is slower than
8178 //    vadd d2, d0, d1
8179 //    vmul d3, d2, d2
8180 static SDValue PerformVMULCombine(SDNode *N,
8181                                   TargetLowering::DAGCombinerInfo &DCI,
8182                                   const ARMSubtarget *Subtarget) {
8183   if (!Subtarget->hasVMLxForwarding())
8184     return SDValue();
8185
8186   SelectionDAG &DAG = DCI.DAG;
8187   SDValue N0 = N->getOperand(0);
8188   SDValue N1 = N->getOperand(1);
8189   unsigned Opcode = N0.getOpcode();
8190   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8191       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8192     Opcode = N1.getOpcode();
8193     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8194         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8195       return SDValue();
8196     std::swap(N0, N1);
8197   }
8198
8199   if (N0 == N1)
8200     return SDValue();
8201
8202   EVT VT = N->getValueType(0);
8203   SDLoc DL(N);
8204   SDValue N00 = N0->getOperand(0);
8205   SDValue N01 = N0->getOperand(1);
8206   return DAG.getNode(Opcode, DL, VT,
8207                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8208                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8209 }
8210
8211 static SDValue PerformMULCombine(SDNode *N,
8212                                  TargetLowering::DAGCombinerInfo &DCI,
8213                                  const ARMSubtarget *Subtarget) {
8214   SelectionDAG &DAG = DCI.DAG;
8215
8216   if (Subtarget->isThumb1Only())
8217     return SDValue();
8218
8219   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8220     return SDValue();
8221
8222   EVT VT = N->getValueType(0);
8223   if (VT.is64BitVector() || VT.is128BitVector())
8224     return PerformVMULCombine(N, DCI, Subtarget);
8225   if (VT != MVT::i32)
8226     return SDValue();
8227
8228   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8229   if (!C)
8230     return SDValue();
8231
8232   int64_t MulAmt = C->getSExtValue();
8233   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8234
8235   ShiftAmt = ShiftAmt & (32 - 1);
8236   SDValue V = N->getOperand(0);
8237   SDLoc DL(N);
8238
8239   SDValue Res;
8240   MulAmt >>= ShiftAmt;
8241
8242   if (MulAmt >= 0) {
8243     if (isPowerOf2_32(MulAmt - 1)) {
8244       // (mul x, 2^N + 1) => (add (shl x, N), x)
8245       Res = DAG.getNode(ISD::ADD, DL, VT,
8246                         V,
8247                         DAG.getNode(ISD::SHL, DL, VT,
8248                                     V,
8249                                     DAG.getConstant(Log2_32(MulAmt - 1),
8250                                                     MVT::i32)));
8251     } else if (isPowerOf2_32(MulAmt + 1)) {
8252       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8253       Res = DAG.getNode(ISD::SUB, DL, VT,
8254                         DAG.getNode(ISD::SHL, DL, VT,
8255                                     V,
8256                                     DAG.getConstant(Log2_32(MulAmt + 1),
8257                                                     MVT::i32)),
8258                         V);
8259     } else
8260       return SDValue();
8261   } else {
8262     uint64_t MulAmtAbs = -MulAmt;
8263     if (isPowerOf2_32(MulAmtAbs + 1)) {
8264       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8265       Res = DAG.getNode(ISD::SUB, DL, VT,
8266                         V,
8267                         DAG.getNode(ISD::SHL, DL, VT,
8268                                     V,
8269                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8270                                                     MVT::i32)));
8271     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8272       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8273       Res = DAG.getNode(ISD::ADD, DL, VT,
8274                         V,
8275                         DAG.getNode(ISD::SHL, DL, VT,
8276                                     V,
8277                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8278                                                     MVT::i32)));
8279       Res = DAG.getNode(ISD::SUB, DL, VT,
8280                         DAG.getConstant(0, MVT::i32),Res);
8281
8282     } else
8283       return SDValue();
8284   }
8285
8286   if (ShiftAmt != 0)
8287     Res = DAG.getNode(ISD::SHL, DL, VT,
8288                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8289
8290   // Do not add new nodes to DAG combiner worklist.
8291   DCI.CombineTo(N, Res, false);
8292   return SDValue();
8293 }
8294
8295 static SDValue PerformANDCombine(SDNode *N,
8296                                  TargetLowering::DAGCombinerInfo &DCI,
8297                                  const ARMSubtarget *Subtarget) {
8298
8299   // Attempt to use immediate-form VBIC
8300   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8301   SDLoc dl(N);
8302   EVT VT = N->getValueType(0);
8303   SelectionDAG &DAG = DCI.DAG;
8304
8305   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8306     return SDValue();
8307
8308   APInt SplatBits, SplatUndef;
8309   unsigned SplatBitSize;
8310   bool HasAnyUndefs;
8311   if (BVN &&
8312       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8313     if (SplatBitSize <= 64) {
8314       EVT VbicVT;
8315       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8316                                       SplatUndef.getZExtValue(), SplatBitSize,
8317                                       DAG, VbicVT, VT.is128BitVector(),
8318                                       OtherModImm);
8319       if (Val.getNode()) {
8320         SDValue Input =
8321           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8322         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8323         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8324       }
8325     }
8326   }
8327
8328   if (!Subtarget->isThumb1Only()) {
8329     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8330     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8331     if (Result.getNode())
8332       return Result;
8333   }
8334
8335   return SDValue();
8336 }
8337
8338 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8339 static SDValue PerformORCombine(SDNode *N,
8340                                 TargetLowering::DAGCombinerInfo &DCI,
8341                                 const ARMSubtarget *Subtarget) {
8342   // Attempt to use immediate-form VORR
8343   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8344   SDLoc dl(N);
8345   EVT VT = N->getValueType(0);
8346   SelectionDAG &DAG = DCI.DAG;
8347
8348   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8349     return SDValue();
8350
8351   APInt SplatBits, SplatUndef;
8352   unsigned SplatBitSize;
8353   bool HasAnyUndefs;
8354   if (BVN && Subtarget->hasNEON() &&
8355       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8356     if (SplatBitSize <= 64) {
8357       EVT VorrVT;
8358       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8359                                       SplatUndef.getZExtValue(), SplatBitSize,
8360                                       DAG, VorrVT, VT.is128BitVector(),
8361                                       OtherModImm);
8362       if (Val.getNode()) {
8363         SDValue Input =
8364           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8365         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8366         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8367       }
8368     }
8369   }
8370
8371   if (!Subtarget->isThumb1Only()) {
8372     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8373     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8374     if (Result.getNode())
8375       return Result;
8376   }
8377
8378   // The code below optimizes (or (and X, Y), Z).
8379   // The AND operand needs to have a single user to make these optimizations
8380   // profitable.
8381   SDValue N0 = N->getOperand(0);
8382   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8383     return SDValue();
8384   SDValue N1 = N->getOperand(1);
8385
8386   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8387   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8388       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8389     APInt SplatUndef;
8390     unsigned SplatBitSize;
8391     bool HasAnyUndefs;
8392
8393     APInt SplatBits0, SplatBits1;
8394     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8395     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8396     // Ensure that the second operand of both ands are constants
8397     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8398                                       HasAnyUndefs) && !HasAnyUndefs) {
8399         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8400                                           HasAnyUndefs) && !HasAnyUndefs) {
8401             // Ensure that the bit width of the constants are the same and that
8402             // the splat arguments are logical inverses as per the pattern we
8403             // are trying to simplify.
8404             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8405                 SplatBits0 == ~SplatBits1) {
8406                 // Canonicalize the vector type to make instruction selection
8407                 // simpler.
8408                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8409                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8410                                              N0->getOperand(1),
8411                                              N0->getOperand(0),
8412                                              N1->getOperand(0));
8413                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8414             }
8415         }
8416     }
8417   }
8418
8419   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8420   // reasonable.
8421
8422   // BFI is only available on V6T2+
8423   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8424     return SDValue();
8425
8426   SDLoc DL(N);
8427   // 1) or (and A, mask), val => ARMbfi A, val, mask
8428   //      iff (val & mask) == val
8429   //
8430   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8431   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8432   //          && mask == ~mask2
8433   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8434   //          && ~mask == mask2
8435   //  (i.e., copy a bitfield value into another bitfield of the same width)
8436
8437   if (VT != MVT::i32)
8438     return SDValue();
8439
8440   SDValue N00 = N0.getOperand(0);
8441
8442   // The value and the mask need to be constants so we can verify this is
8443   // actually a bitfield set. If the mask is 0xffff, we can do better
8444   // via a movt instruction, so don't use BFI in that case.
8445   SDValue MaskOp = N0.getOperand(1);
8446   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8447   if (!MaskC)
8448     return SDValue();
8449   unsigned Mask = MaskC->getZExtValue();
8450   if (Mask == 0xffff)
8451     return SDValue();
8452   SDValue Res;
8453   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8454   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8455   if (N1C) {
8456     unsigned Val = N1C->getZExtValue();
8457     if ((Val & ~Mask) != Val)
8458       return SDValue();
8459
8460     if (ARM::isBitFieldInvertedMask(Mask)) {
8461       Val >>= countTrailingZeros(~Mask);
8462
8463       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8464                         DAG.getConstant(Val, MVT::i32),
8465                         DAG.getConstant(Mask, MVT::i32));
8466
8467       // Do not add new nodes to DAG combiner worklist.
8468       DCI.CombineTo(N, Res, false);
8469       return SDValue();
8470     }
8471   } else if (N1.getOpcode() == ISD::AND) {
8472     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8473     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8474     if (!N11C)
8475       return SDValue();
8476     unsigned Mask2 = N11C->getZExtValue();
8477
8478     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8479     // as is to match.
8480     if (ARM::isBitFieldInvertedMask(Mask) &&
8481         (Mask == ~Mask2)) {
8482       // The pack halfword instruction works better for masks that fit it,
8483       // so use that when it's available.
8484       if (Subtarget->hasT2ExtractPack() &&
8485           (Mask == 0xffff || Mask == 0xffff0000))
8486         return SDValue();
8487       // 2a
8488       unsigned amt = countTrailingZeros(Mask2);
8489       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8490                         DAG.getConstant(amt, MVT::i32));
8491       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8492                         DAG.getConstant(Mask, MVT::i32));
8493       // Do not add new nodes to DAG combiner worklist.
8494       DCI.CombineTo(N, Res, false);
8495       return SDValue();
8496     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8497                (~Mask == Mask2)) {
8498       // The pack halfword instruction works better for masks that fit it,
8499       // so use that when it's available.
8500       if (Subtarget->hasT2ExtractPack() &&
8501           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8502         return SDValue();
8503       // 2b
8504       unsigned lsb = countTrailingZeros(Mask);
8505       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8506                         DAG.getConstant(lsb, MVT::i32));
8507       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8508                         DAG.getConstant(Mask2, MVT::i32));
8509       // Do not add new nodes to DAG combiner worklist.
8510       DCI.CombineTo(N, Res, false);
8511       return SDValue();
8512     }
8513   }
8514
8515   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8516       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8517       ARM::isBitFieldInvertedMask(~Mask)) {
8518     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8519     // where lsb(mask) == #shamt and masked bits of B are known zero.
8520     SDValue ShAmt = N00.getOperand(1);
8521     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8522     unsigned LSB = countTrailingZeros(Mask);
8523     if (ShAmtC != LSB)
8524       return SDValue();
8525
8526     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8527                       DAG.getConstant(~Mask, MVT::i32));
8528
8529     // Do not add new nodes to DAG combiner worklist.
8530     DCI.CombineTo(N, Res, false);
8531   }
8532
8533   return SDValue();
8534 }
8535
8536 static SDValue PerformXORCombine(SDNode *N,
8537                                  TargetLowering::DAGCombinerInfo &DCI,
8538                                  const ARMSubtarget *Subtarget) {
8539   EVT VT = N->getValueType(0);
8540   SelectionDAG &DAG = DCI.DAG;
8541
8542   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8543     return SDValue();
8544
8545   if (!Subtarget->isThumb1Only()) {
8546     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8547     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8548     if (Result.getNode())
8549       return Result;
8550   }
8551
8552   return SDValue();
8553 }
8554
8555 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8556 /// the bits being cleared by the AND are not demanded by the BFI.
8557 static SDValue PerformBFICombine(SDNode *N,
8558                                  TargetLowering::DAGCombinerInfo &DCI) {
8559   SDValue N1 = N->getOperand(1);
8560   if (N1.getOpcode() == ISD::AND) {
8561     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8562     if (!N11C)
8563       return SDValue();
8564     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8565     unsigned LSB = countTrailingZeros(~InvMask);
8566     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8567     unsigned Mask = (1 << Width)-1;
8568     unsigned Mask2 = N11C->getZExtValue();
8569     if ((Mask & (~Mask2)) == 0)
8570       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8571                              N->getOperand(0), N1.getOperand(0),
8572                              N->getOperand(2));
8573   }
8574   return SDValue();
8575 }
8576
8577 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8578 /// ARMISD::VMOVRRD.
8579 static SDValue PerformVMOVRRDCombine(SDNode *N,
8580                                      TargetLowering::DAGCombinerInfo &DCI,
8581                                      const ARMSubtarget *Subtarget) {
8582   // vmovrrd(vmovdrr x, y) -> x,y
8583   SDValue InDouble = N->getOperand(0);
8584   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8585     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8586
8587   // vmovrrd(load f64) -> (load i32), (load i32)
8588   SDNode *InNode = InDouble.getNode();
8589   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8590       InNode->getValueType(0) == MVT::f64 &&
8591       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8592       !cast<LoadSDNode>(InNode)->isVolatile()) {
8593     // TODO: Should this be done for non-FrameIndex operands?
8594     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8595
8596     SelectionDAG &DAG = DCI.DAG;
8597     SDLoc DL(LD);
8598     SDValue BasePtr = LD->getBasePtr();
8599     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8600                                  LD->getPointerInfo(), LD->isVolatile(),
8601                                  LD->isNonTemporal(), LD->isInvariant(),
8602                                  LD->getAlignment());
8603
8604     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8605                                     DAG.getConstant(4, MVT::i32));
8606     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8607                                  LD->getPointerInfo(), LD->isVolatile(),
8608                                  LD->isNonTemporal(), LD->isInvariant(),
8609                                  std::min(4U, LD->getAlignment() / 2));
8610
8611     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8612     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8613       std::swap (NewLD1, NewLD2);
8614     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8615     return Result;
8616   }
8617
8618   return SDValue();
8619 }
8620
8621 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8622 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8623 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8624   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8625   SDValue Op0 = N->getOperand(0);
8626   SDValue Op1 = N->getOperand(1);
8627   if (Op0.getOpcode() == ISD::BITCAST)
8628     Op0 = Op0.getOperand(0);
8629   if (Op1.getOpcode() == ISD::BITCAST)
8630     Op1 = Op1.getOperand(0);
8631   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8632       Op0.getNode() == Op1.getNode() &&
8633       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8634     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8635                        N->getValueType(0), Op0.getOperand(0));
8636   return SDValue();
8637 }
8638
8639 /// PerformSTORECombine - Target-specific dag combine xforms for
8640 /// ISD::STORE.
8641 static SDValue PerformSTORECombine(SDNode *N,
8642                                    TargetLowering::DAGCombinerInfo &DCI) {
8643   StoreSDNode *St = cast<StoreSDNode>(N);
8644   if (St->isVolatile())
8645     return SDValue();
8646
8647   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8648   // pack all of the elements in one place.  Next, store to memory in fewer
8649   // chunks.
8650   SDValue StVal = St->getValue();
8651   EVT VT = StVal.getValueType();
8652   if (St->isTruncatingStore() && VT.isVector()) {
8653     SelectionDAG &DAG = DCI.DAG;
8654     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8655     EVT StVT = St->getMemoryVT();
8656     unsigned NumElems = VT.getVectorNumElements();
8657     assert(StVT != VT && "Cannot truncate to the same type");
8658     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8659     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8660
8661     // From, To sizes and ElemCount must be pow of two
8662     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8663
8664     // We are going to use the original vector elt for storing.
8665     // Accumulated smaller vector elements must be a multiple of the store size.
8666     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8667
8668     unsigned SizeRatio  = FromEltSz / ToEltSz;
8669     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8670
8671     // Create a type on which we perform the shuffle.
8672     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8673                                      NumElems*SizeRatio);
8674     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8675
8676     SDLoc DL(St);
8677     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8678     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8679     for (unsigned i = 0; i < NumElems; ++i)
8680       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8681
8682     // Can't shuffle using an illegal type.
8683     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8684
8685     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8686                                 DAG.getUNDEF(WideVec.getValueType()),
8687                                 ShuffleVec.data());
8688     // At this point all of the data is stored at the bottom of the
8689     // register. We now need to save it to mem.
8690
8691     // Find the largest store unit
8692     MVT StoreType = MVT::i8;
8693     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8694          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8695       MVT Tp = (MVT::SimpleValueType)tp;
8696       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8697         StoreType = Tp;
8698     }
8699     // Didn't find a legal store type.
8700     if (!TLI.isTypeLegal(StoreType))
8701       return SDValue();
8702
8703     // Bitcast the original vector into a vector of store-size units
8704     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8705             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8706     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8707     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8708     SmallVector<SDValue, 8> Chains;
8709     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8710                                         TLI.getPointerTy());
8711     SDValue BasePtr = St->getBasePtr();
8712
8713     // Perform one or more big stores into memory.
8714     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8715     for (unsigned I = 0; I < E; I++) {
8716       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8717                                    StoreType, ShuffWide,
8718                                    DAG.getIntPtrConstant(I));
8719       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8720                                 St->getPointerInfo(), St->isVolatile(),
8721                                 St->isNonTemporal(), St->getAlignment());
8722       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8723                             Increment);
8724       Chains.push_back(Ch);
8725     }
8726     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8727   }
8728
8729   if (!ISD::isNormalStore(St))
8730     return SDValue();
8731
8732   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8733   // ARM stores of arguments in the same cache line.
8734   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8735       StVal.getNode()->hasOneUse()) {
8736     SelectionDAG  &DAG = DCI.DAG;
8737     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8738     SDLoc DL(St);
8739     SDValue BasePtr = St->getBasePtr();
8740     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8741                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8742                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8743                                   St->isNonTemporal(), St->getAlignment());
8744
8745     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8746                                     DAG.getConstant(4, MVT::i32));
8747     return DAG.getStore(NewST1.getValue(0), DL,
8748                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8749                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8750                         St->isNonTemporal(),
8751                         std::min(4U, St->getAlignment() / 2));
8752   }
8753
8754   if (StVal.getValueType() != MVT::i64 ||
8755       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8756     return SDValue();
8757
8758   // Bitcast an i64 store extracted from a vector to f64.
8759   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8760   SelectionDAG &DAG = DCI.DAG;
8761   SDLoc dl(StVal);
8762   SDValue IntVec = StVal.getOperand(0);
8763   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8764                                  IntVec.getValueType().getVectorNumElements());
8765   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8766   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8767                                Vec, StVal.getOperand(1));
8768   dl = SDLoc(N);
8769   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8770   // Make the DAGCombiner fold the bitcasts.
8771   DCI.AddToWorklist(Vec.getNode());
8772   DCI.AddToWorklist(ExtElt.getNode());
8773   DCI.AddToWorklist(V.getNode());
8774   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8775                       St->getPointerInfo(), St->isVolatile(),
8776                       St->isNonTemporal(), St->getAlignment(),
8777                       St->getAAInfo());
8778 }
8779
8780 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8781 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8782 /// i64 vector to have f64 elements, since the value can then be loaded
8783 /// directly into a VFP register.
8784 static bool hasNormalLoadOperand(SDNode *N) {
8785   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8786   for (unsigned i = 0; i < NumElts; ++i) {
8787     SDNode *Elt = N->getOperand(i).getNode();
8788     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8789       return true;
8790   }
8791   return false;
8792 }
8793
8794 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8795 /// ISD::BUILD_VECTOR.
8796 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8797                                           TargetLowering::DAGCombinerInfo &DCI,
8798                                           const ARMSubtarget *Subtarget) {
8799   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8800   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8801   // into a pair of GPRs, which is fine when the value is used as a scalar,
8802   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8803   SelectionDAG &DAG = DCI.DAG;
8804   if (N->getNumOperands() == 2) {
8805     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8806     if (RV.getNode())
8807       return RV;
8808   }
8809
8810   // Load i64 elements as f64 values so that type legalization does not split
8811   // them up into i32 values.
8812   EVT VT = N->getValueType(0);
8813   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8814     return SDValue();
8815   SDLoc dl(N);
8816   SmallVector<SDValue, 8> Ops;
8817   unsigned NumElts = VT.getVectorNumElements();
8818   for (unsigned i = 0; i < NumElts; ++i) {
8819     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8820     Ops.push_back(V);
8821     // Make the DAGCombiner fold the bitcast.
8822     DCI.AddToWorklist(V.getNode());
8823   }
8824   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8825   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8826   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8827 }
8828
8829 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8830 static SDValue
8831 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8832   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8833   // At that time, we may have inserted bitcasts from integer to float.
8834   // If these bitcasts have survived DAGCombine, change the lowering of this
8835   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8836   // force to use floating point types.
8837
8838   // Make sure we can change the type of the vector.
8839   // This is possible iff:
8840   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8841   //    1.1. Vector is used only once.
8842   //    1.2. Use is a bit convert to an integer type.
8843   // 2. The size of its operands are 32-bits (64-bits are not legal).
8844   EVT VT = N->getValueType(0);
8845   EVT EltVT = VT.getVectorElementType();
8846
8847   // Check 1.1. and 2.
8848   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8849     return SDValue();
8850
8851   // By construction, the input type must be float.
8852   assert(EltVT == MVT::f32 && "Unexpected type!");
8853
8854   // Check 1.2.
8855   SDNode *Use = *N->use_begin();
8856   if (Use->getOpcode() != ISD::BITCAST ||
8857       Use->getValueType(0).isFloatingPoint())
8858     return SDValue();
8859
8860   // Check profitability.
8861   // Model is, if more than half of the relevant operands are bitcast from
8862   // i32, turn the build_vector into a sequence of insert_vector_elt.
8863   // Relevant operands are everything that is not statically
8864   // (i.e., at compile time) bitcasted.
8865   unsigned NumOfBitCastedElts = 0;
8866   unsigned NumElts = VT.getVectorNumElements();
8867   unsigned NumOfRelevantElts = NumElts;
8868   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8869     SDValue Elt = N->getOperand(Idx);
8870     if (Elt->getOpcode() == ISD::BITCAST) {
8871       // Assume only bit cast to i32 will go away.
8872       if (Elt->getOperand(0).getValueType() == MVT::i32)
8873         ++NumOfBitCastedElts;
8874     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8875       // Constants are statically casted, thus do not count them as
8876       // relevant operands.
8877       --NumOfRelevantElts;
8878   }
8879
8880   // Check if more than half of the elements require a non-free bitcast.
8881   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8882     return SDValue();
8883
8884   SelectionDAG &DAG = DCI.DAG;
8885   // Create the new vector type.
8886   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8887   // Check if the type is legal.
8888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8889   if (!TLI.isTypeLegal(VecVT))
8890     return SDValue();
8891
8892   // Combine:
8893   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8894   // => BITCAST INSERT_VECTOR_ELT
8895   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8896   //                      (BITCAST EN), N.
8897   SDValue Vec = DAG.getUNDEF(VecVT);
8898   SDLoc dl(N);
8899   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8900     SDValue V = N->getOperand(Idx);
8901     if (V.getOpcode() == ISD::UNDEF)
8902       continue;
8903     if (V.getOpcode() == ISD::BITCAST &&
8904         V->getOperand(0).getValueType() == MVT::i32)
8905       // Fold obvious case.
8906       V = V.getOperand(0);
8907     else {
8908       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8909       // Make the DAGCombiner fold the bitcasts.
8910       DCI.AddToWorklist(V.getNode());
8911     }
8912     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8913     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8914   }
8915   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8916   // Make the DAGCombiner fold the bitcasts.
8917   DCI.AddToWorklist(Vec.getNode());
8918   return Vec;
8919 }
8920
8921 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8922 /// ISD::INSERT_VECTOR_ELT.
8923 static SDValue PerformInsertEltCombine(SDNode *N,
8924                                        TargetLowering::DAGCombinerInfo &DCI) {
8925   // Bitcast an i64 load inserted into a vector to f64.
8926   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8927   EVT VT = N->getValueType(0);
8928   SDNode *Elt = N->getOperand(1).getNode();
8929   if (VT.getVectorElementType() != MVT::i64 ||
8930       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8931     return SDValue();
8932
8933   SelectionDAG &DAG = DCI.DAG;
8934   SDLoc dl(N);
8935   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8936                                  VT.getVectorNumElements());
8937   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8938   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8939   // Make the DAGCombiner fold the bitcasts.
8940   DCI.AddToWorklist(Vec.getNode());
8941   DCI.AddToWorklist(V.getNode());
8942   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8943                                Vec, V, N->getOperand(2));
8944   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8945 }
8946
8947 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8948 /// ISD::VECTOR_SHUFFLE.
8949 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8950   // The LLVM shufflevector instruction does not require the shuffle mask
8951   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8952   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8953   // operands do not match the mask length, they are extended by concatenating
8954   // them with undef vectors.  That is probably the right thing for other
8955   // targets, but for NEON it is better to concatenate two double-register
8956   // size vector operands into a single quad-register size vector.  Do that
8957   // transformation here:
8958   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8959   //   shuffle(concat(v1, v2), undef)
8960   SDValue Op0 = N->getOperand(0);
8961   SDValue Op1 = N->getOperand(1);
8962   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8963       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8964       Op0.getNumOperands() != 2 ||
8965       Op1.getNumOperands() != 2)
8966     return SDValue();
8967   SDValue Concat0Op1 = Op0.getOperand(1);
8968   SDValue Concat1Op1 = Op1.getOperand(1);
8969   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8970       Concat1Op1.getOpcode() != ISD::UNDEF)
8971     return SDValue();
8972   // Skip the transformation if any of the types are illegal.
8973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8974   EVT VT = N->getValueType(0);
8975   if (!TLI.isTypeLegal(VT) ||
8976       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8977       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8978     return SDValue();
8979
8980   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8981                                   Op0.getOperand(0), Op1.getOperand(0));
8982   // Translate the shuffle mask.
8983   SmallVector<int, 16> NewMask;
8984   unsigned NumElts = VT.getVectorNumElements();
8985   unsigned HalfElts = NumElts/2;
8986   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8987   for (unsigned n = 0; n < NumElts; ++n) {
8988     int MaskElt = SVN->getMaskElt(n);
8989     int NewElt = -1;
8990     if (MaskElt < (int)HalfElts)
8991       NewElt = MaskElt;
8992     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8993       NewElt = HalfElts + MaskElt - NumElts;
8994     NewMask.push_back(NewElt);
8995   }
8996   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8997                               DAG.getUNDEF(VT), NewMask.data());
8998 }
8999
9000 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
9001 /// NEON load/store intrinsics to merge base address updates.
9002 static SDValue CombineBaseUpdate(SDNode *N,
9003                                  TargetLowering::DAGCombinerInfo &DCI) {
9004   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9005     return SDValue();
9006
9007   SelectionDAG &DAG = DCI.DAG;
9008   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9009                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9010   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
9011   SDValue Addr = N->getOperand(AddrOpIdx);
9012
9013   // Search for a use of the address operand that is an increment.
9014   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9015          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9016     SDNode *User = *UI;
9017     if (User->getOpcode() != ISD::ADD ||
9018         UI.getUse().getResNo() != Addr.getResNo())
9019       continue;
9020
9021     // Check that the add is independent of the load/store.  Otherwise, folding
9022     // it would create a cycle.
9023     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9024       continue;
9025
9026     // Find the new opcode for the updating load/store.
9027     bool isLoad = true;
9028     bool isLaneOp = false;
9029     unsigned NewOpc = 0;
9030     unsigned NumVecs = 0;
9031     if (isIntrinsic) {
9032       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9033       switch (IntNo) {
9034       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9035       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9036         NumVecs = 1; break;
9037       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9038         NumVecs = 2; break;
9039       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9040         NumVecs = 3; break;
9041       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9042         NumVecs = 4; break;
9043       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9044         NumVecs = 2; isLaneOp = true; break;
9045       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9046         NumVecs = 3; isLaneOp = true; break;
9047       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9048         NumVecs = 4; isLaneOp = true; break;
9049       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9050         NumVecs = 1; isLoad = false; break;
9051       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9052         NumVecs = 2; isLoad = false; break;
9053       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9054         NumVecs = 3; isLoad = false; break;
9055       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9056         NumVecs = 4; isLoad = false; break;
9057       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9058         NumVecs = 2; isLoad = false; isLaneOp = true; break;
9059       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9060         NumVecs = 3; isLoad = false; isLaneOp = true; break;
9061       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9062         NumVecs = 4; isLoad = false; isLaneOp = true; break;
9063       }
9064     } else {
9065       isLaneOp = true;
9066       switch (N->getOpcode()) {
9067       default: llvm_unreachable("unexpected opcode for Neon base update");
9068       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9069       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9070       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9071       }
9072     }
9073
9074     // Find the size of memory referenced by the load/store.
9075     EVT VecTy;
9076     if (isLoad)
9077       VecTy = N->getValueType(0);
9078     else
9079       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9080     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9081     if (isLaneOp)
9082       NumBytes /= VecTy.getVectorNumElements();
9083
9084     // If the increment is a constant, it must match the memory ref size.
9085     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9086     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9087       uint64_t IncVal = CInc->getZExtValue();
9088       if (IncVal != NumBytes)
9089         continue;
9090     } else if (NumBytes >= 3 * 16) {
9091       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9092       // separate instructions that make it harder to use a non-constant update.
9093       continue;
9094     }
9095
9096     // Create the new updating load/store node.
9097     EVT Tys[6];
9098     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
9099     unsigned n;
9100     for (n = 0; n < NumResultVecs; ++n)
9101       Tys[n] = VecTy;
9102     Tys[n++] = MVT::i32;
9103     Tys[n] = MVT::Other;
9104     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9105     SmallVector<SDValue, 8> Ops;
9106     Ops.push_back(N->getOperand(0)); // incoming chain
9107     Ops.push_back(N->getOperand(AddrOpIdx));
9108     Ops.push_back(Inc);
9109     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
9110       Ops.push_back(N->getOperand(i));
9111     }
9112     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9113     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
9114                                            Ops, MemInt->getMemoryVT(),
9115                                            MemInt->getMemOperand());
9116
9117     // Update the uses.
9118     std::vector<SDValue> NewResults;
9119     for (unsigned i = 0; i < NumResultVecs; ++i) {
9120       NewResults.push_back(SDValue(UpdN.getNode(), i));
9121     }
9122     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9123     DCI.CombineTo(N, NewResults);
9124     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9125
9126     break;
9127   }
9128   return SDValue();
9129 }
9130
9131 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9132 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9133 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9134 /// return true.
9135 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9136   SelectionDAG &DAG = DCI.DAG;
9137   EVT VT = N->getValueType(0);
9138   // vldN-dup instructions only support 64-bit vectors for N > 1.
9139   if (!VT.is64BitVector())
9140     return false;
9141
9142   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9143   SDNode *VLD = N->getOperand(0).getNode();
9144   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9145     return false;
9146   unsigned NumVecs = 0;
9147   unsigned NewOpc = 0;
9148   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9149   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9150     NumVecs = 2;
9151     NewOpc = ARMISD::VLD2DUP;
9152   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9153     NumVecs = 3;
9154     NewOpc = ARMISD::VLD3DUP;
9155   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9156     NumVecs = 4;
9157     NewOpc = ARMISD::VLD4DUP;
9158   } else {
9159     return false;
9160   }
9161
9162   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9163   // numbers match the load.
9164   unsigned VLDLaneNo =
9165     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9166   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9167        UI != UE; ++UI) {
9168     // Ignore uses of the chain result.
9169     if (UI.getUse().getResNo() == NumVecs)
9170       continue;
9171     SDNode *User = *UI;
9172     if (User->getOpcode() != ARMISD::VDUPLANE ||
9173         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9174       return false;
9175   }
9176
9177   // Create the vldN-dup node.
9178   EVT Tys[5];
9179   unsigned n;
9180   for (n = 0; n < NumVecs; ++n)
9181     Tys[n] = VT;
9182   Tys[n] = MVT::Other;
9183   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9184   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9185   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9186   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9187                                            Ops, VLDMemInt->getMemoryVT(),
9188                                            VLDMemInt->getMemOperand());
9189
9190   // Update the uses.
9191   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9192        UI != UE; ++UI) {
9193     unsigned ResNo = UI.getUse().getResNo();
9194     // Ignore uses of the chain result.
9195     if (ResNo == NumVecs)
9196       continue;
9197     SDNode *User = *UI;
9198     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9199   }
9200
9201   // Now the vldN-lane intrinsic is dead except for its chain result.
9202   // Update uses of the chain.
9203   std::vector<SDValue> VLDDupResults;
9204   for (unsigned n = 0; n < NumVecs; ++n)
9205     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9206   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9207   DCI.CombineTo(VLD, VLDDupResults);
9208
9209   return true;
9210 }
9211
9212 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9213 /// ARMISD::VDUPLANE.
9214 static SDValue PerformVDUPLANECombine(SDNode *N,
9215                                       TargetLowering::DAGCombinerInfo &DCI) {
9216   SDValue Op = N->getOperand(0);
9217
9218   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9219   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9220   if (CombineVLDDUP(N, DCI))
9221     return SDValue(N, 0);
9222
9223   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9224   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9225   while (Op.getOpcode() == ISD::BITCAST)
9226     Op = Op.getOperand(0);
9227   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9228     return SDValue();
9229
9230   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9231   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9232   // The canonical VMOV for a zero vector uses a 32-bit element size.
9233   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9234   unsigned EltBits;
9235   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9236     EltSize = 8;
9237   EVT VT = N->getValueType(0);
9238   if (EltSize > VT.getVectorElementType().getSizeInBits())
9239     return SDValue();
9240
9241   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9242 }
9243
9244 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9245 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9246 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9247 {
9248   integerPart cN;
9249   integerPart c0 = 0;
9250   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9251        I != E; I++) {
9252     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9253     if (!C)
9254       return false;
9255
9256     bool isExact;
9257     APFloat APF = C->getValueAPF();
9258     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9259         != APFloat::opOK || !isExact)
9260       return false;
9261
9262     c0 = (I == 0) ? cN : c0;
9263     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9264       return false;
9265   }
9266   C = c0;
9267   return true;
9268 }
9269
9270 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9271 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9272 /// when the VMUL has a constant operand that is a power of 2.
9273 ///
9274 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9275 ///  vmul.f32        d16, d17, d16
9276 ///  vcvt.s32.f32    d16, d16
9277 /// becomes:
9278 ///  vcvt.s32.f32    d16, d16, #3
9279 static SDValue PerformVCVTCombine(SDNode *N,
9280                                   TargetLowering::DAGCombinerInfo &DCI,
9281                                   const ARMSubtarget *Subtarget) {
9282   SelectionDAG &DAG = DCI.DAG;
9283   SDValue Op = N->getOperand(0);
9284
9285   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9286       Op.getOpcode() != ISD::FMUL)
9287     return SDValue();
9288
9289   uint64_t C;
9290   SDValue N0 = Op->getOperand(0);
9291   SDValue ConstVec = Op->getOperand(1);
9292   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9293
9294   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9295       !isConstVecPow2(ConstVec, isSigned, C))
9296     return SDValue();
9297
9298   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9299   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9300   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9301     // These instructions only exist converting from f32 to i32. We can handle
9302     // smaller integers by generating an extra truncate, but larger ones would
9303     // be lossy.
9304     return SDValue();
9305   }
9306
9307   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9308     Intrinsic::arm_neon_vcvtfp2fxu;
9309   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9310   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9311                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9312                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9313                                  DAG.getConstant(Log2_64(C), MVT::i32));
9314
9315   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9316     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9317
9318   return FixConv;
9319 }
9320
9321 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9322 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9323 /// when the VDIV has a constant operand that is a power of 2.
9324 ///
9325 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9326 ///  vcvt.f32.s32    d16, d16
9327 ///  vdiv.f32        d16, d17, d16
9328 /// becomes:
9329 ///  vcvt.f32.s32    d16, d16, #3
9330 static SDValue PerformVDIVCombine(SDNode *N,
9331                                   TargetLowering::DAGCombinerInfo &DCI,
9332                                   const ARMSubtarget *Subtarget) {
9333   SelectionDAG &DAG = DCI.DAG;
9334   SDValue Op = N->getOperand(0);
9335   unsigned OpOpcode = Op.getNode()->getOpcode();
9336
9337   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9338       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9339     return SDValue();
9340
9341   uint64_t C;
9342   SDValue ConstVec = N->getOperand(1);
9343   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9344
9345   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9346       !isConstVecPow2(ConstVec, isSigned, C))
9347     return SDValue();
9348
9349   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9350   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9351   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9352     // These instructions only exist converting from i32 to f32. We can handle
9353     // smaller integers by generating an extra extend, but larger ones would
9354     // be lossy.
9355     return SDValue();
9356   }
9357
9358   SDValue ConvInput = Op.getOperand(0);
9359   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9360   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9361     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9362                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9363                             ConvInput);
9364
9365   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9366     Intrinsic::arm_neon_vcvtfxu2fp;
9367   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9368                      Op.getValueType(),
9369                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9370                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9371 }
9372
9373 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9374 /// operand of a vector shift operation, where all the elements of the
9375 /// build_vector must have the same constant integer value.
9376 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9377   // Ignore bit_converts.
9378   while (Op.getOpcode() == ISD::BITCAST)
9379     Op = Op.getOperand(0);
9380   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9381   APInt SplatBits, SplatUndef;
9382   unsigned SplatBitSize;
9383   bool HasAnyUndefs;
9384   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9385                                       HasAnyUndefs, ElementBits) ||
9386       SplatBitSize > ElementBits)
9387     return false;
9388   Cnt = SplatBits.getSExtValue();
9389   return true;
9390 }
9391
9392 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9393 /// operand of a vector shift left operation.  That value must be in the range:
9394 ///   0 <= Value < ElementBits for a left shift; or
9395 ///   0 <= Value <= ElementBits for a long left shift.
9396 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9397   assert(VT.isVector() && "vector shift count is not a vector type");
9398   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9399   if (! getVShiftImm(Op, ElementBits, Cnt))
9400     return false;
9401   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9402 }
9403
9404 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9405 /// operand of a vector shift right operation.  For a shift opcode, the value
9406 /// is positive, but for an intrinsic the value count must be negative. The
9407 /// absolute value must be in the range:
9408 ///   1 <= |Value| <= ElementBits for a right shift; or
9409 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9410 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9411                          int64_t &Cnt) {
9412   assert(VT.isVector() && "vector shift count is not a vector type");
9413   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9414   if (! getVShiftImm(Op, ElementBits, Cnt))
9415     return false;
9416   if (isIntrinsic)
9417     Cnt = -Cnt;
9418   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9419 }
9420
9421 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9422 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9423   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9424   switch (IntNo) {
9425   default:
9426     // Don't do anything for most intrinsics.
9427     break;
9428
9429   // Vector shifts: check for immediate versions and lower them.
9430   // Note: This is done during DAG combining instead of DAG legalizing because
9431   // the build_vectors for 64-bit vector element shift counts are generally
9432   // not legal, and it is hard to see their values after they get legalized to
9433   // loads from a constant pool.
9434   case Intrinsic::arm_neon_vshifts:
9435   case Intrinsic::arm_neon_vshiftu:
9436   case Intrinsic::arm_neon_vrshifts:
9437   case Intrinsic::arm_neon_vrshiftu:
9438   case Intrinsic::arm_neon_vrshiftn:
9439   case Intrinsic::arm_neon_vqshifts:
9440   case Intrinsic::arm_neon_vqshiftu:
9441   case Intrinsic::arm_neon_vqshiftsu:
9442   case Intrinsic::arm_neon_vqshiftns:
9443   case Intrinsic::arm_neon_vqshiftnu:
9444   case Intrinsic::arm_neon_vqshiftnsu:
9445   case Intrinsic::arm_neon_vqrshiftns:
9446   case Intrinsic::arm_neon_vqrshiftnu:
9447   case Intrinsic::arm_neon_vqrshiftnsu: {
9448     EVT VT = N->getOperand(1).getValueType();
9449     int64_t Cnt;
9450     unsigned VShiftOpc = 0;
9451
9452     switch (IntNo) {
9453     case Intrinsic::arm_neon_vshifts:
9454     case Intrinsic::arm_neon_vshiftu:
9455       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9456         VShiftOpc = ARMISD::VSHL;
9457         break;
9458       }
9459       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9460         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9461                      ARMISD::VSHRs : ARMISD::VSHRu);
9462         break;
9463       }
9464       return SDValue();
9465
9466     case Intrinsic::arm_neon_vrshifts:
9467     case Intrinsic::arm_neon_vrshiftu:
9468       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9469         break;
9470       return SDValue();
9471
9472     case Intrinsic::arm_neon_vqshifts:
9473     case Intrinsic::arm_neon_vqshiftu:
9474       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9475         break;
9476       return SDValue();
9477
9478     case Intrinsic::arm_neon_vqshiftsu:
9479       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9480         break;
9481       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9482
9483     case Intrinsic::arm_neon_vrshiftn:
9484     case Intrinsic::arm_neon_vqshiftns:
9485     case Intrinsic::arm_neon_vqshiftnu:
9486     case Intrinsic::arm_neon_vqshiftnsu:
9487     case Intrinsic::arm_neon_vqrshiftns:
9488     case Intrinsic::arm_neon_vqrshiftnu:
9489     case Intrinsic::arm_neon_vqrshiftnsu:
9490       // Narrowing shifts require an immediate right shift.
9491       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9492         break;
9493       llvm_unreachable("invalid shift count for narrowing vector shift "
9494                        "intrinsic");
9495
9496     default:
9497       llvm_unreachable("unhandled vector shift");
9498     }
9499
9500     switch (IntNo) {
9501     case Intrinsic::arm_neon_vshifts:
9502     case Intrinsic::arm_neon_vshiftu:
9503       // Opcode already set above.
9504       break;
9505     case Intrinsic::arm_neon_vrshifts:
9506       VShiftOpc = ARMISD::VRSHRs; break;
9507     case Intrinsic::arm_neon_vrshiftu:
9508       VShiftOpc = ARMISD::VRSHRu; break;
9509     case Intrinsic::arm_neon_vrshiftn:
9510       VShiftOpc = ARMISD::VRSHRN; break;
9511     case Intrinsic::arm_neon_vqshifts:
9512       VShiftOpc = ARMISD::VQSHLs; break;
9513     case Intrinsic::arm_neon_vqshiftu:
9514       VShiftOpc = ARMISD::VQSHLu; break;
9515     case Intrinsic::arm_neon_vqshiftsu:
9516       VShiftOpc = ARMISD::VQSHLsu; break;
9517     case Intrinsic::arm_neon_vqshiftns:
9518       VShiftOpc = ARMISD::VQSHRNs; break;
9519     case Intrinsic::arm_neon_vqshiftnu:
9520       VShiftOpc = ARMISD::VQSHRNu; break;
9521     case Intrinsic::arm_neon_vqshiftnsu:
9522       VShiftOpc = ARMISD::VQSHRNsu; break;
9523     case Intrinsic::arm_neon_vqrshiftns:
9524       VShiftOpc = ARMISD::VQRSHRNs; break;
9525     case Intrinsic::arm_neon_vqrshiftnu:
9526       VShiftOpc = ARMISD::VQRSHRNu; break;
9527     case Intrinsic::arm_neon_vqrshiftnsu:
9528       VShiftOpc = ARMISD::VQRSHRNsu; break;
9529     }
9530
9531     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9532                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9533   }
9534
9535   case Intrinsic::arm_neon_vshiftins: {
9536     EVT VT = N->getOperand(1).getValueType();
9537     int64_t Cnt;
9538     unsigned VShiftOpc = 0;
9539
9540     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9541       VShiftOpc = ARMISD::VSLI;
9542     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9543       VShiftOpc = ARMISD::VSRI;
9544     else {
9545       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9546     }
9547
9548     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9549                        N->getOperand(1), N->getOperand(2),
9550                        DAG.getConstant(Cnt, MVT::i32));
9551   }
9552
9553   case Intrinsic::arm_neon_vqrshifts:
9554   case Intrinsic::arm_neon_vqrshiftu:
9555     // No immediate versions of these to check for.
9556     break;
9557   }
9558
9559   return SDValue();
9560 }
9561
9562 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9563 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9564 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9565 /// vector element shift counts are generally not legal, and it is hard to see
9566 /// their values after they get legalized to loads from a constant pool.
9567 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9568                                    const ARMSubtarget *ST) {
9569   EVT VT = N->getValueType(0);
9570   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9571     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9572     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9573     SDValue N1 = N->getOperand(1);
9574     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9575       SDValue N0 = N->getOperand(0);
9576       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9577           DAG.MaskedValueIsZero(N0.getOperand(0),
9578                                 APInt::getHighBitsSet(32, 16)))
9579         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9580     }
9581   }
9582
9583   // Nothing to be done for scalar shifts.
9584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9585   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9586     return SDValue();
9587
9588   assert(ST->hasNEON() && "unexpected vector shift");
9589   int64_t Cnt;
9590
9591   switch (N->getOpcode()) {
9592   default: llvm_unreachable("unexpected shift opcode");
9593
9594   case ISD::SHL:
9595     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9596       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9597                          DAG.getConstant(Cnt, MVT::i32));
9598     break;
9599
9600   case ISD::SRA:
9601   case ISD::SRL:
9602     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9603       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9604                             ARMISD::VSHRs : ARMISD::VSHRu);
9605       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9606                          DAG.getConstant(Cnt, MVT::i32));
9607     }
9608   }
9609   return SDValue();
9610 }
9611
9612 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9613 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9614 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9615                                     const ARMSubtarget *ST) {
9616   SDValue N0 = N->getOperand(0);
9617
9618   // Check for sign- and zero-extensions of vector extract operations of 8-
9619   // and 16-bit vector elements.  NEON supports these directly.  They are
9620   // handled during DAG combining because type legalization will promote them
9621   // to 32-bit types and it is messy to recognize the operations after that.
9622   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9623     SDValue Vec = N0.getOperand(0);
9624     SDValue Lane = N0.getOperand(1);
9625     EVT VT = N->getValueType(0);
9626     EVT EltVT = N0.getValueType();
9627     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9628
9629     if (VT == MVT::i32 &&
9630         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9631         TLI.isTypeLegal(Vec.getValueType()) &&
9632         isa<ConstantSDNode>(Lane)) {
9633
9634       unsigned Opc = 0;
9635       switch (N->getOpcode()) {
9636       default: llvm_unreachable("unexpected opcode");
9637       case ISD::SIGN_EXTEND:
9638         Opc = ARMISD::VGETLANEs;
9639         break;
9640       case ISD::ZERO_EXTEND:
9641       case ISD::ANY_EXTEND:
9642         Opc = ARMISD::VGETLANEu;
9643         break;
9644       }
9645       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9646     }
9647   }
9648
9649   return SDValue();
9650 }
9651
9652 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9653 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9654 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9655                                        const ARMSubtarget *ST) {
9656   // If the target supports NEON, try to use vmax/vmin instructions for f32
9657   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9658   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9659   // a NaN; only do the transformation when it matches that behavior.
9660
9661   // For now only do this when using NEON for FP operations; if using VFP, it
9662   // is not obvious that the benefit outweighs the cost of switching to the
9663   // NEON pipeline.
9664   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9665       N->getValueType(0) != MVT::f32)
9666     return SDValue();
9667
9668   SDValue CondLHS = N->getOperand(0);
9669   SDValue CondRHS = N->getOperand(1);
9670   SDValue LHS = N->getOperand(2);
9671   SDValue RHS = N->getOperand(3);
9672   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9673
9674   unsigned Opcode = 0;
9675   bool IsReversed;
9676   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9677     IsReversed = false; // x CC y ? x : y
9678   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9679     IsReversed = true ; // x CC y ? y : x
9680   } else {
9681     return SDValue();
9682   }
9683
9684   bool IsUnordered;
9685   switch (CC) {
9686   default: break;
9687   case ISD::SETOLT:
9688   case ISD::SETOLE:
9689   case ISD::SETLT:
9690   case ISD::SETLE:
9691   case ISD::SETULT:
9692   case ISD::SETULE:
9693     // If LHS is NaN, an ordered comparison will be false and the result will
9694     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9695     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9696     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9697     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9698       break;
9699     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9700     // will return -0, so vmin can only be used for unsafe math or if one of
9701     // the operands is known to be nonzero.
9702     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9703         !DAG.getTarget().Options.UnsafeFPMath &&
9704         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9705       break;
9706     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9707     break;
9708
9709   case ISD::SETOGT:
9710   case ISD::SETOGE:
9711   case ISD::SETGT:
9712   case ISD::SETGE:
9713   case ISD::SETUGT:
9714   case ISD::SETUGE:
9715     // If LHS is NaN, an ordered comparison will be false and the result will
9716     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9717     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9718     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9719     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9720       break;
9721     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9722     // will return +0, so vmax can only be used for unsafe math or if one of
9723     // the operands is known to be nonzero.
9724     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9725         !DAG.getTarget().Options.UnsafeFPMath &&
9726         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9727       break;
9728     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9729     break;
9730   }
9731
9732   if (!Opcode)
9733     return SDValue();
9734   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9735 }
9736
9737 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9738 SDValue
9739 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9740   SDValue Cmp = N->getOperand(4);
9741   if (Cmp.getOpcode() != ARMISD::CMPZ)
9742     // Only looking at EQ and NE cases.
9743     return SDValue();
9744
9745   EVT VT = N->getValueType(0);
9746   SDLoc dl(N);
9747   SDValue LHS = Cmp.getOperand(0);
9748   SDValue RHS = Cmp.getOperand(1);
9749   SDValue FalseVal = N->getOperand(0);
9750   SDValue TrueVal = N->getOperand(1);
9751   SDValue ARMcc = N->getOperand(2);
9752   ARMCC::CondCodes CC =
9753     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9754
9755   // Simplify
9756   //   mov     r1, r0
9757   //   cmp     r1, x
9758   //   mov     r0, y
9759   //   moveq   r0, x
9760   // to
9761   //   cmp     r0, x
9762   //   movne   r0, y
9763   //
9764   //   mov     r1, r0
9765   //   cmp     r1, x
9766   //   mov     r0, x
9767   //   movne   r0, y
9768   // to
9769   //   cmp     r0, x
9770   //   movne   r0, y
9771   /// FIXME: Turn this into a target neutral optimization?
9772   SDValue Res;
9773   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9774     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9775                       N->getOperand(3), Cmp);
9776   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9777     SDValue ARMcc;
9778     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9779     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9780                       N->getOperand(3), NewCmp);
9781   }
9782
9783   if (Res.getNode()) {
9784     APInt KnownZero, KnownOne;
9785     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9786     // Capture demanded bits information that would be otherwise lost.
9787     if (KnownZero == 0xfffffffe)
9788       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9789                         DAG.getValueType(MVT::i1));
9790     else if (KnownZero == 0xffffff00)
9791       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9792                         DAG.getValueType(MVT::i8));
9793     else if (KnownZero == 0xffff0000)
9794       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9795                         DAG.getValueType(MVT::i16));
9796   }
9797
9798   return Res;
9799 }
9800
9801 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9802                                              DAGCombinerInfo &DCI) const {
9803   switch (N->getOpcode()) {
9804   default: break;
9805   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9806   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9807   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9808   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9809   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9810   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9811   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9812   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9813   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
9814   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9815   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9816   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
9817   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9818   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9819   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9820   case ISD::FP_TO_SINT:
9821   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9822   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9823   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9824   case ISD::SHL:
9825   case ISD::SRA:
9826   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9827   case ISD::SIGN_EXTEND:
9828   case ISD::ZERO_EXTEND:
9829   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9830   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9831   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9832   case ARMISD::VLD2DUP:
9833   case ARMISD::VLD3DUP:
9834   case ARMISD::VLD4DUP:
9835     return CombineBaseUpdate(N, DCI);
9836   case ARMISD::BUILD_VECTOR:
9837     return PerformARMBUILD_VECTORCombine(N, DCI);
9838   case ISD::INTRINSIC_VOID:
9839   case ISD::INTRINSIC_W_CHAIN:
9840     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9841     case Intrinsic::arm_neon_vld1:
9842     case Intrinsic::arm_neon_vld2:
9843     case Intrinsic::arm_neon_vld3:
9844     case Intrinsic::arm_neon_vld4:
9845     case Intrinsic::arm_neon_vld2lane:
9846     case Intrinsic::arm_neon_vld3lane:
9847     case Intrinsic::arm_neon_vld4lane:
9848     case Intrinsic::arm_neon_vst1:
9849     case Intrinsic::arm_neon_vst2:
9850     case Intrinsic::arm_neon_vst3:
9851     case Intrinsic::arm_neon_vst4:
9852     case Intrinsic::arm_neon_vst2lane:
9853     case Intrinsic::arm_neon_vst3lane:
9854     case Intrinsic::arm_neon_vst4lane:
9855       return CombineBaseUpdate(N, DCI);
9856     default: break;
9857     }
9858     break;
9859   }
9860   return SDValue();
9861 }
9862
9863 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9864                                                           EVT VT) const {
9865   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9866 }
9867
9868 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9869                                                        unsigned,
9870                                                        unsigned,
9871                                                        bool *Fast) const {
9872   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9873   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9874
9875   switch (VT.getSimpleVT().SimpleTy) {
9876   default:
9877     return false;
9878   case MVT::i8:
9879   case MVT::i16:
9880   case MVT::i32: {
9881     // Unaligned access can use (for example) LRDB, LRDH, LDR
9882     if (AllowsUnaligned) {
9883       if (Fast)
9884         *Fast = Subtarget->hasV7Ops();
9885       return true;
9886     }
9887     return false;
9888   }
9889   case MVT::f64:
9890   case MVT::v2f64: {
9891     // For any little-endian targets with neon, we can support unaligned ld/st
9892     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9893     // A big-endian target may also explicitly support unaligned accesses
9894     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9895       if (Fast)
9896         *Fast = true;
9897       return true;
9898     }
9899     return false;
9900   }
9901   }
9902 }
9903
9904 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9905                        unsigned AlignCheck) {
9906   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9907           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9908 }
9909
9910 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9911                                            unsigned DstAlign, unsigned SrcAlign,
9912                                            bool IsMemset, bool ZeroMemset,
9913                                            bool MemcpyStrSrc,
9914                                            MachineFunction &MF) const {
9915   const Function *F = MF.getFunction();
9916
9917   // See if we can use NEON instructions for this...
9918   if ((!IsMemset || ZeroMemset) &&
9919       Subtarget->hasNEON() &&
9920       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9921                                        Attribute::NoImplicitFloat)) {
9922     bool Fast;
9923     if (Size >= 16 &&
9924         (memOpAlign(SrcAlign, DstAlign, 16) ||
9925          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9926       return MVT::v2f64;
9927     } else if (Size >= 8 &&
9928                (memOpAlign(SrcAlign, DstAlign, 8) ||
9929                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9930                  Fast))) {
9931       return MVT::f64;
9932     }
9933   }
9934
9935   // Lowering to i32/i16 if the size permits.
9936   if (Size >= 4)
9937     return MVT::i32;
9938   else if (Size >= 2)
9939     return MVT::i16;
9940
9941   // Let the target-independent logic figure it out.
9942   return MVT::Other;
9943 }
9944
9945 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9946   if (Val.getOpcode() != ISD::LOAD)
9947     return false;
9948
9949   EVT VT1 = Val.getValueType();
9950   if (!VT1.isSimple() || !VT1.isInteger() ||
9951       !VT2.isSimple() || !VT2.isInteger())
9952     return false;
9953
9954   switch (VT1.getSimpleVT().SimpleTy) {
9955   default: break;
9956   case MVT::i1:
9957   case MVT::i8:
9958   case MVT::i16:
9959     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9960     return true;
9961   }
9962
9963   return false;
9964 }
9965
9966 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9967   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9968     return false;
9969
9970   if (!isTypeLegal(EVT::getEVT(Ty1)))
9971     return false;
9972
9973   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9974
9975   // Assuming the caller doesn't have a zeroext or signext return parameter,
9976   // truncation all the way down to i1 is valid.
9977   return true;
9978 }
9979
9980
9981 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9982   if (V < 0)
9983     return false;
9984
9985   unsigned Scale = 1;
9986   switch (VT.getSimpleVT().SimpleTy) {
9987   default: return false;
9988   case MVT::i1:
9989   case MVT::i8:
9990     // Scale == 1;
9991     break;
9992   case MVT::i16:
9993     // Scale == 2;
9994     Scale = 2;
9995     break;
9996   case MVT::i32:
9997     // Scale == 4;
9998     Scale = 4;
9999     break;
10000   }
10001
10002   if ((V & (Scale - 1)) != 0)
10003     return false;
10004   V /= Scale;
10005   return V == (V & ((1LL << 5) - 1));
10006 }
10007
10008 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10009                                       const ARMSubtarget *Subtarget) {
10010   bool isNeg = false;
10011   if (V < 0) {
10012     isNeg = true;
10013     V = - V;
10014   }
10015
10016   switch (VT.getSimpleVT().SimpleTy) {
10017   default: return false;
10018   case MVT::i1:
10019   case MVT::i8:
10020   case MVT::i16:
10021   case MVT::i32:
10022     // + imm12 or - imm8
10023     if (isNeg)
10024       return V == (V & ((1LL << 8) - 1));
10025     return V == (V & ((1LL << 12) - 1));
10026   case MVT::f32:
10027   case MVT::f64:
10028     // Same as ARM mode. FIXME: NEON?
10029     if (!Subtarget->hasVFP2())
10030       return false;
10031     if ((V & 3) != 0)
10032       return false;
10033     V >>= 2;
10034     return V == (V & ((1LL << 8) - 1));
10035   }
10036 }
10037
10038 /// isLegalAddressImmediate - Return true if the integer value can be used
10039 /// as the offset of the target addressing mode for load / store of the
10040 /// given type.
10041 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10042                                     const ARMSubtarget *Subtarget) {
10043   if (V == 0)
10044     return true;
10045
10046   if (!VT.isSimple())
10047     return false;
10048
10049   if (Subtarget->isThumb1Only())
10050     return isLegalT1AddressImmediate(V, VT);
10051   else if (Subtarget->isThumb2())
10052     return isLegalT2AddressImmediate(V, VT, Subtarget);
10053
10054   // ARM mode.
10055   if (V < 0)
10056     V = - V;
10057   switch (VT.getSimpleVT().SimpleTy) {
10058   default: return false;
10059   case MVT::i1:
10060   case MVT::i8:
10061   case MVT::i32:
10062     // +- imm12
10063     return V == (V & ((1LL << 12) - 1));
10064   case MVT::i16:
10065     // +- imm8
10066     return V == (V & ((1LL << 8) - 1));
10067   case MVT::f32:
10068   case MVT::f64:
10069     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10070       return false;
10071     if ((V & 3) != 0)
10072       return false;
10073     V >>= 2;
10074     return V == (V & ((1LL << 8) - 1));
10075   }
10076 }
10077
10078 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10079                                                       EVT VT) const {
10080   int Scale = AM.Scale;
10081   if (Scale < 0)
10082     return false;
10083
10084   switch (VT.getSimpleVT().SimpleTy) {
10085   default: return false;
10086   case MVT::i1:
10087   case MVT::i8:
10088   case MVT::i16:
10089   case MVT::i32:
10090     if (Scale == 1)
10091       return true;
10092     // r + r << imm
10093     Scale = Scale & ~1;
10094     return Scale == 2 || Scale == 4 || Scale == 8;
10095   case MVT::i64:
10096     // r + r
10097     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10098       return true;
10099     return false;
10100   case MVT::isVoid:
10101     // Note, we allow "void" uses (basically, uses that aren't loads or
10102     // stores), because arm allows folding a scale into many arithmetic
10103     // operations.  This should be made more precise and revisited later.
10104
10105     // Allow r << imm, but the imm has to be a multiple of two.
10106     if (Scale & 1) return false;
10107     return isPowerOf2_32(Scale);
10108   }
10109 }
10110
10111 /// isLegalAddressingMode - Return true if the addressing mode represented
10112 /// by AM is legal for this target, for a load/store of the specified type.
10113 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
10114                                               Type *Ty) const {
10115   EVT VT = getValueType(Ty, true);
10116   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10117     return false;
10118
10119   // Can never fold addr of global into load/store.
10120   if (AM.BaseGV)
10121     return false;
10122
10123   switch (AM.Scale) {
10124   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10125     break;
10126   case 1:
10127     if (Subtarget->isThumb1Only())
10128       return false;
10129     // FALL THROUGH.
10130   default:
10131     // ARM doesn't support any R+R*scale+imm addr modes.
10132     if (AM.BaseOffs)
10133       return false;
10134
10135     if (!VT.isSimple())
10136       return false;
10137
10138     if (Subtarget->isThumb2())
10139       return isLegalT2ScaledAddressingMode(AM, VT);
10140
10141     int Scale = AM.Scale;
10142     switch (VT.getSimpleVT().SimpleTy) {
10143     default: return false;
10144     case MVT::i1:
10145     case MVT::i8:
10146     case MVT::i32:
10147       if (Scale < 0) Scale = -Scale;
10148       if (Scale == 1)
10149         return true;
10150       // r + r << imm
10151       return isPowerOf2_32(Scale & ~1);
10152     case MVT::i16:
10153     case MVT::i64:
10154       // r + r
10155       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10156         return true;
10157       return false;
10158
10159     case MVT::isVoid:
10160       // Note, we allow "void" uses (basically, uses that aren't loads or
10161       // stores), because arm allows folding a scale into many arithmetic
10162       // operations.  This should be made more precise and revisited later.
10163
10164       // Allow r << imm, but the imm has to be a multiple of two.
10165       if (Scale & 1) return false;
10166       return isPowerOf2_32(Scale);
10167     }
10168   }
10169   return true;
10170 }
10171
10172 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10173 /// icmp immediate, that is the target has icmp instructions which can compare
10174 /// a register against the immediate without having to materialize the
10175 /// immediate into a register.
10176 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10177   // Thumb2 and ARM modes can use cmn for negative immediates.
10178   if (!Subtarget->isThumb())
10179     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10180   if (Subtarget->isThumb2())
10181     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10182   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10183   return Imm >= 0 && Imm <= 255;
10184 }
10185
10186 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10187 /// *or sub* immediate, that is the target has add or sub instructions which can
10188 /// add a register with the immediate without having to materialize the
10189 /// immediate into a register.
10190 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10191   // Same encoding for add/sub, just flip the sign.
10192   int64_t AbsImm = llvm::abs64(Imm);
10193   if (!Subtarget->isThumb())
10194     return ARM_AM::getSOImmVal(AbsImm) != -1;
10195   if (Subtarget->isThumb2())
10196     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10197   // Thumb1 only has 8-bit unsigned immediate.
10198   return AbsImm >= 0 && AbsImm <= 255;
10199 }
10200
10201 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10202                                       bool isSEXTLoad, SDValue &Base,
10203                                       SDValue &Offset, bool &isInc,
10204                                       SelectionDAG &DAG) {
10205   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10206     return false;
10207
10208   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10209     // AddressingMode 3
10210     Base = Ptr->getOperand(0);
10211     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10212       int RHSC = (int)RHS->getZExtValue();
10213       if (RHSC < 0 && RHSC > -256) {
10214         assert(Ptr->getOpcode() == ISD::ADD);
10215         isInc = false;
10216         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10217         return true;
10218       }
10219     }
10220     isInc = (Ptr->getOpcode() == ISD::ADD);
10221     Offset = Ptr->getOperand(1);
10222     return true;
10223   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10224     // AddressingMode 2
10225     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10226       int RHSC = (int)RHS->getZExtValue();
10227       if (RHSC < 0 && RHSC > -0x1000) {
10228         assert(Ptr->getOpcode() == ISD::ADD);
10229         isInc = false;
10230         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10231         Base = Ptr->getOperand(0);
10232         return true;
10233       }
10234     }
10235
10236     if (Ptr->getOpcode() == ISD::ADD) {
10237       isInc = true;
10238       ARM_AM::ShiftOpc ShOpcVal=
10239         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10240       if (ShOpcVal != ARM_AM::no_shift) {
10241         Base = Ptr->getOperand(1);
10242         Offset = Ptr->getOperand(0);
10243       } else {
10244         Base = Ptr->getOperand(0);
10245         Offset = Ptr->getOperand(1);
10246       }
10247       return true;
10248     }
10249
10250     isInc = (Ptr->getOpcode() == ISD::ADD);
10251     Base = Ptr->getOperand(0);
10252     Offset = Ptr->getOperand(1);
10253     return true;
10254   }
10255
10256   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10257   return false;
10258 }
10259
10260 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10261                                      bool isSEXTLoad, SDValue &Base,
10262                                      SDValue &Offset, bool &isInc,
10263                                      SelectionDAG &DAG) {
10264   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10265     return false;
10266
10267   Base = Ptr->getOperand(0);
10268   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10269     int RHSC = (int)RHS->getZExtValue();
10270     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10271       assert(Ptr->getOpcode() == ISD::ADD);
10272       isInc = false;
10273       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10274       return true;
10275     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10276       isInc = Ptr->getOpcode() == ISD::ADD;
10277       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10278       return true;
10279     }
10280   }
10281
10282   return false;
10283 }
10284
10285 /// getPreIndexedAddressParts - returns true by value, base pointer and
10286 /// offset pointer and addressing mode by reference if the node's address
10287 /// can be legally represented as pre-indexed load / store address.
10288 bool
10289 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10290                                              SDValue &Offset,
10291                                              ISD::MemIndexedMode &AM,
10292                                              SelectionDAG &DAG) const {
10293   if (Subtarget->isThumb1Only())
10294     return false;
10295
10296   EVT VT;
10297   SDValue Ptr;
10298   bool isSEXTLoad = false;
10299   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10300     Ptr = LD->getBasePtr();
10301     VT  = LD->getMemoryVT();
10302     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10303   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10304     Ptr = ST->getBasePtr();
10305     VT  = ST->getMemoryVT();
10306   } else
10307     return false;
10308
10309   bool isInc;
10310   bool isLegal = false;
10311   if (Subtarget->isThumb2())
10312     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10313                                        Offset, isInc, DAG);
10314   else
10315     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10316                                         Offset, isInc, DAG);
10317   if (!isLegal)
10318     return false;
10319
10320   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10321   return true;
10322 }
10323
10324 /// getPostIndexedAddressParts - returns true by value, base pointer and
10325 /// offset pointer and addressing mode by reference if this node can be
10326 /// combined with a load / store to form a post-indexed load / store.
10327 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10328                                                    SDValue &Base,
10329                                                    SDValue &Offset,
10330                                                    ISD::MemIndexedMode &AM,
10331                                                    SelectionDAG &DAG) const {
10332   if (Subtarget->isThumb1Only())
10333     return false;
10334
10335   EVT VT;
10336   SDValue Ptr;
10337   bool isSEXTLoad = false;
10338   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10339     VT  = LD->getMemoryVT();
10340     Ptr = LD->getBasePtr();
10341     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10342   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10343     VT  = ST->getMemoryVT();
10344     Ptr = ST->getBasePtr();
10345   } else
10346     return false;
10347
10348   bool isInc;
10349   bool isLegal = false;
10350   if (Subtarget->isThumb2())
10351     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10352                                        isInc, DAG);
10353   else
10354     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10355                                         isInc, DAG);
10356   if (!isLegal)
10357     return false;
10358
10359   if (Ptr != Base) {
10360     // Swap base ptr and offset to catch more post-index load / store when
10361     // it's legal. In Thumb2 mode, offset must be an immediate.
10362     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10363         !Subtarget->isThumb2())
10364       std::swap(Base, Offset);
10365
10366     // Post-indexed load / store update the base pointer.
10367     if (Ptr != Base)
10368       return false;
10369   }
10370
10371   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10372   return true;
10373 }
10374
10375 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10376                                                       APInt &KnownZero,
10377                                                       APInt &KnownOne,
10378                                                       const SelectionDAG &DAG,
10379                                                       unsigned Depth) const {
10380   unsigned BitWidth = KnownOne.getBitWidth();
10381   KnownZero = KnownOne = APInt(BitWidth, 0);
10382   switch (Op.getOpcode()) {
10383   default: break;
10384   case ARMISD::ADDC:
10385   case ARMISD::ADDE:
10386   case ARMISD::SUBC:
10387   case ARMISD::SUBE:
10388     // These nodes' second result is a boolean
10389     if (Op.getResNo() == 0)
10390       break;
10391     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10392     break;
10393   case ARMISD::CMOV: {
10394     // Bits are known zero/one if known on the LHS and RHS.
10395     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10396     if (KnownZero == 0 && KnownOne == 0) return;
10397
10398     APInt KnownZeroRHS, KnownOneRHS;
10399     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10400     KnownZero &= KnownZeroRHS;
10401     KnownOne  &= KnownOneRHS;
10402     return;
10403   }
10404   case ISD::INTRINSIC_W_CHAIN: {
10405     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10406     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10407     switch (IntID) {
10408     default: return;
10409     case Intrinsic::arm_ldaex:
10410     case Intrinsic::arm_ldrex: {
10411       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10412       unsigned MemBits = VT.getScalarType().getSizeInBits();
10413       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10414       return;
10415     }
10416     }
10417   }
10418   }
10419 }
10420
10421 //===----------------------------------------------------------------------===//
10422 //                           ARM Inline Assembly Support
10423 //===----------------------------------------------------------------------===//
10424
10425 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10426   // Looking for "rev" which is V6+.
10427   if (!Subtarget->hasV6Ops())
10428     return false;
10429
10430   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10431   std::string AsmStr = IA->getAsmString();
10432   SmallVector<StringRef, 4> AsmPieces;
10433   SplitString(AsmStr, AsmPieces, ";\n");
10434
10435   switch (AsmPieces.size()) {
10436   default: return false;
10437   case 1:
10438     AsmStr = AsmPieces[0];
10439     AsmPieces.clear();
10440     SplitString(AsmStr, AsmPieces, " \t,");
10441
10442     // rev $0, $1
10443     if (AsmPieces.size() == 3 &&
10444         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10445         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10446       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10447       if (Ty && Ty->getBitWidth() == 32)
10448         return IntrinsicLowering::LowerToByteSwap(CI);
10449     }
10450     break;
10451   }
10452
10453   return false;
10454 }
10455
10456 /// getConstraintType - Given a constraint letter, return the type of
10457 /// constraint it is for this target.
10458 ARMTargetLowering::ConstraintType
10459 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10460   if (Constraint.size() == 1) {
10461     switch (Constraint[0]) {
10462     default:  break;
10463     case 'l': return C_RegisterClass;
10464     case 'w': return C_RegisterClass;
10465     case 'h': return C_RegisterClass;
10466     case 'x': return C_RegisterClass;
10467     case 't': return C_RegisterClass;
10468     case 'j': return C_Other; // Constant for movw.
10469       // An address with a single base register. Due to the way we
10470       // currently handle addresses it is the same as an 'r' memory constraint.
10471     case 'Q': return C_Memory;
10472     }
10473   } else if (Constraint.size() == 2) {
10474     switch (Constraint[0]) {
10475     default: break;
10476     // All 'U+' constraints are addresses.
10477     case 'U': return C_Memory;
10478     }
10479   }
10480   return TargetLowering::getConstraintType(Constraint);
10481 }
10482
10483 /// Examine constraint type and operand type and determine a weight value.
10484 /// This object must already have been set up with the operand type
10485 /// and the current alternative constraint selected.
10486 TargetLowering::ConstraintWeight
10487 ARMTargetLowering::getSingleConstraintMatchWeight(
10488     AsmOperandInfo &info, const char *constraint) const {
10489   ConstraintWeight weight = CW_Invalid;
10490   Value *CallOperandVal = info.CallOperandVal;
10491     // If we don't have a value, we can't do a match,
10492     // but allow it at the lowest weight.
10493   if (!CallOperandVal)
10494     return CW_Default;
10495   Type *type = CallOperandVal->getType();
10496   // Look at the constraint type.
10497   switch (*constraint) {
10498   default:
10499     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10500     break;
10501   case 'l':
10502     if (type->isIntegerTy()) {
10503       if (Subtarget->isThumb())
10504         weight = CW_SpecificReg;
10505       else
10506         weight = CW_Register;
10507     }
10508     break;
10509   case 'w':
10510     if (type->isFloatingPointTy())
10511       weight = CW_Register;
10512     break;
10513   }
10514   return weight;
10515 }
10516
10517 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10518 RCPair
10519 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10520                                                 MVT VT) const {
10521   if (Constraint.size() == 1) {
10522     // GCC ARM Constraint Letters
10523     switch (Constraint[0]) {
10524     case 'l': // Low regs or general regs.
10525       if (Subtarget->isThumb())
10526         return RCPair(0U, &ARM::tGPRRegClass);
10527       return RCPair(0U, &ARM::GPRRegClass);
10528     case 'h': // High regs or no regs.
10529       if (Subtarget->isThumb())
10530         return RCPair(0U, &ARM::hGPRRegClass);
10531       break;
10532     case 'r':
10533       return RCPair(0U, &ARM::GPRRegClass);
10534     case 'w':
10535       if (VT == MVT::Other)
10536         break;
10537       if (VT == MVT::f32)
10538         return RCPair(0U, &ARM::SPRRegClass);
10539       if (VT.getSizeInBits() == 64)
10540         return RCPair(0U, &ARM::DPRRegClass);
10541       if (VT.getSizeInBits() == 128)
10542         return RCPair(0U, &ARM::QPRRegClass);
10543       break;
10544     case 'x':
10545       if (VT == MVT::Other)
10546         break;
10547       if (VT == MVT::f32)
10548         return RCPair(0U, &ARM::SPR_8RegClass);
10549       if (VT.getSizeInBits() == 64)
10550         return RCPair(0U, &ARM::DPR_8RegClass);
10551       if (VT.getSizeInBits() == 128)
10552         return RCPair(0U, &ARM::QPR_8RegClass);
10553       break;
10554     case 't':
10555       if (VT == MVT::f32)
10556         return RCPair(0U, &ARM::SPRRegClass);
10557       break;
10558     }
10559   }
10560   if (StringRef("{cc}").equals_lower(Constraint))
10561     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10562
10563   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10564 }
10565
10566 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10567 /// vector.  If it is invalid, don't add anything to Ops.
10568 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10569                                                      std::string &Constraint,
10570                                                      std::vector<SDValue>&Ops,
10571                                                      SelectionDAG &DAG) const {
10572   SDValue Result;
10573
10574   // Currently only support length 1 constraints.
10575   if (Constraint.length() != 1) return;
10576
10577   char ConstraintLetter = Constraint[0];
10578   switch (ConstraintLetter) {
10579   default: break;
10580   case 'j':
10581   case 'I': case 'J': case 'K': case 'L':
10582   case 'M': case 'N': case 'O':
10583     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10584     if (!C)
10585       return;
10586
10587     int64_t CVal64 = C->getSExtValue();
10588     int CVal = (int) CVal64;
10589     // None of these constraints allow values larger than 32 bits.  Check
10590     // that the value fits in an int.
10591     if (CVal != CVal64)
10592       return;
10593
10594     switch (ConstraintLetter) {
10595       case 'j':
10596         // Constant suitable for movw, must be between 0 and
10597         // 65535.
10598         if (Subtarget->hasV6T2Ops())
10599           if (CVal >= 0 && CVal <= 65535)
10600             break;
10601         return;
10602       case 'I':
10603         if (Subtarget->isThumb1Only()) {
10604           // This must be a constant between 0 and 255, for ADD
10605           // immediates.
10606           if (CVal >= 0 && CVal <= 255)
10607             break;
10608         } else if (Subtarget->isThumb2()) {
10609           // A constant that can be used as an immediate value in a
10610           // data-processing instruction.
10611           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10612             break;
10613         } else {
10614           // A constant that can be used as an immediate value in a
10615           // data-processing instruction.
10616           if (ARM_AM::getSOImmVal(CVal) != -1)
10617             break;
10618         }
10619         return;
10620
10621       case 'J':
10622         if (Subtarget->isThumb()) {  // FIXME thumb2
10623           // This must be a constant between -255 and -1, for negated ADD
10624           // immediates. This can be used in GCC with an "n" modifier that
10625           // prints the negated value, for use with SUB instructions. It is
10626           // not useful otherwise but is implemented for compatibility.
10627           if (CVal >= -255 && CVal <= -1)
10628             break;
10629         } else {
10630           // This must be a constant between -4095 and 4095. It is not clear
10631           // what this constraint is intended for. Implemented for
10632           // compatibility with GCC.
10633           if (CVal >= -4095 && CVal <= 4095)
10634             break;
10635         }
10636         return;
10637
10638       case 'K':
10639         if (Subtarget->isThumb1Only()) {
10640           // A 32-bit value where only one byte has a nonzero value. Exclude
10641           // zero to match GCC. This constraint is used by GCC internally for
10642           // constants that can be loaded with a move/shift combination.
10643           // It is not useful otherwise but is implemented for compatibility.
10644           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10645             break;
10646         } else if (Subtarget->isThumb2()) {
10647           // A constant whose bitwise inverse can be used as an immediate
10648           // value in a data-processing instruction. This can be used in GCC
10649           // with a "B" modifier that prints the inverted value, for use with
10650           // BIC and MVN instructions. It is not useful otherwise but is
10651           // implemented for compatibility.
10652           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10653             break;
10654         } else {
10655           // A constant whose bitwise inverse can be used as an immediate
10656           // value in a data-processing instruction. This can be used in GCC
10657           // with a "B" modifier that prints the inverted value, for use with
10658           // BIC and MVN instructions. It is not useful otherwise but is
10659           // implemented for compatibility.
10660           if (ARM_AM::getSOImmVal(~CVal) != -1)
10661             break;
10662         }
10663         return;
10664
10665       case 'L':
10666         if (Subtarget->isThumb1Only()) {
10667           // This must be a constant between -7 and 7,
10668           // for 3-operand ADD/SUB immediate instructions.
10669           if (CVal >= -7 && CVal < 7)
10670             break;
10671         } else if (Subtarget->isThumb2()) {
10672           // A constant whose negation can be used as an immediate value in a
10673           // data-processing instruction. This can be used in GCC with an "n"
10674           // modifier that prints the negated value, for use with SUB
10675           // instructions. It is not useful otherwise but is implemented for
10676           // compatibility.
10677           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10678             break;
10679         } else {
10680           // A constant whose negation can be used as an immediate value in a
10681           // data-processing instruction. This can be used in GCC with an "n"
10682           // modifier that prints the negated value, for use with SUB
10683           // instructions. It is not useful otherwise but is implemented for
10684           // compatibility.
10685           if (ARM_AM::getSOImmVal(-CVal) != -1)
10686             break;
10687         }
10688         return;
10689
10690       case 'M':
10691         if (Subtarget->isThumb()) { // FIXME thumb2
10692           // This must be a multiple of 4 between 0 and 1020, for
10693           // ADD sp + immediate.
10694           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10695             break;
10696         } else {
10697           // A power of two or a constant between 0 and 32.  This is used in
10698           // GCC for the shift amount on shifted register operands, but it is
10699           // useful in general for any shift amounts.
10700           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10701             break;
10702         }
10703         return;
10704
10705       case 'N':
10706         if (Subtarget->isThumb()) {  // FIXME thumb2
10707           // This must be a constant between 0 and 31, for shift amounts.
10708           if (CVal >= 0 && CVal <= 31)
10709             break;
10710         }
10711         return;
10712
10713       case 'O':
10714         if (Subtarget->isThumb()) {  // FIXME thumb2
10715           // This must be a multiple of 4 between -508 and 508, for
10716           // ADD/SUB sp = sp + immediate.
10717           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10718             break;
10719         }
10720         return;
10721     }
10722     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10723     break;
10724   }
10725
10726   if (Result.getNode()) {
10727     Ops.push_back(Result);
10728     return;
10729   }
10730   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10731 }
10732
10733 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10734   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10735   unsigned Opcode = Op->getOpcode();
10736   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10737          "Invalid opcode for Div/Rem lowering");
10738   bool isSigned = (Opcode == ISD::SDIVREM);
10739   EVT VT = Op->getValueType(0);
10740   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10741
10742   RTLIB::Libcall LC;
10743   switch (VT.getSimpleVT().SimpleTy) {
10744   default: llvm_unreachable("Unexpected request for libcall!");
10745   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10746   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10747   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10748   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10749   }
10750
10751   SDValue InChain = DAG.getEntryNode();
10752
10753   TargetLowering::ArgListTy Args;
10754   TargetLowering::ArgListEntry Entry;
10755   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10756     EVT ArgVT = Op->getOperand(i).getValueType();
10757     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10758     Entry.Node = Op->getOperand(i);
10759     Entry.Ty = ArgTy;
10760     Entry.isSExt = isSigned;
10761     Entry.isZExt = !isSigned;
10762     Args.push_back(Entry);
10763   }
10764
10765   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10766                                          getPointerTy());
10767
10768   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10769
10770   SDLoc dl(Op);
10771   TargetLowering::CallLoweringInfo CLI(DAG);
10772   CLI.setDebugLoc(dl).setChain(InChain)
10773     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10774     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10775
10776   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10777   return CallInfo.first;
10778 }
10779
10780 SDValue
10781 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10782   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10783   SDLoc DL(Op);
10784
10785   // Get the inputs.
10786   SDValue Chain = Op.getOperand(0);
10787   SDValue Size  = Op.getOperand(1);
10788
10789   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10790                               DAG.getConstant(2, MVT::i32));
10791
10792   SDValue Flag;
10793   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10794   Flag = Chain.getValue(1);
10795
10796   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10797   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10798
10799   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10800   Chain = NewSP.getValue(1);
10801
10802   SDValue Ops[2] = { NewSP, Chain };
10803   return DAG.getMergeValues(Ops, DL);
10804 }
10805
10806 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10807   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
10808          "Unexpected type for custom-lowering FP_EXTEND");
10809
10810   RTLIB::Libcall LC;
10811   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
10812
10813   SDValue SrcVal = Op.getOperand(0);
10814   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10815                      /*isSigned*/ false, SDLoc(Op)).first;
10816 }
10817
10818 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
10819   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
10820          Subtarget->isFPOnlySP() &&
10821          "Unexpected type for custom-lowering FP_ROUND");
10822
10823   RTLIB::Libcall LC;
10824   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
10825
10826   SDValue SrcVal = Op.getOperand(0);
10827   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
10828                      /*isSigned*/ false, SDLoc(Op)).first;
10829 }
10830
10831 bool
10832 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10833   // The ARM target isn't yet aware of offsets.
10834   return false;
10835 }
10836
10837 bool ARM::isBitFieldInvertedMask(unsigned v) {
10838   if (v == 0xffffffff)
10839     return false;
10840
10841   // there can be 1's on either or both "outsides", all the "inside"
10842   // bits must be 0's
10843   unsigned TO = CountTrailingOnes_32(v);
10844   unsigned LO = CountLeadingOnes_32(v);
10845   v = (v >> TO) << TO;
10846   v = (v << LO) >> LO;
10847   return v == 0;
10848 }
10849
10850 /// isFPImmLegal - Returns true if the target can instruction select the
10851 /// specified FP immediate natively. If false, the legalizer will
10852 /// materialize the FP immediate as a load from a constant pool.
10853 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10854   if (!Subtarget->hasVFP3())
10855     return false;
10856   if (VT == MVT::f32)
10857     return ARM_AM::getFP32Imm(Imm) != -1;
10858   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
10859     return ARM_AM::getFP64Imm(Imm) != -1;
10860   return false;
10861 }
10862
10863 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10864 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10865 /// specified in the intrinsic calls.
10866 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10867                                            const CallInst &I,
10868                                            unsigned Intrinsic) const {
10869   switch (Intrinsic) {
10870   case Intrinsic::arm_neon_vld1:
10871   case Intrinsic::arm_neon_vld2:
10872   case Intrinsic::arm_neon_vld3:
10873   case Intrinsic::arm_neon_vld4:
10874   case Intrinsic::arm_neon_vld2lane:
10875   case Intrinsic::arm_neon_vld3lane:
10876   case Intrinsic::arm_neon_vld4lane: {
10877     Info.opc = ISD::INTRINSIC_W_CHAIN;
10878     // Conservatively set memVT to the entire set of vectors loaded.
10879     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10880     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10881     Info.ptrVal = I.getArgOperand(0);
10882     Info.offset = 0;
10883     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10884     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10885     Info.vol = false; // volatile loads with NEON intrinsics not supported
10886     Info.readMem = true;
10887     Info.writeMem = false;
10888     return true;
10889   }
10890   case Intrinsic::arm_neon_vst1:
10891   case Intrinsic::arm_neon_vst2:
10892   case Intrinsic::arm_neon_vst3:
10893   case Intrinsic::arm_neon_vst4:
10894   case Intrinsic::arm_neon_vst2lane:
10895   case Intrinsic::arm_neon_vst3lane:
10896   case Intrinsic::arm_neon_vst4lane: {
10897     Info.opc = ISD::INTRINSIC_VOID;
10898     // Conservatively set memVT to the entire set of vectors stored.
10899     unsigned NumElts = 0;
10900     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10901       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10902       if (!ArgTy->isVectorTy())
10903         break;
10904       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10905     }
10906     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10907     Info.ptrVal = I.getArgOperand(0);
10908     Info.offset = 0;
10909     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10910     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10911     Info.vol = false; // volatile stores with NEON intrinsics not supported
10912     Info.readMem = false;
10913     Info.writeMem = true;
10914     return true;
10915   }
10916   case Intrinsic::arm_ldaex:
10917   case Intrinsic::arm_ldrex: {
10918     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10919     Info.opc = ISD::INTRINSIC_W_CHAIN;
10920     Info.memVT = MVT::getVT(PtrTy->getElementType());
10921     Info.ptrVal = I.getArgOperand(0);
10922     Info.offset = 0;
10923     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10924     Info.vol = true;
10925     Info.readMem = true;
10926     Info.writeMem = false;
10927     return true;
10928   }
10929   case Intrinsic::arm_stlex:
10930   case Intrinsic::arm_strex: {
10931     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10932     Info.opc = ISD::INTRINSIC_W_CHAIN;
10933     Info.memVT = MVT::getVT(PtrTy->getElementType());
10934     Info.ptrVal = I.getArgOperand(1);
10935     Info.offset = 0;
10936     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10937     Info.vol = true;
10938     Info.readMem = false;
10939     Info.writeMem = true;
10940     return true;
10941   }
10942   case Intrinsic::arm_stlexd:
10943   case Intrinsic::arm_strexd: {
10944     Info.opc = ISD::INTRINSIC_W_CHAIN;
10945     Info.memVT = MVT::i64;
10946     Info.ptrVal = I.getArgOperand(2);
10947     Info.offset = 0;
10948     Info.align = 8;
10949     Info.vol = true;
10950     Info.readMem = false;
10951     Info.writeMem = true;
10952     return true;
10953   }
10954   case Intrinsic::arm_ldaexd:
10955   case Intrinsic::arm_ldrexd: {
10956     Info.opc = ISD::INTRINSIC_W_CHAIN;
10957     Info.memVT = MVT::i64;
10958     Info.ptrVal = I.getArgOperand(0);
10959     Info.offset = 0;
10960     Info.align = 8;
10961     Info.vol = true;
10962     Info.readMem = true;
10963     Info.writeMem = false;
10964     return true;
10965   }
10966   default:
10967     break;
10968   }
10969
10970   return false;
10971 }
10972
10973 /// \brief Returns true if it is beneficial to convert a load of a constant
10974 /// to just the constant itself.
10975 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10976                                                           Type *Ty) const {
10977   assert(Ty->isIntegerTy());
10978
10979   unsigned Bits = Ty->getPrimitiveSizeInBits();
10980   if (Bits == 0 || Bits > 32)
10981     return false;
10982   return true;
10983 }
10984
10985 static void makeDMB(IRBuilder<> &Builder, ARM_MB::MemBOpt Domain) {
10986   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10987   Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
10988   Constant *CDomain = Builder.getInt32(Domain);
10989   Builder.CreateCall(DMB, CDomain);
10990 }
10991
10992 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10993 void ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10994                                          AtomicOrdering Ord, bool IsStore,
10995                                          bool IsLoad) const {
10996   if (!getInsertFencesForAtomic())
10997     return;
10998
10999   switch (Ord) {
11000   case NotAtomic:
11001   case Unordered:
11002     llvm_unreachable("Invalid fence: unordered/non-atomic");
11003   case Monotonic:
11004   case Acquire:
11005     return; // Nothing to do
11006   case SequentiallyConsistent:
11007     if (!IsStore)
11008       return; // Nothing to do
11009               /*FALLTHROUGH*/
11010   case Release:
11011   case AcquireRelease:
11012     if (Subtarget->isSwift())
11013       makeDMB(Builder, ARM_MB::ISHST);
11014     // FIXME: add a comment with a link to documentation justifying this.
11015     else
11016       makeDMB(Builder, ARM_MB::ISH);
11017     return;
11018   }
11019 }
11020
11021 void ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11022                                           AtomicOrdering Ord, bool IsStore,
11023                                           bool IsLoad) const {
11024   if (!getInsertFencesForAtomic())
11025     return;
11026
11027   switch (Ord) {
11028   case NotAtomic:
11029   case Unordered:
11030     llvm_unreachable("Invalid fence: unordered/not-atomic");
11031   case Monotonic:
11032   case Release:
11033     return; // Nothing to do
11034   case Acquire:
11035   case AcquireRelease:
11036     case SequentiallyConsistent:
11037     makeDMB(Builder, ARM_MB::ISH);
11038     return;
11039   }
11040 }
11041
11042 // Loads and stores less than 64-bits are already atomic; ones above that
11043 // are doomed anyway, so defer to the default libcall and blame the OS when
11044 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11045 // anything for those.
11046 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11047   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11048   return (Size == 64) && !Subtarget->isMClass();
11049 }
11050
11051 // Loads and stores less than 64-bits are already atomic; ones above that
11052 // are doomed anyway, so defer to the default libcall and blame the OS when
11053 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11054 // anything for those.
11055 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11056   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11057   return (Size == 64) && !Subtarget->isMClass();
11058 }
11059
11060 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11061 // and up to 64 bits on the non-M profiles
11062 bool ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11063   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11064   return Size <= (Subtarget->isMClass() ? 32U : 64U);
11065 }
11066
11067 // This has so far only been implemented for MachO.
11068 bool ARMTargetLowering::useLoadStackGuardNode() const {
11069   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
11070 }
11071
11072 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11073                                          AtomicOrdering Ord) const {
11074   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11075   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11076   bool IsAcquire = isAtLeastAcquire(Ord);
11077
11078   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11079   // intrinsic must return {i32, i32} and we have to recombine them into a
11080   // single i64 here.
11081   if (ValTy->getPrimitiveSizeInBits() == 64) {
11082     Intrinsic::ID Int =
11083         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11084     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11085
11086     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11087     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11088
11089     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11090     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11091     if (!Subtarget->isLittle())
11092       std::swap (Lo, Hi);
11093     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11094     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11095     return Builder.CreateOr(
11096         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11097   }
11098
11099   Type *Tys[] = { Addr->getType() };
11100   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11101   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11102
11103   return Builder.CreateTruncOrBitCast(
11104       Builder.CreateCall(Ldrex, Addr),
11105       cast<PointerType>(Addr->getType())->getElementType());
11106 }
11107
11108 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11109                                                Value *Addr,
11110                                                AtomicOrdering Ord) const {
11111   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11112   bool IsRelease = isAtLeastRelease(Ord);
11113
11114   // Since the intrinsics must have legal type, the i64 intrinsics take two
11115   // parameters: "i32, i32". We must marshal Val into the appropriate form
11116   // before the call.
11117   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11118     Intrinsic::ID Int =
11119         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11120     Function *Strex = Intrinsic::getDeclaration(M, Int);
11121     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11122
11123     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11124     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11125     if (!Subtarget->isLittle())
11126       std::swap (Lo, Hi);
11127     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11128     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
11129   }
11130
11131   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11132   Type *Tys[] = { Addr->getType() };
11133   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11134
11135   return Builder.CreateCall2(
11136       Strex, Builder.CreateZExtOrBitCast(
11137                  Val, Strex->getFunctionType()->getParamType(0)),
11138       Addr);
11139 }
11140
11141 enum HABaseType {
11142   HA_UNKNOWN = 0,
11143   HA_FLOAT,
11144   HA_DOUBLE,
11145   HA_VECT64,
11146   HA_VECT128
11147 };
11148
11149 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11150                                    uint64_t &Members) {
11151   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
11152     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11153       uint64_t SubMembers = 0;
11154       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11155         return false;
11156       Members += SubMembers;
11157     }
11158   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
11159     uint64_t SubMembers = 0;
11160     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11161       return false;
11162     Members += SubMembers * AT->getNumElements();
11163   } else if (Ty->isFloatTy()) {
11164     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11165       return false;
11166     Members = 1;
11167     Base = HA_FLOAT;
11168   } else if (Ty->isDoubleTy()) {
11169     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11170       return false;
11171     Members = 1;
11172     Base = HA_DOUBLE;
11173   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
11174     Members = 1;
11175     switch (Base) {
11176     case HA_FLOAT:
11177     case HA_DOUBLE:
11178       return false;
11179     case HA_VECT64:
11180       return VT->getBitWidth() == 64;
11181     case HA_VECT128:
11182       return VT->getBitWidth() == 128;
11183     case HA_UNKNOWN:
11184       switch (VT->getBitWidth()) {
11185       case 64:
11186         Base = HA_VECT64;
11187         return true;
11188       case 128:
11189         Base = HA_VECT128;
11190         return true;
11191       default:
11192         return false;
11193       }
11194     }
11195   }
11196
11197   return (Members > 0 && Members <= 4);
11198 }
11199
11200 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
11201 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11202     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11203   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11204       CallingConv::ARM_AAPCS_VFP)
11205     return false;
11206
11207   HABaseType Base = HA_UNKNOWN;
11208   uint64_t Members = 0;
11209   bool result = isHomogeneousAggregate(Ty, Base, Members);
11210   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump());
11211   return result;
11212 }