[SDAG] Let the DAG combiner take care of dead nodes rather than manually
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/CodeGen/CallingConvLower.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineBasicBlock.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/GlobalValue.h"
39 #include "llvm/IR/IRBuilder.h"
40 #include "llvm/IR/Instruction.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/IR/Type.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/Support/CommandLine.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/ErrorHandling.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include <utility>
51 using namespace llvm;
52
53 #define DEBUG_TYPE "arm-isel"
54
55 STATISTIC(NumTailCalls, "Number of tail calls");
56 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
57 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
58
59 cl::opt<bool>
60 EnableARMLongCalls("arm-long-calls", cl::Hidden,
61   cl::desc("Generate calls via indirect call instructions"),
62   cl::init(false));
63
64 static cl::opt<bool>
65 ARMInterworking("arm-interworking", cl::Hidden,
66   cl::desc("Enable / disable ARM interworking (for debugging only)"),
67   cl::init(true));
68
69 namespace {
70   class ARMCCState : public CCState {
71   public:
72     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
73                const TargetMachine &TM, SmallVectorImpl<CCValAssign> &locs,
74                LLVMContext &C, ParmContext PC)
75         : CCState(CC, isVarArg, MF, TM, locs, C) {
76       assert(((PC == Call) || (PC == Prologue)) &&
77              "ARMCCState users must specify whether their context is call"
78              "or prologue generation.");
79       CallOrPrologue = PC;
80     }
81   };
82 }
83
84 // The APCS parameter registers.
85 static const MCPhysReg GPRArgRegs[] = {
86   ARM::R0, ARM::R1, ARM::R2, ARM::R3
87 };
88
89 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
90                                        MVT PromotedBitwiseVT) {
91   if (VT != PromotedLdStVT) {
92     setOperationAction(ISD::LOAD, VT, Promote);
93     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
94
95     setOperationAction(ISD::STORE, VT, Promote);
96     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
97   }
98
99   MVT ElemTy = VT.getVectorElementType();
100   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
101     setOperationAction(ISD::SETCC, VT, Custom);
102   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
103   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
104   if (ElemTy == MVT::i32) {
105     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
107     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
108     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
109   } else {
110     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
112     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
113     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
114   }
115   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
116   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
117   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
118   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
119   setOperationAction(ISD::SELECT,            VT, Expand);
120   setOperationAction(ISD::SELECT_CC,         VT, Expand);
121   setOperationAction(ISD::VSELECT,           VT, Expand);
122   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
123   if (VT.isInteger()) {
124     setOperationAction(ISD::SHL, VT, Custom);
125     setOperationAction(ISD::SRA, VT, Custom);
126     setOperationAction(ISD::SRL, VT, Custom);
127   }
128
129   // Promote all bit-wise operations.
130   if (VT.isInteger() && VT != PromotedBitwiseVT) {
131     setOperationAction(ISD::AND, VT, Promote);
132     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
133     setOperationAction(ISD::OR,  VT, Promote);
134     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
135     setOperationAction(ISD::XOR, VT, Promote);
136     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
137   }
138
139   // Neon does not support vector divide/remainder operations.
140   setOperationAction(ISD::SDIV, VT, Expand);
141   setOperationAction(ISD::UDIV, VT, Expand);
142   setOperationAction(ISD::FDIV, VT, Expand);
143   setOperationAction(ISD::SREM, VT, Expand);
144   setOperationAction(ISD::UREM, VT, Expand);
145   setOperationAction(ISD::FREM, VT, Expand);
146 }
147
148 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
149   addRegisterClass(VT, &ARM::DPRRegClass);
150   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
151 }
152
153 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
154   addRegisterClass(VT, &ARM::DPairRegClass);
155   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
156 }
157
158 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
159   if (TT.isOSBinFormatMachO())
160     return new TargetLoweringObjectFileMachO();
161   if (TT.isOSWindows())
162     return new TargetLoweringObjectFileCOFF();
163   return new ARMElfTargetObjectFile();
164 }
165
166 ARMTargetLowering::ARMTargetLowering(TargetMachine &TM)
167     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
168   Subtarget = &TM.getSubtarget<ARMSubtarget>();
169   RegInfo = TM.getRegisterInfo();
170   Itins = TM.getInstrItineraryData();
171
172   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
173
174   if (Subtarget->isTargetMachO()) {
175     // Uses VFP for Thumb libfuncs if available.
176     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
177         Subtarget->hasARMOps() && !TM.Options.UseSoftFloat) {
178       // Single-precision floating-point arithmetic.
179       setLibcallName(RTLIB::ADD_F32, "__addsf3vfp");
180       setLibcallName(RTLIB::SUB_F32, "__subsf3vfp");
181       setLibcallName(RTLIB::MUL_F32, "__mulsf3vfp");
182       setLibcallName(RTLIB::DIV_F32, "__divsf3vfp");
183
184       // Double-precision floating-point arithmetic.
185       setLibcallName(RTLIB::ADD_F64, "__adddf3vfp");
186       setLibcallName(RTLIB::SUB_F64, "__subdf3vfp");
187       setLibcallName(RTLIB::MUL_F64, "__muldf3vfp");
188       setLibcallName(RTLIB::DIV_F64, "__divdf3vfp");
189
190       // Single-precision comparisons.
191       setLibcallName(RTLIB::OEQ_F32, "__eqsf2vfp");
192       setLibcallName(RTLIB::UNE_F32, "__nesf2vfp");
193       setLibcallName(RTLIB::OLT_F32, "__ltsf2vfp");
194       setLibcallName(RTLIB::OLE_F32, "__lesf2vfp");
195       setLibcallName(RTLIB::OGE_F32, "__gesf2vfp");
196       setLibcallName(RTLIB::OGT_F32, "__gtsf2vfp");
197       setLibcallName(RTLIB::UO_F32,  "__unordsf2vfp");
198       setLibcallName(RTLIB::O_F32,   "__unordsf2vfp");
199
200       setCmpLibcallCC(RTLIB::OEQ_F32, ISD::SETNE);
201       setCmpLibcallCC(RTLIB::UNE_F32, ISD::SETNE);
202       setCmpLibcallCC(RTLIB::OLT_F32, ISD::SETNE);
203       setCmpLibcallCC(RTLIB::OLE_F32, ISD::SETNE);
204       setCmpLibcallCC(RTLIB::OGE_F32, ISD::SETNE);
205       setCmpLibcallCC(RTLIB::OGT_F32, ISD::SETNE);
206       setCmpLibcallCC(RTLIB::UO_F32,  ISD::SETNE);
207       setCmpLibcallCC(RTLIB::O_F32,   ISD::SETEQ);
208
209       // Double-precision comparisons.
210       setLibcallName(RTLIB::OEQ_F64, "__eqdf2vfp");
211       setLibcallName(RTLIB::UNE_F64, "__nedf2vfp");
212       setLibcallName(RTLIB::OLT_F64, "__ltdf2vfp");
213       setLibcallName(RTLIB::OLE_F64, "__ledf2vfp");
214       setLibcallName(RTLIB::OGE_F64, "__gedf2vfp");
215       setLibcallName(RTLIB::OGT_F64, "__gtdf2vfp");
216       setLibcallName(RTLIB::UO_F64,  "__unorddf2vfp");
217       setLibcallName(RTLIB::O_F64,   "__unorddf2vfp");
218
219       setCmpLibcallCC(RTLIB::OEQ_F64, ISD::SETNE);
220       setCmpLibcallCC(RTLIB::UNE_F64, ISD::SETNE);
221       setCmpLibcallCC(RTLIB::OLT_F64, ISD::SETNE);
222       setCmpLibcallCC(RTLIB::OLE_F64, ISD::SETNE);
223       setCmpLibcallCC(RTLIB::OGE_F64, ISD::SETNE);
224       setCmpLibcallCC(RTLIB::OGT_F64, ISD::SETNE);
225       setCmpLibcallCC(RTLIB::UO_F64,  ISD::SETNE);
226       setCmpLibcallCC(RTLIB::O_F64,   ISD::SETEQ);
227
228       // Floating-point to integer conversions.
229       // i64 conversions are done via library routines even when generating VFP
230       // instructions, so use the same ones.
231       setLibcallName(RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp");
232       setLibcallName(RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp");
233       setLibcallName(RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp");
234       setLibcallName(RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp");
235
236       // Conversions between floating types.
237       setLibcallName(RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp");
238       setLibcallName(RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp");
239
240       // Integer to floating-point conversions.
241       // i64 conversions are done via library routines even when generating VFP
242       // instructions, so use the same ones.
243       // FIXME: There appears to be some naming inconsistency in ARM libgcc:
244       // e.g., __floatunsidf vs. __floatunssidfvfp.
245       setLibcallName(RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp");
246       setLibcallName(RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp");
247       setLibcallName(RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp");
248       setLibcallName(RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp");
249     }
250   }
251
252   // These libcalls are not available in 32-bit.
253   setLibcallName(RTLIB::SHL_I128, nullptr);
254   setLibcallName(RTLIB::SRL_I128, nullptr);
255   setLibcallName(RTLIB::SRA_I128, nullptr);
256
257   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
258       !Subtarget->isTargetWindows()) {
259     static const struct {
260       const RTLIB::Libcall Op;
261       const char * const Name;
262       const CallingConv::ID CC;
263       const ISD::CondCode Cond;
264     } LibraryCalls[] = {
265       // Double-precision floating-point arithmetic helper functions
266       // RTABI chapter 4.1.2, Table 2
267       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
268       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
269       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
270       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
271
272       // Double-precision floating-point comparison helper functions
273       // RTABI chapter 4.1.2, Table 3
274       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
275       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
276       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
277       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
278       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
279       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
280       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
281       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
282
283       // Single-precision floating-point arithmetic helper functions
284       // RTABI chapter 4.1.2, Table 4
285       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
286       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
287       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
288       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
289
290       // Single-precision floating-point comparison helper functions
291       // RTABI chapter 4.1.2, Table 5
292       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
293       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
294       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
295       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
296       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
297       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
298       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
299       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
300
301       // Floating-point to integer conversions.
302       // RTABI chapter 4.1.2, Table 6
303       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
304       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
308       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
309       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
310       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311
312       // Conversions between floating types.
313       // RTABI chapter 4.1.2, Table 7
314       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317
318       // Integer to floating-point conversions.
319       // RTABI chapter 4.1.2, Table 8
320       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
328
329       // Long long helper functions
330       // RTABI chapter 4.2, Table 9
331       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335
336       // Integer division functions
337       // RTABI chapter 4.3.1
338       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346
347       // Memory operations
348       // RTABI chapter 4.3.4
349       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352     };
353
354     for (const auto &LC : LibraryCalls) {
355       setLibcallName(LC.Op, LC.Name);
356       setLibcallCallingConv(LC.Op, LC.CC);
357       if (LC.Cond != ISD::SETCC_INVALID)
358         setCmpLibcallCC(LC.Op, LC.Cond);
359     }
360   }
361
362   if (Subtarget->isTargetWindows()) {
363     static const struct {
364       const RTLIB::Libcall Op;
365       const char * const Name;
366       const CallingConv::ID CC;
367     } LibraryCalls[] = {
368       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
375       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
376     };
377
378     for (const auto &LC : LibraryCalls) {
379       setLibcallName(LC.Op, LC.Name);
380       setLibcallCallingConv(LC.Op, LC.CC);
381     }
382   }
383
384   // Use divmod compiler-rt calls for iOS 5.0 and later.
385   if (Subtarget->getTargetTriple().isiOS() &&
386       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
387     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
388     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
389   }
390
391   if (Subtarget->isThumb1Only())
392     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
393   else
394     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
395   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
396       !Subtarget->isThumb1Only()) {
397     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
398     if (!Subtarget->isFPOnlySP())
399       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
400   }
401
402   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
403        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
404     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
405          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
406       setTruncStoreAction((MVT::SimpleValueType)VT,
407                           (MVT::SimpleValueType)InnerVT, Expand);
408     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
409     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
411
412     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
413     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
416
417     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
418   }
419
420   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
421   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
422
423   if (Subtarget->hasNEON()) {
424     addDRTypeForNEON(MVT::v2f32);
425     addDRTypeForNEON(MVT::v8i8);
426     addDRTypeForNEON(MVT::v4i16);
427     addDRTypeForNEON(MVT::v2i32);
428     addDRTypeForNEON(MVT::v1i64);
429
430     addQRTypeForNEON(MVT::v4f32);
431     addQRTypeForNEON(MVT::v2f64);
432     addQRTypeForNEON(MVT::v16i8);
433     addQRTypeForNEON(MVT::v8i16);
434     addQRTypeForNEON(MVT::v4i32);
435     addQRTypeForNEON(MVT::v2i64);
436
437     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
438     // neither Neon nor VFP support any arithmetic operations on it.
439     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
440     // supported for v4f32.
441     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
442     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
443     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
444     // FIXME: Code duplication: FDIV and FREM are expanded always, see
445     // ARMTargetLowering::addTypeForNEON method for details.
446     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
447     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
448     // FIXME: Create unittest.
449     // In another words, find a way when "copysign" appears in DAG with vector
450     // operands.
451     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
452     // FIXME: Code duplication: SETCC has custom operation action, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
455     // FIXME: Create unittest for FNEG and for FABS.
456     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
457     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
458     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
460     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
461     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
463     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
466     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
468     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
469     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
470     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
471     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
472     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
474     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
475
476     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
477     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
478     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
479     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
481     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
484     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
487     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
488     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
489     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
491
492     // Mark v2f32 intrinsics.
493     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
494     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
495     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
496     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
498     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
501     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
504     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
505     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
506     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
508
509     // Neon does not support some operations on v1i64 and v2i64 types.
510     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
511     // Custom handling for some quad-vector types to detect VMULL.
512     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
513     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
514     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
515     // Custom handling for some vector types to avoid expensive expansions
516     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
517     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
518     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
519     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
520     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
521     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
522     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
523     // a destination type that is wider than the source, and nor does
524     // it have a FP_TO_[SU]INT instruction with a narrower destination than
525     // source.
526     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
527     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
530
531     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
532     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
533
534     // NEON does not have single instruction CTPOP for vectors with element
535     // types wider than 8-bits.  However, custom lowering can leverage the
536     // v8i8/v16i8 vcnt instruction.
537     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
538     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
541
542     // NEON only has FMA instructions as of VFP4.
543     if (!Subtarget->hasVFP4()) {
544       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
545       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
546     }
547
548     setTargetDAGCombine(ISD::INTRINSIC_VOID);
549     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
550     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
551     setTargetDAGCombine(ISD::SHL);
552     setTargetDAGCombine(ISD::SRL);
553     setTargetDAGCombine(ISD::SRA);
554     setTargetDAGCombine(ISD::SIGN_EXTEND);
555     setTargetDAGCombine(ISD::ZERO_EXTEND);
556     setTargetDAGCombine(ISD::ANY_EXTEND);
557     setTargetDAGCombine(ISD::SELECT_CC);
558     setTargetDAGCombine(ISD::BUILD_VECTOR);
559     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
560     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
561     setTargetDAGCombine(ISD::STORE);
562     setTargetDAGCombine(ISD::FP_TO_SINT);
563     setTargetDAGCombine(ISD::FP_TO_UINT);
564     setTargetDAGCombine(ISD::FDIV);
565
566     // It is legal to extload from v4i8 to v4i16 or v4i32.
567     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
568                   MVT::v4i16, MVT::v2i16,
569                   MVT::v2i32};
570     for (unsigned i = 0; i < 6; ++i) {
571       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
572       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
574     }
575   }
576
577   // ARM and Thumb2 support UMLAL/SMLAL.
578   if (!Subtarget->isThumb1Only())
579     setTargetDAGCombine(ISD::ADDC);
580
581
582   computeRegisterProperties();
583
584   // ARM does not have floating-point extending loads.
585   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
586   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
587
588   // ... or truncating stores
589   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
590   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
591   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
592
593   // ARM does not have i1 sign extending load.
594   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
595
596   // ARM supports all 4 flavors of integer indexed load / store.
597   if (!Subtarget->isThumb1Only()) {
598     for (unsigned im = (unsigned)ISD::PRE_INC;
599          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
600       setIndexedLoadAction(im,  MVT::i1,  Legal);
601       setIndexedLoadAction(im,  MVT::i8,  Legal);
602       setIndexedLoadAction(im,  MVT::i16, Legal);
603       setIndexedLoadAction(im,  MVT::i32, Legal);
604       setIndexedStoreAction(im, MVT::i1,  Legal);
605       setIndexedStoreAction(im, MVT::i8,  Legal);
606       setIndexedStoreAction(im, MVT::i16, Legal);
607       setIndexedStoreAction(im, MVT::i32, Legal);
608     }
609   }
610
611   setOperationAction(ISD::SADDO, MVT::i32, Custom);
612   setOperationAction(ISD::UADDO, MVT::i32, Custom);
613   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
614   setOperationAction(ISD::USUBO, MVT::i32, Custom);
615
616   // i64 operation support.
617   setOperationAction(ISD::MUL,     MVT::i64, Expand);
618   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
619   if (Subtarget->isThumb1Only()) {
620     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
621     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
622   }
623   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
624       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
625     setOperationAction(ISD::MULHS, MVT::i32, Expand);
626
627   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
628   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
629   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
630   setOperationAction(ISD::SRL,       MVT::i64, Custom);
631   setOperationAction(ISD::SRA,       MVT::i64, Custom);
632
633   if (!Subtarget->isThumb1Only()) {
634     // FIXME: We should do this for Thumb1 as well.
635     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
636     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
637     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
638     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
639   }
640
641   // ARM does not have ROTL.
642   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
643   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
644   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
645   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
646     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
647
648   // These just redirect to CTTZ and CTLZ on ARM.
649   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
650   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
651
652   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
653
654   // Only ARMv6 has BSWAP.
655   if (!Subtarget->hasV6Ops())
656     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
657
658   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
659       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
660     // These are expanded into libcalls if the cpu doesn't have HW divider.
661     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
662     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
663   }
664
665   // FIXME: Also set divmod for SREM on EABI
666   setOperationAction(ISD::SREM,  MVT::i32, Expand);
667   setOperationAction(ISD::UREM,  MVT::i32, Expand);
668   // Register based DivRem for AEABI (RTABI 4.2)
669   if (Subtarget->isTargetAEABI()) {
670     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
671     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
672     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
673     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
674     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
675     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
676     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
677     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
678
679     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
682     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
683     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
684     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
685     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
686     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
687
688     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
689     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
690   } else {
691     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
692     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
693   }
694
695   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
696   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
697   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
698   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
699   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
700
701   setOperationAction(ISD::TRAP, MVT::Other, Legal);
702
703   // Use the default implementation.
704   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
705   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
706   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
707   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
708   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
709   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
710
711   if (!Subtarget->isTargetMachO()) {
712     // Non-MachO platforms may return values in these registers via the
713     // personality function.
714     setExceptionPointerRegister(ARM::R0);
715     setExceptionSelectorRegister(ARM::R1);
716   }
717
718   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
719     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
720   else
721     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
722
723   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
724   // the default expansion.
725   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
726     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
727     // to ldrex/strex loops already.
728     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
729
730     // On v8, we have particularly efficient implementations of atomic fences
731     // if they can be combined with nearby atomic loads and stores.
732     if (!Subtarget->hasV8Ops()) {
733       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
734       setInsertFencesForAtomic(true);
735     }
736   } else {
737     // If there's anything we can use as a barrier, go through custom lowering
738     // for ATOMIC_FENCE.
739     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
740                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
741
742     // Set them all for expansion, which will force libcalls.
743     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
746     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
747     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
748     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
749     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
750     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
751     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
752     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
753     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
754     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
755     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
756     // Unordered/Monotonic case.
757     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
758     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
759   }
760
761   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
762
763   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
764   if (!Subtarget->hasV6Ops()) {
765     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
766     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
767   }
768   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
769
770   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
771       !Subtarget->isThumb1Only()) {
772     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
773     // iff target supports vfp2.
774     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
775     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
776   }
777
778   // We want to custom lower some of our intrinsics.
779   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
780   if (Subtarget->isTargetDarwin()) {
781     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
782     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
783     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
784   }
785
786   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
787   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
788   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
789   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
790   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
791   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
792   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
793   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
794   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
795
796   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
797   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
798   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
799   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
800   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
801
802   // We don't support sin/cos/fmod/copysign/pow
803   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
804   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
805   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
806   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
807   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
808   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
809   setOperationAction(ISD::FREM,      MVT::f64, Expand);
810   setOperationAction(ISD::FREM,      MVT::f32, Expand);
811   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
812       !Subtarget->isThumb1Only()) {
813     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
814     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
815   }
816   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
817   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
818
819   if (!Subtarget->hasVFP4()) {
820     setOperationAction(ISD::FMA, MVT::f64, Expand);
821     setOperationAction(ISD::FMA, MVT::f32, Expand);
822   }
823
824   // Various VFP goodness
825   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
826     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
827     if (Subtarget->hasVFP2()) {
828       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
829       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
830       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
831       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
832     }
833
834     // v8 adds f64 <-> f16 conversion. Before that it should be expanded.
835     if (!Subtarget->hasV8Ops()) {
836       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
837       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
838     }
839
840     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
841     if (!Subtarget->hasFP16()) {
842       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
843       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
844     }
845   }
846
847   // Combine sin / cos into one node or libcall if possible.
848   if (Subtarget->hasSinCos()) {
849     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
850     setLibcallName(RTLIB::SINCOS_F64, "sincos");
851     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
852       // For iOS, we don't want to the normal expansion of a libcall to
853       // sincos. We want to issue a libcall to __sincos_stret.
854       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
855       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
856     }
857   }
858
859   // We have target-specific dag combine patterns for the following nodes:
860   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
861   setTargetDAGCombine(ISD::ADD);
862   setTargetDAGCombine(ISD::SUB);
863   setTargetDAGCombine(ISD::MUL);
864   setTargetDAGCombine(ISD::AND);
865   setTargetDAGCombine(ISD::OR);
866   setTargetDAGCombine(ISD::XOR);
867
868   if (Subtarget->hasV6Ops())
869     setTargetDAGCombine(ISD::SRL);
870
871   setStackPointerRegisterToSaveRestore(ARM::SP);
872
873   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
874       !Subtarget->hasVFP2())
875     setSchedulingPreference(Sched::RegPressure);
876   else
877     setSchedulingPreference(Sched::Hybrid);
878
879   //// temporary - rewrite interface to use type
880   MaxStoresPerMemset = 8;
881   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
882   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
883   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
884   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
885   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
886
887   // On ARM arguments smaller than 4 bytes are extended, so all arguments
888   // are at least 4 bytes aligned.
889   setMinStackArgumentAlignment(4);
890
891   // Prefer likely predicted branches to selects on out-of-order cores.
892   PredictableSelectIsExpensive = Subtarget->isLikeA9();
893
894   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
895 }
896
897 // FIXME: It might make sense to define the representative register class as the
898 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
899 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
900 // SPR's representative would be DPR_VFP2. This should work well if register
901 // pressure tracking were modified such that a register use would increment the
902 // pressure of the register class's representative and all of it's super
903 // classes' representatives transitively. We have not implemented this because
904 // of the difficulty prior to coalescing of modeling operand register classes
905 // due to the common occurrence of cross class copies and subregister insertions
906 // and extractions.
907 std::pair<const TargetRegisterClass*, uint8_t>
908 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
909   const TargetRegisterClass *RRC = nullptr;
910   uint8_t Cost = 1;
911   switch (VT.SimpleTy) {
912   default:
913     return TargetLowering::findRepresentativeClass(VT);
914   // Use DPR as representative register class for all floating point
915   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
916   // the cost is 1 for both f32 and f64.
917   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
918   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
919     RRC = &ARM::DPRRegClass;
920     // When NEON is used for SP, only half of the register file is available
921     // because operations that define both SP and DP results will be constrained
922     // to the VFP2 class (D0-D15). We currently model this constraint prior to
923     // coalescing by double-counting the SP regs. See the FIXME above.
924     if (Subtarget->useNEONForSinglePrecisionFP())
925       Cost = 2;
926     break;
927   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
928   case MVT::v4f32: case MVT::v2f64:
929     RRC = &ARM::DPRRegClass;
930     Cost = 2;
931     break;
932   case MVT::v4i64:
933     RRC = &ARM::DPRRegClass;
934     Cost = 4;
935     break;
936   case MVT::v8i64:
937     RRC = &ARM::DPRRegClass;
938     Cost = 8;
939     break;
940   }
941   return std::make_pair(RRC, Cost);
942 }
943
944 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
945   switch (Opcode) {
946   default: return nullptr;
947   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
948   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
949   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
950   case ARMISD::CALL:          return "ARMISD::CALL";
951   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
952   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
953   case ARMISD::tCALL:         return "ARMISD::tCALL";
954   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
955   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
956   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
957   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
958   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
959   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
960   case ARMISD::CMP:           return "ARMISD::CMP";
961   case ARMISD::CMN:           return "ARMISD::CMN";
962   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
963   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
964   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
965   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
966   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
967
968   case ARMISD::CMOV:          return "ARMISD::CMOV";
969
970   case ARMISD::RBIT:          return "ARMISD::RBIT";
971
972   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
973   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
974   case ARMISD::SITOF:         return "ARMISD::SITOF";
975   case ARMISD::UITOF:         return "ARMISD::UITOF";
976
977   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
978   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
979   case ARMISD::RRX:           return "ARMISD::RRX";
980
981   case ARMISD::ADDC:          return "ARMISD::ADDC";
982   case ARMISD::ADDE:          return "ARMISD::ADDE";
983   case ARMISD::SUBC:          return "ARMISD::SUBC";
984   case ARMISD::SUBE:          return "ARMISD::SUBE";
985
986   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
987   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
988
989   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
990   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
991
992   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
993
994   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
995
996   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
997
998   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
999
1000   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1001
1002   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1003
1004   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1005   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1006   case ARMISD::VCGE:          return "ARMISD::VCGE";
1007   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1008   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1009   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1010   case ARMISD::VCGT:          return "ARMISD::VCGT";
1011   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1012   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1013   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1014   case ARMISD::VTST:          return "ARMISD::VTST";
1015
1016   case ARMISD::VSHL:          return "ARMISD::VSHL";
1017   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1018   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1019   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1020   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1021   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1022   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1023   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1024   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1025   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1026   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1027   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1028   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1029   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1030   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1031   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1032   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1033   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1034   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1035   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1036   case ARMISD::VDUP:          return "ARMISD::VDUP";
1037   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1038   case ARMISD::VEXT:          return "ARMISD::VEXT";
1039   case ARMISD::VREV64:        return "ARMISD::VREV64";
1040   case ARMISD::VREV32:        return "ARMISD::VREV32";
1041   case ARMISD::VREV16:        return "ARMISD::VREV16";
1042   case ARMISD::VZIP:          return "ARMISD::VZIP";
1043   case ARMISD::VUZP:          return "ARMISD::VUZP";
1044   case ARMISD::VTRN:          return "ARMISD::VTRN";
1045   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1046   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1047   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1048   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1049   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1050   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1051   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1052   case ARMISD::FMAX:          return "ARMISD::FMAX";
1053   case ARMISD::FMIN:          return "ARMISD::FMIN";
1054   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1055   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1056   case ARMISD::BFI:           return "ARMISD::BFI";
1057   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1058   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1059   case ARMISD::VBSL:          return "ARMISD::VBSL";
1060   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1061   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1062   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1063   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1064   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1065   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1066   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1067   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1068   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1069   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1070   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1071   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1072   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1073   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1074   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1075   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1076   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1077   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1078   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1079   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1080   }
1081 }
1082
1083 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1084   if (!VT.isVector()) return getPointerTy();
1085   return VT.changeVectorElementTypeToInteger();
1086 }
1087
1088 /// getRegClassFor - Return the register class that should be used for the
1089 /// specified value type.
1090 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1091   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1092   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1093   // load / store 4 to 8 consecutive D registers.
1094   if (Subtarget->hasNEON()) {
1095     if (VT == MVT::v4i64)
1096       return &ARM::QQPRRegClass;
1097     if (VT == MVT::v8i64)
1098       return &ARM::QQQQPRRegClass;
1099   }
1100   return TargetLowering::getRegClassFor(VT);
1101 }
1102
1103 // Create a fast isel object.
1104 FastISel *
1105 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1106                                   const TargetLibraryInfo *libInfo) const {
1107   return ARM::createFastISel(funcInfo, libInfo);
1108 }
1109
1110 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1111 /// be used for loads / stores from the global.
1112 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1113   return (Subtarget->isThumb1Only() ? 127 : 4095);
1114 }
1115
1116 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1117   unsigned NumVals = N->getNumValues();
1118   if (!NumVals)
1119     return Sched::RegPressure;
1120
1121   for (unsigned i = 0; i != NumVals; ++i) {
1122     EVT VT = N->getValueType(i);
1123     if (VT == MVT::Glue || VT == MVT::Other)
1124       continue;
1125     if (VT.isFloatingPoint() || VT.isVector())
1126       return Sched::ILP;
1127   }
1128
1129   if (!N->isMachineOpcode())
1130     return Sched::RegPressure;
1131
1132   // Load are scheduled for latency even if there instruction itinerary
1133   // is not available.
1134   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1135   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1136
1137   if (MCID.getNumDefs() == 0)
1138     return Sched::RegPressure;
1139   if (!Itins->isEmpty() &&
1140       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1141     return Sched::ILP;
1142
1143   return Sched::RegPressure;
1144 }
1145
1146 //===----------------------------------------------------------------------===//
1147 // Lowering Code
1148 //===----------------------------------------------------------------------===//
1149
1150 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1151 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1152   switch (CC) {
1153   default: llvm_unreachable("Unknown condition code!");
1154   case ISD::SETNE:  return ARMCC::NE;
1155   case ISD::SETEQ:  return ARMCC::EQ;
1156   case ISD::SETGT:  return ARMCC::GT;
1157   case ISD::SETGE:  return ARMCC::GE;
1158   case ISD::SETLT:  return ARMCC::LT;
1159   case ISD::SETLE:  return ARMCC::LE;
1160   case ISD::SETUGT: return ARMCC::HI;
1161   case ISD::SETUGE: return ARMCC::HS;
1162   case ISD::SETULT: return ARMCC::LO;
1163   case ISD::SETULE: return ARMCC::LS;
1164   }
1165 }
1166
1167 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1168 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1169                         ARMCC::CondCodes &CondCode2) {
1170   CondCode2 = ARMCC::AL;
1171   switch (CC) {
1172   default: llvm_unreachable("Unknown FP condition!");
1173   case ISD::SETEQ:
1174   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1175   case ISD::SETGT:
1176   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1177   case ISD::SETGE:
1178   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1179   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1180   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1181   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1182   case ISD::SETO:   CondCode = ARMCC::VC; break;
1183   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1184   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1185   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1186   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1187   case ISD::SETLT:
1188   case ISD::SETULT: CondCode = ARMCC::LT; break;
1189   case ISD::SETLE:
1190   case ISD::SETULE: CondCode = ARMCC::LE; break;
1191   case ISD::SETNE:
1192   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1193   }
1194 }
1195
1196 //===----------------------------------------------------------------------===//
1197 //                      Calling Convention Implementation
1198 //===----------------------------------------------------------------------===//
1199
1200 #include "ARMGenCallingConv.inc"
1201
1202 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1203 /// account presence of floating point hardware and calling convention
1204 /// limitations, such as support for variadic functions.
1205 CallingConv::ID
1206 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1207                                            bool isVarArg) const {
1208   switch (CC) {
1209   default:
1210     llvm_unreachable("Unsupported calling convention");
1211   case CallingConv::ARM_AAPCS:
1212   case CallingConv::ARM_APCS:
1213   case CallingConv::GHC:
1214     return CC;
1215   case CallingConv::ARM_AAPCS_VFP:
1216     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1217   case CallingConv::C:
1218     if (!Subtarget->isAAPCS_ABI())
1219       return CallingConv::ARM_APCS;
1220     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1221              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1222              !isVarArg)
1223       return CallingConv::ARM_AAPCS_VFP;
1224     else
1225       return CallingConv::ARM_AAPCS;
1226   case CallingConv::Fast:
1227     if (!Subtarget->isAAPCS_ABI()) {
1228       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1229         return CallingConv::Fast;
1230       return CallingConv::ARM_APCS;
1231     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1232       return CallingConv::ARM_AAPCS_VFP;
1233     else
1234       return CallingConv::ARM_AAPCS;
1235   }
1236 }
1237
1238 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1239 /// CallingConvention.
1240 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1241                                                  bool Return,
1242                                                  bool isVarArg) const {
1243   switch (getEffectiveCallingConv(CC, isVarArg)) {
1244   default:
1245     llvm_unreachable("Unsupported calling convention");
1246   case CallingConv::ARM_APCS:
1247     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1248   case CallingConv::ARM_AAPCS:
1249     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1250   case CallingConv::ARM_AAPCS_VFP:
1251     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1252   case CallingConv::Fast:
1253     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1254   case CallingConv::GHC:
1255     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1256   }
1257 }
1258
1259 /// LowerCallResult - Lower the result values of a call into the
1260 /// appropriate copies out of appropriate physical registers.
1261 SDValue
1262 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1263                                    CallingConv::ID CallConv, bool isVarArg,
1264                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1265                                    SDLoc dl, SelectionDAG &DAG,
1266                                    SmallVectorImpl<SDValue> &InVals,
1267                                    bool isThisReturn, SDValue ThisVal) const {
1268
1269   // Assign locations to each value returned by this call.
1270   SmallVector<CCValAssign, 16> RVLocs;
1271   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1272                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1273   CCInfo.AnalyzeCallResult(Ins,
1274                            CCAssignFnForNode(CallConv, /* Return*/ true,
1275                                              isVarArg));
1276
1277   // Copy all of the result registers out of their specified physreg.
1278   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1279     CCValAssign VA = RVLocs[i];
1280
1281     // Pass 'this' value directly from the argument to return value, to avoid
1282     // reg unit interference
1283     if (i == 0 && isThisReturn) {
1284       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1285              "unexpected return calling convention register assignment");
1286       InVals.push_back(ThisVal);
1287       continue;
1288     }
1289
1290     SDValue Val;
1291     if (VA.needsCustom()) {
1292       // Handle f64 or half of a v2f64.
1293       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1294                                       InFlag);
1295       Chain = Lo.getValue(1);
1296       InFlag = Lo.getValue(2);
1297       VA = RVLocs[++i]; // skip ahead to next loc
1298       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1299                                       InFlag);
1300       Chain = Hi.getValue(1);
1301       InFlag = Hi.getValue(2);
1302       if (!Subtarget->isLittle())
1303         std::swap (Lo, Hi);
1304       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1305
1306       if (VA.getLocVT() == MVT::v2f64) {
1307         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1308         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1309                           DAG.getConstant(0, MVT::i32));
1310
1311         VA = RVLocs[++i]; // skip ahead to next loc
1312         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1313         Chain = Lo.getValue(1);
1314         InFlag = Lo.getValue(2);
1315         VA = RVLocs[++i]; // skip ahead to next loc
1316         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1317         Chain = Hi.getValue(1);
1318         InFlag = Hi.getValue(2);
1319         if (!Subtarget->isLittle())
1320           std::swap (Lo, Hi);
1321         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1322         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1323                           DAG.getConstant(1, MVT::i32));
1324       }
1325     } else {
1326       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1327                                InFlag);
1328       Chain = Val.getValue(1);
1329       InFlag = Val.getValue(2);
1330     }
1331
1332     switch (VA.getLocInfo()) {
1333     default: llvm_unreachable("Unknown loc info!");
1334     case CCValAssign::Full: break;
1335     case CCValAssign::BCvt:
1336       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1337       break;
1338     }
1339
1340     InVals.push_back(Val);
1341   }
1342
1343   return Chain;
1344 }
1345
1346 /// LowerMemOpCallTo - Store the argument to the stack.
1347 SDValue
1348 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1349                                     SDValue StackPtr, SDValue Arg,
1350                                     SDLoc dl, SelectionDAG &DAG,
1351                                     const CCValAssign &VA,
1352                                     ISD::ArgFlagsTy Flags) const {
1353   unsigned LocMemOffset = VA.getLocMemOffset();
1354   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1355   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1356   return DAG.getStore(Chain, dl, Arg, PtrOff,
1357                       MachinePointerInfo::getStack(LocMemOffset),
1358                       false, false, 0);
1359 }
1360
1361 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1362                                          SDValue Chain, SDValue &Arg,
1363                                          RegsToPassVector &RegsToPass,
1364                                          CCValAssign &VA, CCValAssign &NextVA,
1365                                          SDValue &StackPtr,
1366                                          SmallVectorImpl<SDValue> &MemOpChains,
1367                                          ISD::ArgFlagsTy Flags) const {
1368
1369   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1370                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1371   unsigned id = Subtarget->isLittle() ? 0 : 1;
1372   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1373
1374   if (NextVA.isRegLoc())
1375     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1376   else {
1377     assert(NextVA.isMemLoc());
1378     if (!StackPtr.getNode())
1379       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1380
1381     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1382                                            dl, DAG, NextVA,
1383                                            Flags));
1384   }
1385 }
1386
1387 /// LowerCall - Lowering a call into a callseq_start <-
1388 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1389 /// nodes.
1390 SDValue
1391 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1392                              SmallVectorImpl<SDValue> &InVals) const {
1393   SelectionDAG &DAG                     = CLI.DAG;
1394   SDLoc &dl                          = CLI.DL;
1395   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1396   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1397   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1398   SDValue Chain                         = CLI.Chain;
1399   SDValue Callee                        = CLI.Callee;
1400   bool &isTailCall                      = CLI.IsTailCall;
1401   CallingConv::ID CallConv              = CLI.CallConv;
1402   bool doesNotRet                       = CLI.DoesNotReturn;
1403   bool isVarArg                         = CLI.IsVarArg;
1404
1405   MachineFunction &MF = DAG.getMachineFunction();
1406   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1407   bool isThisReturn   = false;
1408   bool isSibCall      = false;
1409
1410   // Disable tail calls if they're not supported.
1411   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1412     isTailCall = false;
1413
1414   if (isTailCall) {
1415     // Check if it's really possible to do a tail call.
1416     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1417                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1418                                                    Outs, OutVals, Ins, DAG);
1419     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1420       report_fatal_error("failed to perform tail call elimination on a call "
1421                          "site marked musttail");
1422     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1423     // detected sibcalls.
1424     if (isTailCall) {
1425       ++NumTailCalls;
1426       isSibCall = true;
1427     }
1428   }
1429
1430   // Analyze operands of the call, assigning locations to each operand.
1431   SmallVector<CCValAssign, 16> ArgLocs;
1432   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1433                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1434   CCInfo.AnalyzeCallOperands(Outs,
1435                              CCAssignFnForNode(CallConv, /* Return*/ false,
1436                                                isVarArg));
1437
1438   // Get a count of how many bytes are to be pushed on the stack.
1439   unsigned NumBytes = CCInfo.getNextStackOffset();
1440
1441   // For tail calls, memory operands are available in our caller's stack.
1442   if (isSibCall)
1443     NumBytes = 0;
1444
1445   // Adjust the stack pointer for the new arguments...
1446   // These operations are automatically eliminated by the prolog/epilog pass
1447   if (!isSibCall)
1448     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1449                                  dl);
1450
1451   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1452
1453   RegsToPassVector RegsToPass;
1454   SmallVector<SDValue, 8> MemOpChains;
1455
1456   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1457   // of tail call optimization, arguments are handled later.
1458   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1459        i != e;
1460        ++i, ++realArgIdx) {
1461     CCValAssign &VA = ArgLocs[i];
1462     SDValue Arg = OutVals[realArgIdx];
1463     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1464     bool isByVal = Flags.isByVal();
1465
1466     // Promote the value if needed.
1467     switch (VA.getLocInfo()) {
1468     default: llvm_unreachable("Unknown loc info!");
1469     case CCValAssign::Full: break;
1470     case CCValAssign::SExt:
1471       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1472       break;
1473     case CCValAssign::ZExt:
1474       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1475       break;
1476     case CCValAssign::AExt:
1477       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1478       break;
1479     case CCValAssign::BCvt:
1480       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1481       break;
1482     }
1483
1484     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1485     if (VA.needsCustom()) {
1486       if (VA.getLocVT() == MVT::v2f64) {
1487         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1488                                   DAG.getConstant(0, MVT::i32));
1489         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1490                                   DAG.getConstant(1, MVT::i32));
1491
1492         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1493                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1494
1495         VA = ArgLocs[++i]; // skip ahead to next loc
1496         if (VA.isRegLoc()) {
1497           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1498                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1499         } else {
1500           assert(VA.isMemLoc());
1501
1502           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1503                                                  dl, DAG, VA, Flags));
1504         }
1505       } else {
1506         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1507                          StackPtr, MemOpChains, Flags);
1508       }
1509     } else if (VA.isRegLoc()) {
1510       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1511         assert(VA.getLocVT() == MVT::i32 &&
1512                "unexpected calling convention register assignment");
1513         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1514                "unexpected use of 'returned'");
1515         isThisReturn = true;
1516       }
1517       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1518     } else if (isByVal) {
1519       assert(VA.isMemLoc());
1520       unsigned offset = 0;
1521
1522       // True if this byval aggregate will be split between registers
1523       // and memory.
1524       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1525       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1526
1527       if (CurByValIdx < ByValArgsCount) {
1528
1529         unsigned RegBegin, RegEnd;
1530         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1531
1532         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1533         unsigned int i, j;
1534         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1535           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1536           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1537           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1538                                      MachinePointerInfo(),
1539                                      false, false, false,
1540                                      DAG.InferPtrAlignment(AddArg));
1541           MemOpChains.push_back(Load.getValue(1));
1542           RegsToPass.push_back(std::make_pair(j, Load));
1543         }
1544
1545         // If parameter size outsides register area, "offset" value
1546         // helps us to calculate stack slot for remained part properly.
1547         offset = RegEnd - RegBegin;
1548
1549         CCInfo.nextInRegsParam();
1550       }
1551
1552       if (Flags.getByValSize() > 4*offset) {
1553         unsigned LocMemOffset = VA.getLocMemOffset();
1554         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1555         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1556                                   StkPtrOff);
1557         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1558         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1559         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1560                                            MVT::i32);
1561         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1562
1563         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1564         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1565         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1566                                           Ops));
1567       }
1568     } else if (!isSibCall) {
1569       assert(VA.isMemLoc());
1570
1571       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1572                                              dl, DAG, VA, Flags));
1573     }
1574   }
1575
1576   if (!MemOpChains.empty())
1577     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1578
1579   // Build a sequence of copy-to-reg nodes chained together with token chain
1580   // and flag operands which copy the outgoing args into the appropriate regs.
1581   SDValue InFlag;
1582   // Tail call byval lowering might overwrite argument registers so in case of
1583   // tail call optimization the copies to registers are lowered later.
1584   if (!isTailCall)
1585     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1586       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1587                                RegsToPass[i].second, InFlag);
1588       InFlag = Chain.getValue(1);
1589     }
1590
1591   // For tail calls lower the arguments to the 'real' stack slot.
1592   if (isTailCall) {
1593     // Force all the incoming stack arguments to be loaded from the stack
1594     // before any new outgoing arguments are stored to the stack, because the
1595     // outgoing stack slots may alias the incoming argument stack slots, and
1596     // the alias isn't otherwise explicit. This is slightly more conservative
1597     // than necessary, because it means that each store effectively depends
1598     // on every argument instead of just those arguments it would clobber.
1599
1600     // Do not flag preceding copytoreg stuff together with the following stuff.
1601     InFlag = SDValue();
1602     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1603       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1604                                RegsToPass[i].second, InFlag);
1605       InFlag = Chain.getValue(1);
1606     }
1607     InFlag = SDValue();
1608   }
1609
1610   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1611   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1612   // node so that legalize doesn't hack it.
1613   bool isDirect = false;
1614   bool isARMFunc = false;
1615   bool isLocalARMFunc = false;
1616   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1617
1618   if (EnableARMLongCalls) {
1619     assert((Subtarget->isTargetWindows() ||
1620             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1621            "long-calls with non-static relocation model!");
1622     // Handle a global address or an external symbol. If it's not one of
1623     // those, the target's already in a register, so we don't need to do
1624     // anything extra.
1625     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1626       const GlobalValue *GV = G->getGlobal();
1627       // Create a constant pool entry for the callee address
1628       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1629       ARMConstantPoolValue *CPV =
1630         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1631
1632       // Get the address of the callee into a register
1633       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1634       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1635       Callee = DAG.getLoad(getPointerTy(), dl,
1636                            DAG.getEntryNode(), CPAddr,
1637                            MachinePointerInfo::getConstantPool(),
1638                            false, false, false, 0);
1639     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1640       const char *Sym = S->getSymbol();
1641
1642       // Create a constant pool entry for the callee address
1643       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1644       ARMConstantPoolValue *CPV =
1645         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1646                                       ARMPCLabelIndex, 0);
1647       // Get the address of the callee into a register
1648       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1649       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1650       Callee = DAG.getLoad(getPointerTy(), dl,
1651                            DAG.getEntryNode(), CPAddr,
1652                            MachinePointerInfo::getConstantPool(),
1653                            false, false, false, 0);
1654     }
1655   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1656     const GlobalValue *GV = G->getGlobal();
1657     isDirect = true;
1658     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1659     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1660                    getTargetMachine().getRelocationModel() != Reloc::Static;
1661     isARMFunc = !Subtarget->isThumb() || isStub;
1662     // ARM call to a local ARM function is predicable.
1663     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1664     // tBX takes a register source operand.
1665     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1666       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1667       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1668                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1669     } else if (Subtarget->isTargetCOFF()) {
1670       assert(Subtarget->isTargetWindows() &&
1671              "Windows is the only supported COFF target");
1672       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1673                                  ? ARMII::MO_DLLIMPORT
1674                                  : ARMII::MO_NO_FLAG;
1675       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), /*Offset=*/0,
1676                                           TargetFlags);
1677       if (GV->hasDLLImportStorageClass())
1678         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1679                              DAG.getNode(ARMISD::Wrapper, dl, getPointerTy(),
1680                                          Callee), MachinePointerInfo::getGOT(),
1681                              false, false, false, 0);
1682     } else {
1683       // On ELF targets for PIC code, direct calls should go through the PLT
1684       unsigned OpFlags = 0;
1685       if (Subtarget->isTargetELF() &&
1686           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1687         OpFlags = ARMII::MO_PLT;
1688       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1689     }
1690   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1691     isDirect = true;
1692     bool isStub = Subtarget->isTargetMachO() &&
1693                   getTargetMachine().getRelocationModel() != Reloc::Static;
1694     isARMFunc = !Subtarget->isThumb() || isStub;
1695     // tBX takes a register source operand.
1696     const char *Sym = S->getSymbol();
1697     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1698       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1699       ARMConstantPoolValue *CPV =
1700         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1701                                       ARMPCLabelIndex, 4);
1702       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1703       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1704       Callee = DAG.getLoad(getPointerTy(), dl,
1705                            DAG.getEntryNode(), CPAddr,
1706                            MachinePointerInfo::getConstantPool(),
1707                            false, false, false, 0);
1708       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1709       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1710                            getPointerTy(), Callee, PICLabel);
1711     } else {
1712       unsigned OpFlags = 0;
1713       // On ELF targets for PIC code, direct calls should go through the PLT
1714       if (Subtarget->isTargetELF() &&
1715                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1716         OpFlags = ARMII::MO_PLT;
1717       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1718     }
1719   }
1720
1721   // FIXME: handle tail calls differently.
1722   unsigned CallOpc;
1723   bool HasMinSizeAttr = MF.getFunction()->getAttributes().hasAttribute(
1724       AttributeSet::FunctionIndex, Attribute::MinSize);
1725   if (Subtarget->isThumb()) {
1726     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1727       CallOpc = ARMISD::CALL_NOLINK;
1728     else
1729       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1730   } else {
1731     if (!isDirect && !Subtarget->hasV5TOps())
1732       CallOpc = ARMISD::CALL_NOLINK;
1733     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1734                // Emit regular call when code size is the priority
1735                !HasMinSizeAttr)
1736       // "mov lr, pc; b _foo" to avoid confusing the RSP
1737       CallOpc = ARMISD::CALL_NOLINK;
1738     else
1739       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1740   }
1741
1742   std::vector<SDValue> Ops;
1743   Ops.push_back(Chain);
1744   Ops.push_back(Callee);
1745
1746   // Add argument registers to the end of the list so that they are known live
1747   // into the call.
1748   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1749     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1750                                   RegsToPass[i].second.getValueType()));
1751
1752   // Add a register mask operand representing the call-preserved registers.
1753   if (!isTailCall) {
1754     const uint32_t *Mask;
1755     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1756     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1757     if (isThisReturn) {
1758       // For 'this' returns, use the R0-preserving mask if applicable
1759       Mask = ARI->getThisReturnPreservedMask(CallConv);
1760       if (!Mask) {
1761         // Set isThisReturn to false if the calling convention is not one that
1762         // allows 'returned' to be modeled in this way, so LowerCallResult does
1763         // not try to pass 'this' straight through
1764         isThisReturn = false;
1765         Mask = ARI->getCallPreservedMask(CallConv);
1766       }
1767     } else
1768       Mask = ARI->getCallPreservedMask(CallConv);
1769
1770     assert(Mask && "Missing call preserved mask for calling convention");
1771     Ops.push_back(DAG.getRegisterMask(Mask));
1772   }
1773
1774   if (InFlag.getNode())
1775     Ops.push_back(InFlag);
1776
1777   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1778   if (isTailCall)
1779     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1780
1781   // Returns a chain and a flag for retval copy to use.
1782   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1783   InFlag = Chain.getValue(1);
1784
1785   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1786                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1787   if (!Ins.empty())
1788     InFlag = Chain.getValue(1);
1789
1790   // Handle result values, copying them out of physregs into vregs that we
1791   // return.
1792   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1793                          InVals, isThisReturn,
1794                          isThisReturn ? OutVals[0] : SDValue());
1795 }
1796
1797 /// HandleByVal - Every parameter *after* a byval parameter is passed
1798 /// on the stack.  Remember the next parameter register to allocate,
1799 /// and then confiscate the rest of the parameter registers to insure
1800 /// this.
1801 void
1802 ARMTargetLowering::HandleByVal(
1803     CCState *State, unsigned &size, unsigned Align) const {
1804   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1805   assert((State->getCallOrPrologue() == Prologue ||
1806           State->getCallOrPrologue() == Call) &&
1807          "unhandled ParmContext");
1808
1809   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1810     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1811       unsigned AlignInRegs = Align / 4;
1812       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1813       for (unsigned i = 0; i < Waste; ++i)
1814         reg = State->AllocateReg(GPRArgRegs, 4);
1815     }
1816     if (reg != 0) {
1817       unsigned excess = 4 * (ARM::R4 - reg);
1818
1819       // Special case when NSAA != SP and parameter size greater than size of
1820       // all remained GPR regs. In that case we can't split parameter, we must
1821       // send it to stack. We also must set NCRN to R4, so waste all
1822       // remained registers.
1823       const unsigned NSAAOffset = State->getNextStackOffset();
1824       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1825         while (State->AllocateReg(GPRArgRegs, 4))
1826           ;
1827         return;
1828       }
1829
1830       // First register for byval parameter is the first register that wasn't
1831       // allocated before this method call, so it would be "reg".
1832       // If parameter is small enough to be saved in range [reg, r4), then
1833       // the end (first after last) register would be reg + param-size-in-regs,
1834       // else parameter would be splitted between registers and stack,
1835       // end register would be r4 in this case.
1836       unsigned ByValRegBegin = reg;
1837       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1838       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1839       // Note, first register is allocated in the beginning of function already,
1840       // allocate remained amount of registers we need.
1841       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1842         State->AllocateReg(GPRArgRegs, 4);
1843       // A byval parameter that is split between registers and memory needs its
1844       // size truncated here.
1845       // In the case where the entire structure fits in registers, we set the
1846       // size in memory to zero.
1847       if (size < excess)
1848         size = 0;
1849       else
1850         size -= excess;
1851     }
1852   }
1853 }
1854
1855 /// MatchingStackOffset - Return true if the given stack call argument is
1856 /// already available in the same position (relatively) of the caller's
1857 /// incoming argument stack.
1858 static
1859 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1860                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1861                          const TargetInstrInfo *TII) {
1862   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1863   int FI = INT_MAX;
1864   if (Arg.getOpcode() == ISD::CopyFromReg) {
1865     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1866     if (!TargetRegisterInfo::isVirtualRegister(VR))
1867       return false;
1868     MachineInstr *Def = MRI->getVRegDef(VR);
1869     if (!Def)
1870       return false;
1871     if (!Flags.isByVal()) {
1872       if (!TII->isLoadFromStackSlot(Def, FI))
1873         return false;
1874     } else {
1875       return false;
1876     }
1877   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1878     if (Flags.isByVal())
1879       // ByVal argument is passed in as a pointer but it's now being
1880       // dereferenced. e.g.
1881       // define @foo(%struct.X* %A) {
1882       //   tail call @bar(%struct.X* byval %A)
1883       // }
1884       return false;
1885     SDValue Ptr = Ld->getBasePtr();
1886     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1887     if (!FINode)
1888       return false;
1889     FI = FINode->getIndex();
1890   } else
1891     return false;
1892
1893   assert(FI != INT_MAX);
1894   if (!MFI->isFixedObjectIndex(FI))
1895     return false;
1896   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1897 }
1898
1899 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1900 /// for tail call optimization. Targets which want to do tail call
1901 /// optimization should implement this function.
1902 bool
1903 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1904                                                      CallingConv::ID CalleeCC,
1905                                                      bool isVarArg,
1906                                                      bool isCalleeStructRet,
1907                                                      bool isCallerStructRet,
1908                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1909                                     const SmallVectorImpl<SDValue> &OutVals,
1910                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1911                                                      SelectionDAG& DAG) const {
1912   const Function *CallerF = DAG.getMachineFunction().getFunction();
1913   CallingConv::ID CallerCC = CallerF->getCallingConv();
1914   bool CCMatch = CallerCC == CalleeCC;
1915
1916   // Look for obvious safe cases to perform tail call optimization that do not
1917   // require ABI changes. This is what gcc calls sibcall.
1918
1919   // Do not sibcall optimize vararg calls unless the call site is not passing
1920   // any arguments.
1921   if (isVarArg && !Outs.empty())
1922     return false;
1923
1924   // Exception-handling functions need a special set of instructions to indicate
1925   // a return to the hardware. Tail-calling another function would probably
1926   // break this.
1927   if (CallerF->hasFnAttribute("interrupt"))
1928     return false;
1929
1930   // Also avoid sibcall optimization if either caller or callee uses struct
1931   // return semantics.
1932   if (isCalleeStructRet || isCallerStructRet)
1933     return false;
1934
1935   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1936   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1937   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1938   // support in the assembler and linker to be used. This would need to be
1939   // fixed to fully support tail calls in Thumb1.
1940   //
1941   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1942   // LR.  This means if we need to reload LR, it takes an extra instructions,
1943   // which outweighs the value of the tail call; but here we don't know yet
1944   // whether LR is going to be used.  Probably the right approach is to
1945   // generate the tail call here and turn it back into CALL/RET in
1946   // emitEpilogue if LR is used.
1947
1948   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1949   // but we need to make sure there are enough registers; the only valid
1950   // registers are the 4 used for parameters.  We don't currently do this
1951   // case.
1952   if (Subtarget->isThumb1Only())
1953     return false;
1954
1955   // If the calling conventions do not match, then we'd better make sure the
1956   // results are returned in the same way as what the caller expects.
1957   if (!CCMatch) {
1958     SmallVector<CCValAssign, 16> RVLocs1;
1959     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1960                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1961     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1962
1963     SmallVector<CCValAssign, 16> RVLocs2;
1964     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1965                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1966     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1967
1968     if (RVLocs1.size() != RVLocs2.size())
1969       return false;
1970     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1971       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1972         return false;
1973       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1974         return false;
1975       if (RVLocs1[i].isRegLoc()) {
1976         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1977           return false;
1978       } else {
1979         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1980           return false;
1981       }
1982     }
1983   }
1984
1985   // If Caller's vararg or byval argument has been split between registers and
1986   // stack, do not perform tail call, since part of the argument is in caller's
1987   // local frame.
1988   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1989                                       getInfo<ARMFunctionInfo>();
1990   if (AFI_Caller->getArgRegsSaveSize())
1991     return false;
1992
1993   // If the callee takes no arguments then go on to check the results of the
1994   // call.
1995   if (!Outs.empty()) {
1996     // Check if stack adjustment is needed. For now, do not do this if any
1997     // argument is passed on the stack.
1998     SmallVector<CCValAssign, 16> ArgLocs;
1999     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
2000                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
2001     CCInfo.AnalyzeCallOperands(Outs,
2002                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2003     if (CCInfo.getNextStackOffset()) {
2004       MachineFunction &MF = DAG.getMachineFunction();
2005
2006       // Check if the arguments are already laid out in the right way as
2007       // the caller's fixed stack objects.
2008       MachineFrameInfo *MFI = MF.getFrameInfo();
2009       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2010       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
2011       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2012            i != e;
2013            ++i, ++realArgIdx) {
2014         CCValAssign &VA = ArgLocs[i];
2015         EVT RegVT = VA.getLocVT();
2016         SDValue Arg = OutVals[realArgIdx];
2017         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2018         if (VA.getLocInfo() == CCValAssign::Indirect)
2019           return false;
2020         if (VA.needsCustom()) {
2021           // f64 and vector types are split into multiple registers or
2022           // register/stack-slot combinations.  The types will not match
2023           // the registers; give up on memory f64 refs until we figure
2024           // out what to do about this.
2025           if (!VA.isRegLoc())
2026             return false;
2027           if (!ArgLocs[++i].isRegLoc())
2028             return false;
2029           if (RegVT == MVT::v2f64) {
2030             if (!ArgLocs[++i].isRegLoc())
2031               return false;
2032             if (!ArgLocs[++i].isRegLoc())
2033               return false;
2034           }
2035         } else if (!VA.isRegLoc()) {
2036           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2037                                    MFI, MRI, TII))
2038             return false;
2039         }
2040       }
2041     }
2042   }
2043
2044   return true;
2045 }
2046
2047 bool
2048 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2049                                   MachineFunction &MF, bool isVarArg,
2050                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2051                                   LLVMContext &Context) const {
2052   SmallVector<CCValAssign, 16> RVLocs;
2053   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2054   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2055                                                     isVarArg));
2056 }
2057
2058 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2059                                     SDLoc DL, SelectionDAG &DAG) {
2060   const MachineFunction &MF = DAG.getMachineFunction();
2061   const Function *F = MF.getFunction();
2062
2063   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2064
2065   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2066   // version of the "preferred return address". These offsets affect the return
2067   // instruction if this is a return from PL1 without hypervisor extensions.
2068   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2069   //    SWI:     0      "subs pc, lr, #0"
2070   //    ABORT:   +4     "subs pc, lr, #4"
2071   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2072   // UNDEF varies depending on where the exception came from ARM or Thumb
2073   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2074
2075   int64_t LROffset;
2076   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2077       IntKind == "ABORT")
2078     LROffset = 4;
2079   else if (IntKind == "SWI" || IntKind == "UNDEF")
2080     LROffset = 0;
2081   else
2082     report_fatal_error("Unsupported interrupt attribute. If present, value "
2083                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2084
2085   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2086
2087   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2088 }
2089
2090 SDValue
2091 ARMTargetLowering::LowerReturn(SDValue Chain,
2092                                CallingConv::ID CallConv, bool isVarArg,
2093                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2094                                const SmallVectorImpl<SDValue> &OutVals,
2095                                SDLoc dl, SelectionDAG &DAG) const {
2096
2097   // CCValAssign - represent the assignment of the return value to a location.
2098   SmallVector<CCValAssign, 16> RVLocs;
2099
2100   // CCState - Info about the registers and stack slots.
2101   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2102                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2103
2104   // Analyze outgoing return values.
2105   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2106                                                isVarArg));
2107
2108   SDValue Flag;
2109   SmallVector<SDValue, 4> RetOps;
2110   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2111   bool isLittleEndian = Subtarget->isLittle();
2112
2113   // Copy the result values into the output registers.
2114   for (unsigned i = 0, realRVLocIdx = 0;
2115        i != RVLocs.size();
2116        ++i, ++realRVLocIdx) {
2117     CCValAssign &VA = RVLocs[i];
2118     assert(VA.isRegLoc() && "Can only return in registers!");
2119
2120     SDValue Arg = OutVals[realRVLocIdx];
2121
2122     switch (VA.getLocInfo()) {
2123     default: llvm_unreachable("Unknown loc info!");
2124     case CCValAssign::Full: break;
2125     case CCValAssign::BCvt:
2126       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2127       break;
2128     }
2129
2130     if (VA.needsCustom()) {
2131       if (VA.getLocVT() == MVT::v2f64) {
2132         // Extract the first half and return it in two registers.
2133         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2134                                    DAG.getConstant(0, MVT::i32));
2135         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2136                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2137
2138         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2139                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2140                                  Flag);
2141         Flag = Chain.getValue(1);
2142         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2143         VA = RVLocs[++i]; // skip ahead to next loc
2144         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2145                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2146                                  Flag);
2147         Flag = Chain.getValue(1);
2148         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2149         VA = RVLocs[++i]; // skip ahead to next loc
2150
2151         // Extract the 2nd half and fall through to handle it as an f64 value.
2152         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2153                           DAG.getConstant(1, MVT::i32));
2154       }
2155       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2156       // available.
2157       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2158                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2159       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2160                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2161                                Flag);
2162       Flag = Chain.getValue(1);
2163       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2164       VA = RVLocs[++i]; // skip ahead to next loc
2165       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2166                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2167                                Flag);
2168     } else
2169       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2170
2171     // Guarantee that all emitted copies are
2172     // stuck together, avoiding something bad.
2173     Flag = Chain.getValue(1);
2174     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2175   }
2176
2177   // Update chain and glue.
2178   RetOps[0] = Chain;
2179   if (Flag.getNode())
2180     RetOps.push_back(Flag);
2181
2182   // CPUs which aren't M-class use a special sequence to return from
2183   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2184   // though we use "subs pc, lr, #N").
2185   //
2186   // M-class CPUs actually use a normal return sequence with a special
2187   // (hardware-provided) value in LR, so the normal code path works.
2188   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2189       !Subtarget->isMClass()) {
2190     if (Subtarget->isThumb1Only())
2191       report_fatal_error("interrupt attribute is not supported in Thumb1");
2192     return LowerInterruptReturn(RetOps, dl, DAG);
2193   }
2194
2195   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2196 }
2197
2198 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2199   if (N->getNumValues() != 1)
2200     return false;
2201   if (!N->hasNUsesOfValue(1, 0))
2202     return false;
2203
2204   SDValue TCChain = Chain;
2205   SDNode *Copy = *N->use_begin();
2206   if (Copy->getOpcode() == ISD::CopyToReg) {
2207     // If the copy has a glue operand, we conservatively assume it isn't safe to
2208     // perform a tail call.
2209     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2210       return false;
2211     TCChain = Copy->getOperand(0);
2212   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2213     SDNode *VMov = Copy;
2214     // f64 returned in a pair of GPRs.
2215     SmallPtrSet<SDNode*, 2> Copies;
2216     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2217          UI != UE; ++UI) {
2218       if (UI->getOpcode() != ISD::CopyToReg)
2219         return false;
2220       Copies.insert(*UI);
2221     }
2222     if (Copies.size() > 2)
2223       return false;
2224
2225     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2226          UI != UE; ++UI) {
2227       SDValue UseChain = UI->getOperand(0);
2228       if (Copies.count(UseChain.getNode()))
2229         // Second CopyToReg
2230         Copy = *UI;
2231       else
2232         // First CopyToReg
2233         TCChain = UseChain;
2234     }
2235   } else if (Copy->getOpcode() == ISD::BITCAST) {
2236     // f32 returned in a single GPR.
2237     if (!Copy->hasOneUse())
2238       return false;
2239     Copy = *Copy->use_begin();
2240     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2241       return false;
2242     TCChain = Copy->getOperand(0);
2243   } else {
2244     return false;
2245   }
2246
2247   bool HasRet = false;
2248   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2249        UI != UE; ++UI) {
2250     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2251         UI->getOpcode() != ARMISD::INTRET_FLAG)
2252       return false;
2253     HasRet = true;
2254   }
2255
2256   if (!HasRet)
2257     return false;
2258
2259   Chain = TCChain;
2260   return true;
2261 }
2262
2263 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2264   if (!Subtarget->supportsTailCall())
2265     return false;
2266
2267   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2268     return false;
2269
2270   return !Subtarget->isThumb1Only();
2271 }
2272
2273 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2274 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2275 // one of the above mentioned nodes. It has to be wrapped because otherwise
2276 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2277 // be used to form addressing mode. These wrapped nodes will be selected
2278 // into MOVi.
2279 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2280   EVT PtrVT = Op.getValueType();
2281   // FIXME there is no actual debug info here
2282   SDLoc dl(Op);
2283   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2284   SDValue Res;
2285   if (CP->isMachineConstantPoolEntry())
2286     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2287                                     CP->getAlignment());
2288   else
2289     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2290                                     CP->getAlignment());
2291   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2292 }
2293
2294 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2295   return MachineJumpTableInfo::EK_Inline;
2296 }
2297
2298 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2299                                              SelectionDAG &DAG) const {
2300   MachineFunction &MF = DAG.getMachineFunction();
2301   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2302   unsigned ARMPCLabelIndex = 0;
2303   SDLoc DL(Op);
2304   EVT PtrVT = getPointerTy();
2305   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2306   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2307   SDValue CPAddr;
2308   if (RelocM == Reloc::Static) {
2309     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2310   } else {
2311     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2312     ARMPCLabelIndex = AFI->createPICLabelUId();
2313     ARMConstantPoolValue *CPV =
2314       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2315                                       ARMCP::CPBlockAddress, PCAdj);
2316     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2317   }
2318   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2319   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2320                                MachinePointerInfo::getConstantPool(),
2321                                false, false, false, 0);
2322   if (RelocM == Reloc::Static)
2323     return Result;
2324   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2325   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2326 }
2327
2328 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2329 SDValue
2330 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2331                                                  SelectionDAG &DAG) const {
2332   SDLoc dl(GA);
2333   EVT PtrVT = getPointerTy();
2334   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2335   MachineFunction &MF = DAG.getMachineFunction();
2336   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2337   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2338   ARMConstantPoolValue *CPV =
2339     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2340                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2341   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2342   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2343   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2344                          MachinePointerInfo::getConstantPool(),
2345                          false, false, false, 0);
2346   SDValue Chain = Argument.getValue(1);
2347
2348   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2349   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2350
2351   // call __tls_get_addr.
2352   ArgListTy Args;
2353   ArgListEntry Entry;
2354   Entry.Node = Argument;
2355   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2356   Args.push_back(Entry);
2357
2358   // FIXME: is there useful debug info available here?
2359   TargetLowering::CallLoweringInfo CLI(DAG);
2360   CLI.setDebugLoc(dl).setChain(Chain)
2361     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2362                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2363                0);
2364
2365   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2366   return CallResult.first;
2367 }
2368
2369 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2370 // "local exec" model.
2371 SDValue
2372 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2373                                         SelectionDAG &DAG,
2374                                         TLSModel::Model model) const {
2375   const GlobalValue *GV = GA->getGlobal();
2376   SDLoc dl(GA);
2377   SDValue Offset;
2378   SDValue Chain = DAG.getEntryNode();
2379   EVT PtrVT = getPointerTy();
2380   // Get the Thread Pointer
2381   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2382
2383   if (model == TLSModel::InitialExec) {
2384     MachineFunction &MF = DAG.getMachineFunction();
2385     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2386     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2387     // Initial exec model.
2388     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2389     ARMConstantPoolValue *CPV =
2390       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2391                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2392                                       true);
2393     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2394     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2395     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2396                          MachinePointerInfo::getConstantPool(),
2397                          false, false, false, 0);
2398     Chain = Offset.getValue(1);
2399
2400     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2401     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2402
2403     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2404                          MachinePointerInfo::getConstantPool(),
2405                          false, false, false, 0);
2406   } else {
2407     // local exec model
2408     assert(model == TLSModel::LocalExec);
2409     ARMConstantPoolValue *CPV =
2410       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2411     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2412     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2413     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2414                          MachinePointerInfo::getConstantPool(),
2415                          false, false, false, 0);
2416   }
2417
2418   // The address of the thread local variable is the add of the thread
2419   // pointer with the offset of the variable.
2420   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2421 }
2422
2423 SDValue
2424 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2425   // TODO: implement the "local dynamic" model
2426   assert(Subtarget->isTargetELF() &&
2427          "TLS not implemented for non-ELF targets");
2428   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2429
2430   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2431
2432   switch (model) {
2433     case TLSModel::GeneralDynamic:
2434     case TLSModel::LocalDynamic:
2435       return LowerToTLSGeneralDynamicModel(GA, DAG);
2436     case TLSModel::InitialExec:
2437     case TLSModel::LocalExec:
2438       return LowerToTLSExecModels(GA, DAG, model);
2439   }
2440   llvm_unreachable("bogus TLS model");
2441 }
2442
2443 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2444                                                  SelectionDAG &DAG) const {
2445   EVT PtrVT = getPointerTy();
2446   SDLoc dl(Op);
2447   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2448   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2449     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2450     ARMConstantPoolValue *CPV =
2451       ARMConstantPoolConstant::Create(GV,
2452                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2453     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2454     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2455     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2456                                  CPAddr,
2457                                  MachinePointerInfo::getConstantPool(),
2458                                  false, false, false, 0);
2459     SDValue Chain = Result.getValue(1);
2460     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2461     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2462     if (!UseGOTOFF)
2463       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2464                            MachinePointerInfo::getGOT(),
2465                            false, false, false, 0);
2466     return Result;
2467   }
2468
2469   // If we have T2 ops, we can materialize the address directly via movt/movw
2470   // pair. This is always cheaper.
2471   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2472     ++NumMovwMovt;
2473     // FIXME: Once remat is capable of dealing with instructions with register
2474     // operands, expand this into two nodes.
2475     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2476                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2477   } else {
2478     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2479     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2480     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2481                        MachinePointerInfo::getConstantPool(),
2482                        false, false, false, 0);
2483   }
2484 }
2485
2486 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2487                                                     SelectionDAG &DAG) const {
2488   EVT PtrVT = getPointerTy();
2489   SDLoc dl(Op);
2490   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2491   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2492
2493   if (Subtarget->useMovt(DAG.getMachineFunction()))
2494     ++NumMovwMovt;
2495
2496   // FIXME: Once remat is capable of dealing with instructions with register
2497   // operands, expand this into multiple nodes
2498   unsigned Wrapper =
2499       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2500
2501   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2502   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2503
2504   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2505     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2506                          MachinePointerInfo::getGOT(), false, false, false, 0);
2507   return Result;
2508 }
2509
2510 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2511                                                      SelectionDAG &DAG) const {
2512   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2513   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2514          "Windows on ARM expects to use movw/movt");
2515
2516   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2517   const ARMII::TOF TargetFlags =
2518     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2519   EVT PtrVT = getPointerTy();
2520   SDValue Result;
2521   SDLoc DL(Op);
2522
2523   ++NumMovwMovt;
2524
2525   // FIXME: Once remat is capable of dealing with instructions with register
2526   // operands, expand this into two nodes.
2527   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2528                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2529                                                   TargetFlags));
2530   if (GV->hasDLLImportStorageClass())
2531     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2532                          MachinePointerInfo::getGOT(), false, false, false, 0);
2533   return Result;
2534 }
2535
2536 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2537                                                     SelectionDAG &DAG) const {
2538   assert(Subtarget->isTargetELF() &&
2539          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2540   MachineFunction &MF = DAG.getMachineFunction();
2541   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2542   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2543   EVT PtrVT = getPointerTy();
2544   SDLoc dl(Op);
2545   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2546   ARMConstantPoolValue *CPV =
2547     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2548                                   ARMPCLabelIndex, PCAdj);
2549   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2550   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2551   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2552                                MachinePointerInfo::getConstantPool(),
2553                                false, false, false, 0);
2554   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2555   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2556 }
2557
2558 SDValue
2559 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2560   SDLoc dl(Op);
2561   SDValue Val = DAG.getConstant(0, MVT::i32);
2562   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2563                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2564                      Op.getOperand(1), Val);
2565 }
2566
2567 SDValue
2568 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2569   SDLoc dl(Op);
2570   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2571                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2572 }
2573
2574 SDValue
2575 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2576                                           const ARMSubtarget *Subtarget) const {
2577   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2578   SDLoc dl(Op);
2579   switch (IntNo) {
2580   default: return SDValue();    // Don't custom lower most intrinsics.
2581   case Intrinsic::arm_rbit: {
2582     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2583            "RBIT intrinsic must have i32 type!");
2584     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2585   }
2586   case Intrinsic::arm_thread_pointer: {
2587     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2588     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2589   }
2590   case Intrinsic::eh_sjlj_lsda: {
2591     MachineFunction &MF = DAG.getMachineFunction();
2592     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2593     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2594     EVT PtrVT = getPointerTy();
2595     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2596     SDValue CPAddr;
2597     unsigned PCAdj = (RelocM != Reloc::PIC_)
2598       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2599     ARMConstantPoolValue *CPV =
2600       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2601                                       ARMCP::CPLSDA, PCAdj);
2602     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2603     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2604     SDValue Result =
2605       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2606                   MachinePointerInfo::getConstantPool(),
2607                   false, false, false, 0);
2608
2609     if (RelocM == Reloc::PIC_) {
2610       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2611       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2612     }
2613     return Result;
2614   }
2615   case Intrinsic::arm_neon_vmulls:
2616   case Intrinsic::arm_neon_vmullu: {
2617     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2618       ? ARMISD::VMULLs : ARMISD::VMULLu;
2619     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2620                        Op.getOperand(1), Op.getOperand(2));
2621   }
2622   }
2623 }
2624
2625 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2626                                  const ARMSubtarget *Subtarget) {
2627   // FIXME: handle "fence singlethread" more efficiently.
2628   SDLoc dl(Op);
2629   if (!Subtarget->hasDataBarrier()) {
2630     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2631     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2632     // here.
2633     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2634            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2635     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2636                        DAG.getConstant(0, MVT::i32));
2637   }
2638
2639   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2640   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2641   unsigned Domain = ARM_MB::ISH;
2642   if (Subtarget->isMClass()) {
2643     // Only a full system barrier exists in the M-class architectures.
2644     Domain = ARM_MB::SY;
2645   } else if (Subtarget->isSwift() && Ord == Release) {
2646     // Swift happens to implement ISHST barriers in a way that's compatible with
2647     // Release semantics but weaker than ISH so we'd be fools not to use
2648     // it. Beware: other processors probably don't!
2649     Domain = ARM_MB::ISHST;
2650   }
2651
2652   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2653                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2654                      DAG.getConstant(Domain, MVT::i32));
2655 }
2656
2657 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2658                              const ARMSubtarget *Subtarget) {
2659   // ARM pre v5TE and Thumb1 does not have preload instructions.
2660   if (!(Subtarget->isThumb2() ||
2661         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2662     // Just preserve the chain.
2663     return Op.getOperand(0);
2664
2665   SDLoc dl(Op);
2666   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2667   if (!isRead &&
2668       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2669     // ARMv7 with MP extension has PLDW.
2670     return Op.getOperand(0);
2671
2672   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2673   if (Subtarget->isThumb()) {
2674     // Invert the bits.
2675     isRead = ~isRead & 1;
2676     isData = ~isData & 1;
2677   }
2678
2679   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2680                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2681                      DAG.getConstant(isData, MVT::i32));
2682 }
2683
2684 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2685   MachineFunction &MF = DAG.getMachineFunction();
2686   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2687
2688   // vastart just stores the address of the VarArgsFrameIndex slot into the
2689   // memory location argument.
2690   SDLoc dl(Op);
2691   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2692   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2693   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2694   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2695                       MachinePointerInfo(SV), false, false, 0);
2696 }
2697
2698 SDValue
2699 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2700                                         SDValue &Root, SelectionDAG &DAG,
2701                                         SDLoc dl) const {
2702   MachineFunction &MF = DAG.getMachineFunction();
2703   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2704
2705   const TargetRegisterClass *RC;
2706   if (AFI->isThumb1OnlyFunction())
2707     RC = &ARM::tGPRRegClass;
2708   else
2709     RC = &ARM::GPRRegClass;
2710
2711   // Transform the arguments stored in physical registers into virtual ones.
2712   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2713   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2714
2715   SDValue ArgValue2;
2716   if (NextVA.isMemLoc()) {
2717     MachineFrameInfo *MFI = MF.getFrameInfo();
2718     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2719
2720     // Create load node to retrieve arguments from the stack.
2721     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2722     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2723                             MachinePointerInfo::getFixedStack(FI),
2724                             false, false, false, 0);
2725   } else {
2726     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2727     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2728   }
2729   if (!Subtarget->isLittle())
2730     std::swap (ArgValue, ArgValue2);
2731   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2732 }
2733
2734 void
2735 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2736                                   unsigned InRegsParamRecordIdx,
2737                                   unsigned ArgSize,
2738                                   unsigned &ArgRegsSize,
2739                                   unsigned &ArgRegsSaveSize)
2740   const {
2741   unsigned NumGPRs;
2742   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2743     unsigned RBegin, REnd;
2744     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2745     NumGPRs = REnd - RBegin;
2746   } else {
2747     unsigned int firstUnalloced;
2748     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2749                                                 sizeof(GPRArgRegs) /
2750                                                 sizeof(GPRArgRegs[0]));
2751     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2752   }
2753
2754   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2755   ArgRegsSize = NumGPRs * 4;
2756
2757   // If parameter is split between stack and GPRs...
2758   if (NumGPRs && Align > 4 &&
2759       (ArgRegsSize < ArgSize ||
2760         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2761     // Add padding for part of param recovered from GPRs.  For example,
2762     // if Align == 8, its last byte must be at address K*8 - 1.
2763     // We need to do it, since remained (stack) part of parameter has
2764     // stack alignment, and we need to "attach" "GPRs head" without gaps
2765     // to it:
2766     // Stack:
2767     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2768     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2769     //
2770     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2771     unsigned Padding =
2772         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2773     ArgRegsSaveSize = ArgRegsSize + Padding;
2774   } else
2775     // We don't need to extend regs save size for byval parameters if they
2776     // are passed via GPRs only.
2777     ArgRegsSaveSize = ArgRegsSize;
2778 }
2779
2780 // The remaining GPRs hold either the beginning of variable-argument
2781 // data, or the beginning of an aggregate passed by value (usually
2782 // byval).  Either way, we allocate stack slots adjacent to the data
2783 // provided by our caller, and store the unallocated registers there.
2784 // If this is a variadic function, the va_list pointer will begin with
2785 // these values; otherwise, this reassembles a (byval) structure that
2786 // was split between registers and memory.
2787 // Return: The frame index registers were stored into.
2788 int
2789 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2790                                   SDLoc dl, SDValue &Chain,
2791                                   const Value *OrigArg,
2792                                   unsigned InRegsParamRecordIdx,
2793                                   unsigned OffsetFromOrigArg,
2794                                   unsigned ArgOffset,
2795                                   unsigned ArgSize,
2796                                   bool ForceMutable,
2797                                   unsigned ByValStoreOffset,
2798                                   unsigned TotalArgRegsSaveSize) const {
2799
2800   // Currently, two use-cases possible:
2801   // Case #1. Non-var-args function, and we meet first byval parameter.
2802   //          Setup first unallocated register as first byval register;
2803   //          eat all remained registers
2804   //          (these two actions are performed by HandleByVal method).
2805   //          Then, here, we initialize stack frame with
2806   //          "store-reg" instructions.
2807   // Case #2. Var-args function, that doesn't contain byval parameters.
2808   //          The same: eat all remained unallocated registers,
2809   //          initialize stack frame.
2810
2811   MachineFunction &MF = DAG.getMachineFunction();
2812   MachineFrameInfo *MFI = MF.getFrameInfo();
2813   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2814   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2815   unsigned RBegin, REnd;
2816   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2817     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2818     firstRegToSaveIndex = RBegin - ARM::R0;
2819     lastRegToSaveIndex = REnd - ARM::R0;
2820   } else {
2821     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2822       (GPRArgRegs, array_lengthof(GPRArgRegs));
2823     lastRegToSaveIndex = 4;
2824   }
2825
2826   unsigned ArgRegsSize, ArgRegsSaveSize;
2827   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2828                  ArgRegsSize, ArgRegsSaveSize);
2829
2830   // Store any by-val regs to their spots on the stack so that they may be
2831   // loaded by deferencing the result of formal parameter pointer or va_next.
2832   // Note: once stack area for byval/varargs registers
2833   // was initialized, it can't be initialized again.
2834   if (ArgRegsSaveSize) {
2835     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2836
2837     if (Padding) {
2838       assert(AFI->getStoredByValParamsPadding() == 0 &&
2839              "The only parameter may be padded.");
2840       AFI->setStoredByValParamsPadding(Padding);
2841     }
2842
2843     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2844                                             Padding +
2845                                               ByValStoreOffset -
2846                                               (int64_t)TotalArgRegsSaveSize,
2847                                             false);
2848     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2849     if (Padding) {
2850        MFI->CreateFixedObject(Padding,
2851                               ArgOffset + ByValStoreOffset -
2852                                 (int64_t)ArgRegsSaveSize,
2853                               false);
2854     }
2855
2856     SmallVector<SDValue, 4> MemOps;
2857     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2858          ++firstRegToSaveIndex, ++i) {
2859       const TargetRegisterClass *RC;
2860       if (AFI->isThumb1OnlyFunction())
2861         RC = &ARM::tGPRRegClass;
2862       else
2863         RC = &ARM::GPRRegClass;
2864
2865       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2866       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2867       SDValue Store =
2868         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2869                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2870                      false, false, 0);
2871       MemOps.push_back(Store);
2872       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2873                         DAG.getConstant(4, getPointerTy()));
2874     }
2875
2876     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2877
2878     if (!MemOps.empty())
2879       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2880     return FrameIndex;
2881   } else {
2882     if (ArgSize == 0) {
2883       // We cannot allocate a zero-byte object for the first variadic argument,
2884       // so just make up a size.
2885       ArgSize = 4;
2886     }
2887     // This will point to the next argument passed via stack.
2888     return MFI->CreateFixedObject(
2889       ArgSize, ArgOffset, !ForceMutable);
2890   }
2891 }
2892
2893 // Setup stack frame, the va_list pointer will start from.
2894 void
2895 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2896                                         SDLoc dl, SDValue &Chain,
2897                                         unsigned ArgOffset,
2898                                         unsigned TotalArgRegsSaveSize,
2899                                         bool ForceMutable) const {
2900   MachineFunction &MF = DAG.getMachineFunction();
2901   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2902
2903   // Try to store any remaining integer argument regs
2904   // to their spots on the stack so that they may be loaded by deferencing
2905   // the result of va_next.
2906   // If there is no regs to be stored, just point address after last
2907   // argument passed via stack.
2908   int FrameIndex =
2909     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2910                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2911                    0, TotalArgRegsSaveSize);
2912
2913   AFI->setVarArgsFrameIndex(FrameIndex);
2914 }
2915
2916 SDValue
2917 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2918                                         CallingConv::ID CallConv, bool isVarArg,
2919                                         const SmallVectorImpl<ISD::InputArg>
2920                                           &Ins,
2921                                         SDLoc dl, SelectionDAG &DAG,
2922                                         SmallVectorImpl<SDValue> &InVals)
2923                                           const {
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   MachineFrameInfo *MFI = MF.getFrameInfo();
2926
2927   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2928
2929   // Assign locations to all of the incoming arguments.
2930   SmallVector<CCValAssign, 16> ArgLocs;
2931   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2932                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2933   CCInfo.AnalyzeFormalArguments(Ins,
2934                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2935                                                   isVarArg));
2936
2937   SmallVector<SDValue, 16> ArgValues;
2938   int lastInsIndex = -1;
2939   SDValue ArgValue;
2940   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2941   unsigned CurArgIdx = 0;
2942
2943   // Initially ArgRegsSaveSize is zero.
2944   // Then we increase this value each time we meet byval parameter.
2945   // We also increase this value in case of varargs function.
2946   AFI->setArgRegsSaveSize(0);
2947
2948   unsigned ByValStoreOffset = 0;
2949   unsigned TotalArgRegsSaveSize = 0;
2950   unsigned ArgRegsSaveSizeMaxAlign = 4;
2951
2952   // Calculate the amount of stack space that we need to allocate to store
2953   // byval and variadic arguments that are passed in registers.
2954   // We need to know this before we allocate the first byval or variadic
2955   // argument, as they will be allocated a stack slot below the CFA (Canonical
2956   // Frame Address, the stack pointer at entry to the function).
2957   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2958     CCValAssign &VA = ArgLocs[i];
2959     if (VA.isMemLoc()) {
2960       int index = VA.getValNo();
2961       if (index != lastInsIndex) {
2962         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2963         if (Flags.isByVal()) {
2964           unsigned ExtraArgRegsSize;
2965           unsigned ExtraArgRegsSaveSize;
2966           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2967                          Flags.getByValSize(),
2968                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2969
2970           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2971           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2972               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2973           CCInfo.nextInRegsParam();
2974         }
2975         lastInsIndex = index;
2976       }
2977     }
2978   }
2979   CCInfo.rewindByValRegsInfo();
2980   lastInsIndex = -1;
2981   if (isVarArg) {
2982     unsigned ExtraArgRegsSize;
2983     unsigned ExtraArgRegsSaveSize;
2984     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2985                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2986     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2987   }
2988   // If the arg regs save area contains N-byte aligned values, the
2989   // bottom of it must be at least N-byte aligned.
2990   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2991   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2992
2993   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2994     CCValAssign &VA = ArgLocs[i];
2995     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2996     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2997     // Arguments stored in registers.
2998     if (VA.isRegLoc()) {
2999       EVT RegVT = VA.getLocVT();
3000
3001       if (VA.needsCustom()) {
3002         // f64 and vector types are split up into multiple registers or
3003         // combinations of registers and stack slots.
3004         if (VA.getLocVT() == MVT::v2f64) {
3005           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3006                                                    Chain, DAG, dl);
3007           VA = ArgLocs[++i]; // skip ahead to next loc
3008           SDValue ArgValue2;
3009           if (VA.isMemLoc()) {
3010             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3011             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3012             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3013                                     MachinePointerInfo::getFixedStack(FI),
3014                                     false, false, false, 0);
3015           } else {
3016             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3017                                              Chain, DAG, dl);
3018           }
3019           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3020           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3021                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
3022           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3023                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
3024         } else
3025           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3026
3027       } else {
3028         const TargetRegisterClass *RC;
3029
3030         if (RegVT == MVT::f32)
3031           RC = &ARM::SPRRegClass;
3032         else if (RegVT == MVT::f64)
3033           RC = &ARM::DPRRegClass;
3034         else if (RegVT == MVT::v2f64)
3035           RC = &ARM::QPRRegClass;
3036         else if (RegVT == MVT::i32)
3037           RC = AFI->isThumb1OnlyFunction() ?
3038             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3039             (const TargetRegisterClass*)&ARM::GPRRegClass;
3040         else
3041           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3042
3043         // Transform the arguments in physical registers into virtual ones.
3044         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3045         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3046       }
3047
3048       // If this is an 8 or 16-bit value, it is really passed promoted
3049       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3050       // truncate to the right size.
3051       switch (VA.getLocInfo()) {
3052       default: llvm_unreachable("Unknown loc info!");
3053       case CCValAssign::Full: break;
3054       case CCValAssign::BCvt:
3055         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3056         break;
3057       case CCValAssign::SExt:
3058         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3059                                DAG.getValueType(VA.getValVT()));
3060         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3061         break;
3062       case CCValAssign::ZExt:
3063         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3064                                DAG.getValueType(VA.getValVT()));
3065         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3066         break;
3067       }
3068
3069       InVals.push_back(ArgValue);
3070
3071     } else { // VA.isRegLoc()
3072
3073       // sanity check
3074       assert(VA.isMemLoc());
3075       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3076
3077       int index = ArgLocs[i].getValNo();
3078
3079       // Some Ins[] entries become multiple ArgLoc[] entries.
3080       // Process them only once.
3081       if (index != lastInsIndex)
3082         {
3083           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3084           // FIXME: For now, all byval parameter objects are marked mutable.
3085           // This can be changed with more analysis.
3086           // In case of tail call optimization mark all arguments mutable.
3087           // Since they could be overwritten by lowering of arguments in case of
3088           // a tail call.
3089           if (Flags.isByVal()) {
3090             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3091
3092             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3093             int FrameIndex = StoreByValRegs(
3094                 CCInfo, DAG, dl, Chain, CurOrigArg,
3095                 CurByValIndex,
3096                 Ins[VA.getValNo()].PartOffset,
3097                 VA.getLocMemOffset(),
3098                 Flags.getByValSize(),
3099                 true /*force mutable frames*/,
3100                 ByValStoreOffset,
3101                 TotalArgRegsSaveSize);
3102             ByValStoreOffset += Flags.getByValSize();
3103             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3104             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3105             CCInfo.nextInRegsParam();
3106           } else {
3107             unsigned FIOffset = VA.getLocMemOffset();
3108             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3109                                             FIOffset, true);
3110
3111             // Create load nodes to retrieve arguments from the stack.
3112             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3113             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3114                                          MachinePointerInfo::getFixedStack(FI),
3115                                          false, false, false, 0));
3116           }
3117           lastInsIndex = index;
3118         }
3119     }
3120   }
3121
3122   // varargs
3123   if (isVarArg)
3124     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3125                          CCInfo.getNextStackOffset(),
3126                          TotalArgRegsSaveSize);
3127
3128   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3129
3130   return Chain;
3131 }
3132
3133 /// isFloatingPointZero - Return true if this is +0.0.
3134 static bool isFloatingPointZero(SDValue Op) {
3135   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3136     return CFP->getValueAPF().isPosZero();
3137   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3138     // Maybe this has already been legalized into the constant pool?
3139     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3140       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3141       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3142         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3143           return CFP->getValueAPF().isPosZero();
3144     }
3145   }
3146   return false;
3147 }
3148
3149 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3150 /// the given operands.
3151 SDValue
3152 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3153                              SDValue &ARMcc, SelectionDAG &DAG,
3154                              SDLoc dl) const {
3155   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3156     unsigned C = RHSC->getZExtValue();
3157     if (!isLegalICmpImmediate(C)) {
3158       // Constant does not fit, try adjusting it by one?
3159       switch (CC) {
3160       default: break;
3161       case ISD::SETLT:
3162       case ISD::SETGE:
3163         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3164           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3165           RHS = DAG.getConstant(C-1, MVT::i32);
3166         }
3167         break;
3168       case ISD::SETULT:
3169       case ISD::SETUGE:
3170         if (C != 0 && isLegalICmpImmediate(C-1)) {
3171           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3172           RHS = DAG.getConstant(C-1, MVT::i32);
3173         }
3174         break;
3175       case ISD::SETLE:
3176       case ISD::SETGT:
3177         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3178           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3179           RHS = DAG.getConstant(C+1, MVT::i32);
3180         }
3181         break;
3182       case ISD::SETULE:
3183       case ISD::SETUGT:
3184         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3185           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3186           RHS = DAG.getConstant(C+1, MVT::i32);
3187         }
3188         break;
3189       }
3190     }
3191   }
3192
3193   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3194   ARMISD::NodeType CompareType;
3195   switch (CondCode) {
3196   default:
3197     CompareType = ARMISD::CMP;
3198     break;
3199   case ARMCC::EQ:
3200   case ARMCC::NE:
3201     // Uses only Z Flag
3202     CompareType = ARMISD::CMPZ;
3203     break;
3204   }
3205   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3206   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3207 }
3208
3209 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3210 SDValue
3211 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3212                              SDLoc dl) const {
3213   SDValue Cmp;
3214   if (!isFloatingPointZero(RHS))
3215     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3216   else
3217     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3218   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3219 }
3220
3221 /// duplicateCmp - Glue values can have only one use, so this function
3222 /// duplicates a comparison node.
3223 SDValue
3224 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3225   unsigned Opc = Cmp.getOpcode();
3226   SDLoc DL(Cmp);
3227   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3228     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3229
3230   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3231   Cmp = Cmp.getOperand(0);
3232   Opc = Cmp.getOpcode();
3233   if (Opc == ARMISD::CMPFP)
3234     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3235   else {
3236     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3237     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3238   }
3239   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3240 }
3241
3242 std::pair<SDValue, SDValue>
3243 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3244                                  SDValue &ARMcc) const {
3245   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3246
3247   SDValue Value, OverflowCmp;
3248   SDValue LHS = Op.getOperand(0);
3249   SDValue RHS = Op.getOperand(1);
3250
3251
3252   // FIXME: We are currently always generating CMPs because we don't support
3253   // generating CMN through the backend. This is not as good as the natural
3254   // CMP case because it causes a register dependency and cannot be folded
3255   // later.
3256
3257   switch (Op.getOpcode()) {
3258   default:
3259     llvm_unreachable("Unknown overflow instruction!");
3260   case ISD::SADDO:
3261     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3262     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3263     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3264     break;
3265   case ISD::UADDO:
3266     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3267     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3268     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3269     break;
3270   case ISD::SSUBO:
3271     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3272     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3273     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3274     break;
3275   case ISD::USUBO:
3276     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3277     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3278     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3279     break;
3280   } // switch (...)
3281
3282   return std::make_pair(Value, OverflowCmp);
3283 }
3284
3285
3286 SDValue
3287 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3288   // Let legalize expand this if it isn't a legal type yet.
3289   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3290     return SDValue();
3291
3292   SDValue Value, OverflowCmp;
3293   SDValue ARMcc;
3294   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3295   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3296   // We use 0 and 1 as false and true values.
3297   SDValue TVal = DAG.getConstant(1, MVT::i32);
3298   SDValue FVal = DAG.getConstant(0, MVT::i32);
3299   EVT VT = Op.getValueType();
3300
3301   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3302                                  ARMcc, CCR, OverflowCmp);
3303
3304   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3305   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3306 }
3307
3308
3309 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3310   SDValue Cond = Op.getOperand(0);
3311   SDValue SelectTrue = Op.getOperand(1);
3312   SDValue SelectFalse = Op.getOperand(2);
3313   SDLoc dl(Op);
3314   unsigned Opc = Cond.getOpcode();
3315
3316   if (Cond.getResNo() == 1 &&
3317       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3318        Opc == ISD::USUBO)) {
3319     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3320       return SDValue();
3321
3322     SDValue Value, OverflowCmp;
3323     SDValue ARMcc;
3324     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3325     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3326     EVT VT = Op.getValueType();
3327
3328     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3329                        ARMcc, CCR, OverflowCmp);
3330
3331   }
3332
3333   // Convert:
3334   //
3335   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3336   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3337   //
3338   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3339     const ConstantSDNode *CMOVTrue =
3340       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3341     const ConstantSDNode *CMOVFalse =
3342       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3343
3344     if (CMOVTrue && CMOVFalse) {
3345       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3346       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3347
3348       SDValue True;
3349       SDValue False;
3350       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3351         True = SelectTrue;
3352         False = SelectFalse;
3353       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3354         True = SelectFalse;
3355         False = SelectTrue;
3356       }
3357
3358       if (True.getNode() && False.getNode()) {
3359         EVT VT = Op.getValueType();
3360         SDValue ARMcc = Cond.getOperand(2);
3361         SDValue CCR = Cond.getOperand(3);
3362         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3363         assert(True.getValueType() == VT);
3364         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3365       }
3366     }
3367   }
3368
3369   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3370   // undefined bits before doing a full-word comparison with zero.
3371   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3372                      DAG.getConstant(1, Cond.getValueType()));
3373
3374   return DAG.getSelectCC(dl, Cond,
3375                          DAG.getConstant(0, Cond.getValueType()),
3376                          SelectTrue, SelectFalse, ISD::SETNE);
3377 }
3378
3379 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3380   if (CC == ISD::SETNE)
3381     return ISD::SETEQ;
3382   return ISD::getSetCCInverse(CC, true);
3383 }
3384
3385 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3386                                  bool &swpCmpOps, bool &swpVselOps) {
3387   // Start by selecting the GE condition code for opcodes that return true for
3388   // 'equality'
3389   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3390       CC == ISD::SETULE)
3391     CondCode = ARMCC::GE;
3392
3393   // and GT for opcodes that return false for 'equality'.
3394   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3395            CC == ISD::SETULT)
3396     CondCode = ARMCC::GT;
3397
3398   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3399   // to swap the compare operands.
3400   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3401       CC == ISD::SETULT)
3402     swpCmpOps = true;
3403
3404   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3405   // If we have an unordered opcode, we need to swap the operands to the VSEL
3406   // instruction (effectively negating the condition).
3407   //
3408   // This also has the effect of swapping which one of 'less' or 'greater'
3409   // returns true, so we also swap the compare operands. It also switches
3410   // whether we return true for 'equality', so we compensate by picking the
3411   // opposite condition code to our original choice.
3412   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3413       CC == ISD::SETUGT) {
3414     swpCmpOps = !swpCmpOps;
3415     swpVselOps = !swpVselOps;
3416     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3417   }
3418
3419   // 'ordered' is 'anything but unordered', so use the VS condition code and
3420   // swap the VSEL operands.
3421   if (CC == ISD::SETO) {
3422     CondCode = ARMCC::VS;
3423     swpVselOps = true;
3424   }
3425
3426   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3427   // code and swap the VSEL operands.
3428   if (CC == ISD::SETUNE) {
3429     CondCode = ARMCC::EQ;
3430     swpVselOps = true;
3431   }
3432 }
3433
3434 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3435   EVT VT = Op.getValueType();
3436   SDValue LHS = Op.getOperand(0);
3437   SDValue RHS = Op.getOperand(1);
3438   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3439   SDValue TrueVal = Op.getOperand(2);
3440   SDValue FalseVal = Op.getOperand(3);
3441   SDLoc dl(Op);
3442
3443   if (LHS.getValueType() == MVT::i32) {
3444     // Try to generate VSEL on ARMv8.
3445     // The VSEL instruction can't use all the usual ARM condition
3446     // codes: it only has two bits to select the condition code, so it's
3447     // constrained to use only GE, GT, VS and EQ.
3448     //
3449     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3450     // swap the operands of the previous compare instruction (effectively
3451     // inverting the compare condition, swapping 'less' and 'greater') and
3452     // sometimes need to swap the operands to the VSEL (which inverts the
3453     // condition in the sense of firing whenever the previous condition didn't)
3454     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3455                                       TrueVal.getValueType() == MVT::f64)) {
3456       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3457       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3458           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3459         CC = getInverseCCForVSEL(CC);
3460         std::swap(TrueVal, FalseVal);
3461       }
3462     }
3463
3464     SDValue ARMcc;
3465     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3466     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3467     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3468                        Cmp);
3469   }
3470
3471   ARMCC::CondCodes CondCode, CondCode2;
3472   FPCCToARMCC(CC, CondCode, CondCode2);
3473
3474   // Try to generate VSEL on ARMv8.
3475   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3476                                     TrueVal.getValueType() == MVT::f64)) {
3477     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3478     // same operands, as follows:
3479     //   c = fcmp [ogt, olt, ugt, ult] a, b
3480     //   select c, a, b
3481     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3482     // handled differently than the original code sequence.
3483     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3484         RHS == FalseVal) {
3485       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3486         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3487       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3488         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3489     }
3490
3491     bool swpCmpOps = false;
3492     bool swpVselOps = false;
3493     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3494
3495     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3496         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3497       if (swpCmpOps)
3498         std::swap(LHS, RHS);
3499       if (swpVselOps)
3500         std::swap(TrueVal, FalseVal);
3501     }
3502   }
3503
3504   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3505   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3506   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3507   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3508                                ARMcc, CCR, Cmp);
3509   if (CondCode2 != ARMCC::AL) {
3510     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3511     // FIXME: Needs another CMP because flag can have but one use.
3512     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3513     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3514                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3515   }
3516   return Result;
3517 }
3518
3519 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3520 /// to morph to an integer compare sequence.
3521 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3522                            const ARMSubtarget *Subtarget) {
3523   SDNode *N = Op.getNode();
3524   if (!N->hasOneUse())
3525     // Otherwise it requires moving the value from fp to integer registers.
3526     return false;
3527   if (!N->getNumValues())
3528     return false;
3529   EVT VT = Op.getValueType();
3530   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3531     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3532     // vmrs are very slow, e.g. cortex-a8.
3533     return false;
3534
3535   if (isFloatingPointZero(Op)) {
3536     SeenZero = true;
3537     return true;
3538   }
3539   return ISD::isNormalLoad(N);
3540 }
3541
3542 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3543   if (isFloatingPointZero(Op))
3544     return DAG.getConstant(0, MVT::i32);
3545
3546   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3547     return DAG.getLoad(MVT::i32, SDLoc(Op),
3548                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3549                        Ld->isVolatile(), Ld->isNonTemporal(),
3550                        Ld->isInvariant(), Ld->getAlignment());
3551
3552   llvm_unreachable("Unknown VFP cmp argument!");
3553 }
3554
3555 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3556                            SDValue &RetVal1, SDValue &RetVal2) {
3557   if (isFloatingPointZero(Op)) {
3558     RetVal1 = DAG.getConstant(0, MVT::i32);
3559     RetVal2 = DAG.getConstant(0, MVT::i32);
3560     return;
3561   }
3562
3563   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3564     SDValue Ptr = Ld->getBasePtr();
3565     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3566                           Ld->getChain(), Ptr,
3567                           Ld->getPointerInfo(),
3568                           Ld->isVolatile(), Ld->isNonTemporal(),
3569                           Ld->isInvariant(), Ld->getAlignment());
3570
3571     EVT PtrType = Ptr.getValueType();
3572     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3573     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3574                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3575     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3576                           Ld->getChain(), NewPtr,
3577                           Ld->getPointerInfo().getWithOffset(4),
3578                           Ld->isVolatile(), Ld->isNonTemporal(),
3579                           Ld->isInvariant(), NewAlign);
3580     return;
3581   }
3582
3583   llvm_unreachable("Unknown VFP cmp argument!");
3584 }
3585
3586 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3587 /// f32 and even f64 comparisons to integer ones.
3588 SDValue
3589 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3590   SDValue Chain = Op.getOperand(0);
3591   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3592   SDValue LHS = Op.getOperand(2);
3593   SDValue RHS = Op.getOperand(3);
3594   SDValue Dest = Op.getOperand(4);
3595   SDLoc dl(Op);
3596
3597   bool LHSSeenZero = false;
3598   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3599   bool RHSSeenZero = false;
3600   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3601   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3602     // If unsafe fp math optimization is enabled and there are no other uses of
3603     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3604     // to an integer comparison.
3605     if (CC == ISD::SETOEQ)
3606       CC = ISD::SETEQ;
3607     else if (CC == ISD::SETUNE)
3608       CC = ISD::SETNE;
3609
3610     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3611     SDValue ARMcc;
3612     if (LHS.getValueType() == MVT::f32) {
3613       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3614                         bitcastf32Toi32(LHS, DAG), Mask);
3615       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3616                         bitcastf32Toi32(RHS, DAG), Mask);
3617       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3618       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3619       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3620                          Chain, Dest, ARMcc, CCR, Cmp);
3621     }
3622
3623     SDValue LHS1, LHS2;
3624     SDValue RHS1, RHS2;
3625     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3626     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3627     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3628     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3629     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3630     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3631     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3632     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3633     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3634   }
3635
3636   return SDValue();
3637 }
3638
3639 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3640   SDValue Chain = Op.getOperand(0);
3641   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3642   SDValue LHS = Op.getOperand(2);
3643   SDValue RHS = Op.getOperand(3);
3644   SDValue Dest = Op.getOperand(4);
3645   SDLoc dl(Op);
3646
3647   if (LHS.getValueType() == MVT::i32) {
3648     SDValue ARMcc;
3649     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3650     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3651     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3652                        Chain, Dest, ARMcc, CCR, Cmp);
3653   }
3654
3655   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3656
3657   if (getTargetMachine().Options.UnsafeFPMath &&
3658       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3659        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3660     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3661     if (Result.getNode())
3662       return Result;
3663   }
3664
3665   ARMCC::CondCodes CondCode, CondCode2;
3666   FPCCToARMCC(CC, CondCode, CondCode2);
3667
3668   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3669   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3670   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3671   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3672   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3673   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3674   if (CondCode2 != ARMCC::AL) {
3675     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3676     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3677     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3678   }
3679   return Res;
3680 }
3681
3682 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3683   SDValue Chain = Op.getOperand(0);
3684   SDValue Table = Op.getOperand(1);
3685   SDValue Index = Op.getOperand(2);
3686   SDLoc dl(Op);
3687
3688   EVT PTy = getPointerTy();
3689   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3690   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3691   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3692   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3693   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3694   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3695   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3696   if (Subtarget->isThumb2()) {
3697     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3698     // which does another jump to the destination. This also makes it easier
3699     // to translate it to TBB / TBH later.
3700     // FIXME: This might not work if the function is extremely large.
3701     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3702                        Addr, Op.getOperand(2), JTI, UId);
3703   }
3704   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3705     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3706                        MachinePointerInfo::getJumpTable(),
3707                        false, false, false, 0);
3708     Chain = Addr.getValue(1);
3709     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3710     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3711   } else {
3712     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3713                        MachinePointerInfo::getJumpTable(),
3714                        false, false, false, 0);
3715     Chain = Addr.getValue(1);
3716     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3717   }
3718 }
3719
3720 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3721   EVT VT = Op.getValueType();
3722   SDLoc dl(Op);
3723
3724   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3725     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3726       return Op;
3727     return DAG.UnrollVectorOp(Op.getNode());
3728   }
3729
3730   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3731          "Invalid type for custom lowering!");
3732   if (VT != MVT::v4i16)
3733     return DAG.UnrollVectorOp(Op.getNode());
3734
3735   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3736   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3737 }
3738
3739 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3740   EVT VT = Op.getValueType();
3741   if (VT.isVector())
3742     return LowerVectorFP_TO_INT(Op, DAG);
3743
3744   SDLoc dl(Op);
3745   unsigned Opc;
3746
3747   switch (Op.getOpcode()) {
3748   default: llvm_unreachable("Invalid opcode!");
3749   case ISD::FP_TO_SINT:
3750     Opc = ARMISD::FTOSI;
3751     break;
3752   case ISD::FP_TO_UINT:
3753     Opc = ARMISD::FTOUI;
3754     break;
3755   }
3756   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3757   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3758 }
3759
3760 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3761   EVT VT = Op.getValueType();
3762   SDLoc dl(Op);
3763
3764   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3765     if (VT.getVectorElementType() == MVT::f32)
3766       return Op;
3767     return DAG.UnrollVectorOp(Op.getNode());
3768   }
3769
3770   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3771          "Invalid type for custom lowering!");
3772   if (VT != MVT::v4f32)
3773     return DAG.UnrollVectorOp(Op.getNode());
3774
3775   unsigned CastOpc;
3776   unsigned Opc;
3777   switch (Op.getOpcode()) {
3778   default: llvm_unreachable("Invalid opcode!");
3779   case ISD::SINT_TO_FP:
3780     CastOpc = ISD::SIGN_EXTEND;
3781     Opc = ISD::SINT_TO_FP;
3782     break;
3783   case ISD::UINT_TO_FP:
3784     CastOpc = ISD::ZERO_EXTEND;
3785     Opc = ISD::UINT_TO_FP;
3786     break;
3787   }
3788
3789   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3790   return DAG.getNode(Opc, dl, VT, Op);
3791 }
3792
3793 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3794   EVT VT = Op.getValueType();
3795   if (VT.isVector())
3796     return LowerVectorINT_TO_FP(Op, DAG);
3797
3798   SDLoc dl(Op);
3799   unsigned Opc;
3800
3801   switch (Op.getOpcode()) {
3802   default: llvm_unreachable("Invalid opcode!");
3803   case ISD::SINT_TO_FP:
3804     Opc = ARMISD::SITOF;
3805     break;
3806   case ISD::UINT_TO_FP:
3807     Opc = ARMISD::UITOF;
3808     break;
3809   }
3810
3811   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3812   return DAG.getNode(Opc, dl, VT, Op);
3813 }
3814
3815 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3816   // Implement fcopysign with a fabs and a conditional fneg.
3817   SDValue Tmp0 = Op.getOperand(0);
3818   SDValue Tmp1 = Op.getOperand(1);
3819   SDLoc dl(Op);
3820   EVT VT = Op.getValueType();
3821   EVT SrcVT = Tmp1.getValueType();
3822   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3823     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3824   bool UseNEON = !InGPR && Subtarget->hasNEON();
3825
3826   if (UseNEON) {
3827     // Use VBSL to copy the sign bit.
3828     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3829     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3830                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3831     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3832     if (VT == MVT::f64)
3833       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3834                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3835                          DAG.getConstant(32, MVT::i32));
3836     else /*if (VT == MVT::f32)*/
3837       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3838     if (SrcVT == MVT::f32) {
3839       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3840       if (VT == MVT::f64)
3841         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3842                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3843                            DAG.getConstant(32, MVT::i32));
3844     } else if (VT == MVT::f32)
3845       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3846                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3847                          DAG.getConstant(32, MVT::i32));
3848     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3849     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3850
3851     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3852                                             MVT::i32);
3853     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3854     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3855                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3856
3857     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3858                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3859                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3860     if (VT == MVT::f32) {
3861       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3862       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3863                         DAG.getConstant(0, MVT::i32));
3864     } else {
3865       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3866     }
3867
3868     return Res;
3869   }
3870
3871   // Bitcast operand 1 to i32.
3872   if (SrcVT == MVT::f64)
3873     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3874                        Tmp1).getValue(1);
3875   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3876
3877   // Or in the signbit with integer operations.
3878   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3879   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3880   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3881   if (VT == MVT::f32) {
3882     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3883                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3884     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3885                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3886   }
3887
3888   // f64: Or the high part with signbit and then combine two parts.
3889   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3890                      Tmp0);
3891   SDValue Lo = Tmp0.getValue(0);
3892   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3893   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3894   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3895 }
3896
3897 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3898   MachineFunction &MF = DAG.getMachineFunction();
3899   MachineFrameInfo *MFI = MF.getFrameInfo();
3900   MFI->setReturnAddressIsTaken(true);
3901
3902   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3903     return SDValue();
3904
3905   EVT VT = Op.getValueType();
3906   SDLoc dl(Op);
3907   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3908   if (Depth) {
3909     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3910     SDValue Offset = DAG.getConstant(4, MVT::i32);
3911     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3912                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3913                        MachinePointerInfo(), false, false, false, 0);
3914   }
3915
3916   // Return LR, which contains the return address. Mark it an implicit live-in.
3917   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3918   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3919 }
3920
3921 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3922   const ARMBaseRegisterInfo &ARI =
3923     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3924   MachineFunction &MF = DAG.getMachineFunction();
3925   MachineFrameInfo *MFI = MF.getFrameInfo();
3926   MFI->setFrameAddressIsTaken(true);
3927
3928   EVT VT = Op.getValueType();
3929   SDLoc dl(Op);  // FIXME probably not meaningful
3930   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3931   unsigned FrameReg = ARI.getFrameRegister(MF);
3932   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3933   while (Depth--)
3934     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3935                             MachinePointerInfo(),
3936                             false, false, false, 0);
3937   return FrameAddr;
3938 }
3939
3940 // FIXME? Maybe this could be a TableGen attribute on some registers and
3941 // this table could be generated automatically from RegInfo.
3942 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3943                                               EVT VT) const {
3944   unsigned Reg = StringSwitch<unsigned>(RegName)
3945                        .Case("sp", ARM::SP)
3946                        .Default(0);
3947   if (Reg)
3948     return Reg;
3949   report_fatal_error("Invalid register name global variable");
3950 }
3951
3952 /// ExpandBITCAST - If the target supports VFP, this function is called to
3953 /// expand a bit convert where either the source or destination type is i64 to
3954 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3955 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3956 /// vectors), since the legalizer won't know what to do with that.
3957 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3959   SDLoc dl(N);
3960   SDValue Op = N->getOperand(0);
3961
3962   // This function is only supposed to be called for i64 types, either as the
3963   // source or destination of the bit convert.
3964   EVT SrcVT = Op.getValueType();
3965   EVT DstVT = N->getValueType(0);
3966   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3967          "ExpandBITCAST called for non-i64 type");
3968
3969   // Turn i64->f64 into VMOVDRR.
3970   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3971     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3972                              DAG.getConstant(0, MVT::i32));
3973     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3974                              DAG.getConstant(1, MVT::i32));
3975     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3976                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3977   }
3978
3979   // Turn f64->i64 into VMOVRRD.
3980   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3981     SDValue Cvt;
3982     if (TLI.isBigEndian() && SrcVT.isVector() &&
3983         SrcVT.getVectorNumElements() > 1)
3984       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3985                         DAG.getVTList(MVT::i32, MVT::i32),
3986                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3987     else
3988       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3989                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3990     // Merge the pieces into a single i64 value.
3991     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3992   }
3993
3994   return SDValue();
3995 }
3996
3997 /// getZeroVector - Returns a vector of specified type with all zero elements.
3998 /// Zero vectors are used to represent vector negation and in those cases
3999 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4000 /// not support i64 elements, so sometimes the zero vectors will need to be
4001 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4002 /// zero vector.
4003 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4004   assert(VT.isVector() && "Expected a vector type");
4005   // The canonical modified immediate encoding of a zero vector is....0!
4006   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
4007   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4008   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4009   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4010 }
4011
4012 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4013 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4014 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4015                                                 SelectionDAG &DAG) const {
4016   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4017   EVT VT = Op.getValueType();
4018   unsigned VTBits = VT.getSizeInBits();
4019   SDLoc dl(Op);
4020   SDValue ShOpLo = Op.getOperand(0);
4021   SDValue ShOpHi = Op.getOperand(1);
4022   SDValue ShAmt  = Op.getOperand(2);
4023   SDValue ARMcc;
4024   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4025
4026   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4027
4028   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4029                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4030   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4031   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4032                                    DAG.getConstant(VTBits, MVT::i32));
4033   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4034   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4035   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4036
4037   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4038   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4039                           ARMcc, DAG, dl);
4040   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4041   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4042                            CCR, Cmp);
4043
4044   SDValue Ops[2] = { Lo, Hi };
4045   return DAG.getMergeValues(Ops, dl);
4046 }
4047
4048 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4049 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4050 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4051                                                SelectionDAG &DAG) const {
4052   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4053   EVT VT = Op.getValueType();
4054   unsigned VTBits = VT.getSizeInBits();
4055   SDLoc dl(Op);
4056   SDValue ShOpLo = Op.getOperand(0);
4057   SDValue ShOpHi = Op.getOperand(1);
4058   SDValue ShAmt  = Op.getOperand(2);
4059   SDValue ARMcc;
4060
4061   assert(Op.getOpcode() == ISD::SHL_PARTS);
4062   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4063                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4064   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4065   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4066                                    DAG.getConstant(VTBits, MVT::i32));
4067   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4068   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4069
4070   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4071   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4072   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4073                           ARMcc, DAG, dl);
4074   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4075   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4076                            CCR, Cmp);
4077
4078   SDValue Ops[2] = { Lo, Hi };
4079   return DAG.getMergeValues(Ops, dl);
4080 }
4081
4082 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4083                                             SelectionDAG &DAG) const {
4084   // The rounding mode is in bits 23:22 of the FPSCR.
4085   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4086   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4087   // so that the shift + and get folded into a bitfield extract.
4088   SDLoc dl(Op);
4089   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4090                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4091                                               MVT::i32));
4092   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4093                                   DAG.getConstant(1U << 22, MVT::i32));
4094   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4095                               DAG.getConstant(22, MVT::i32));
4096   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4097                      DAG.getConstant(3, MVT::i32));
4098 }
4099
4100 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4101                          const ARMSubtarget *ST) {
4102   EVT VT = N->getValueType(0);
4103   SDLoc dl(N);
4104
4105   if (!ST->hasV6T2Ops())
4106     return SDValue();
4107
4108   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4109   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4110 }
4111
4112 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4113 /// for each 16-bit element from operand, repeated.  The basic idea is to
4114 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4115 ///
4116 /// Trace for v4i16:
4117 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4118 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4119 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4120 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4121 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4122 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4123 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4124 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4125 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4126   EVT VT = N->getValueType(0);
4127   SDLoc DL(N);
4128
4129   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4130   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4131   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4132   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4133   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4134   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4135 }
4136
4137 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4138 /// bit-count for each 16-bit element from the operand.  We need slightly
4139 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4140 /// 64/128-bit registers.
4141 ///
4142 /// Trace for v4i16:
4143 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4144 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4145 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4146 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4147 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4148   EVT VT = N->getValueType(0);
4149   SDLoc DL(N);
4150
4151   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4152   if (VT.is64BitVector()) {
4153     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4154     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4155                        DAG.getIntPtrConstant(0));
4156   } else {
4157     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4158                                     BitCounts, DAG.getIntPtrConstant(0));
4159     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4160   }
4161 }
4162
4163 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4164 /// bit-count for each 32-bit element from the operand.  The idea here is
4165 /// to split the vector into 16-bit elements, leverage the 16-bit count
4166 /// routine, and then combine the results.
4167 ///
4168 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4169 /// input    = [v0    v1    ] (vi: 32-bit elements)
4170 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4171 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4172 /// vrev: N0 = [k1 k0 k3 k2 ]
4173 ///            [k0 k1 k2 k3 ]
4174 ///       N1 =+[k1 k0 k3 k2 ]
4175 ///            [k0 k2 k1 k3 ]
4176 ///       N2 =+[k1 k3 k0 k2 ]
4177 ///            [k0    k2    k1    k3    ]
4178 /// Extended =+[k1    k3    k0    k2    ]
4179 ///            [k0    k2    ]
4180 /// Extracted=+[k1    k3    ]
4181 ///
4182 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4183   EVT VT = N->getValueType(0);
4184   SDLoc DL(N);
4185
4186   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4187
4188   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4189   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4190   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4191   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4192   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4193
4194   if (VT.is64BitVector()) {
4195     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4196     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4197                        DAG.getIntPtrConstant(0));
4198   } else {
4199     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4200                                     DAG.getIntPtrConstant(0));
4201     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4202   }
4203 }
4204
4205 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4206                           const ARMSubtarget *ST) {
4207   EVT VT = N->getValueType(0);
4208
4209   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4210   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4211           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4212          "Unexpected type for custom ctpop lowering");
4213
4214   if (VT.getVectorElementType() == MVT::i32)
4215     return lowerCTPOP32BitElements(N, DAG);
4216   else
4217     return lowerCTPOP16BitElements(N, DAG);
4218 }
4219
4220 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4221                           const ARMSubtarget *ST) {
4222   EVT VT = N->getValueType(0);
4223   SDLoc dl(N);
4224
4225   if (!VT.isVector())
4226     return SDValue();
4227
4228   // Lower vector shifts on NEON to use VSHL.
4229   assert(ST->hasNEON() && "unexpected vector shift");
4230
4231   // Left shifts translate directly to the vshiftu intrinsic.
4232   if (N->getOpcode() == ISD::SHL)
4233     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4234                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4235                        N->getOperand(0), N->getOperand(1));
4236
4237   assert((N->getOpcode() == ISD::SRA ||
4238           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4239
4240   // NEON uses the same intrinsics for both left and right shifts.  For
4241   // right shifts, the shift amounts are negative, so negate the vector of
4242   // shift amounts.
4243   EVT ShiftVT = N->getOperand(1).getValueType();
4244   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4245                                      getZeroVector(ShiftVT, DAG, dl),
4246                                      N->getOperand(1));
4247   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4248                              Intrinsic::arm_neon_vshifts :
4249                              Intrinsic::arm_neon_vshiftu);
4250   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4251                      DAG.getConstant(vshiftInt, MVT::i32),
4252                      N->getOperand(0), NegatedCount);
4253 }
4254
4255 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4256                                 const ARMSubtarget *ST) {
4257   EVT VT = N->getValueType(0);
4258   SDLoc dl(N);
4259
4260   // We can get here for a node like i32 = ISD::SHL i32, i64
4261   if (VT != MVT::i64)
4262     return SDValue();
4263
4264   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4265          "Unknown shift to lower!");
4266
4267   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4268   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4269       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4270     return SDValue();
4271
4272   // If we are in thumb mode, we don't have RRX.
4273   if (ST->isThumb1Only()) return SDValue();
4274
4275   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4276   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4277                            DAG.getConstant(0, MVT::i32));
4278   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4279                            DAG.getConstant(1, MVT::i32));
4280
4281   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4282   // captures the result into a carry flag.
4283   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4284   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4285
4286   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4287   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4288
4289   // Merge the pieces into a single i64 value.
4290  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4291 }
4292
4293 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4294   SDValue TmpOp0, TmpOp1;
4295   bool Invert = false;
4296   bool Swap = false;
4297   unsigned Opc = 0;
4298
4299   SDValue Op0 = Op.getOperand(0);
4300   SDValue Op1 = Op.getOperand(1);
4301   SDValue CC = Op.getOperand(2);
4302   EVT VT = Op.getValueType();
4303   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4304   SDLoc dl(Op);
4305
4306   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4307     switch (SetCCOpcode) {
4308     default: llvm_unreachable("Illegal FP comparison");
4309     case ISD::SETUNE:
4310     case ISD::SETNE:  Invert = true; // Fallthrough
4311     case ISD::SETOEQ:
4312     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4313     case ISD::SETOLT:
4314     case ISD::SETLT: Swap = true; // Fallthrough
4315     case ISD::SETOGT:
4316     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4317     case ISD::SETOLE:
4318     case ISD::SETLE:  Swap = true; // Fallthrough
4319     case ISD::SETOGE:
4320     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4321     case ISD::SETUGE: Swap = true; // Fallthrough
4322     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4323     case ISD::SETUGT: Swap = true; // Fallthrough
4324     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4325     case ISD::SETUEQ: Invert = true; // Fallthrough
4326     case ISD::SETONE:
4327       // Expand this to (OLT | OGT).
4328       TmpOp0 = Op0;
4329       TmpOp1 = Op1;
4330       Opc = ISD::OR;
4331       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4332       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4333       break;
4334     case ISD::SETUO: Invert = true; // Fallthrough
4335     case ISD::SETO:
4336       // Expand this to (OLT | OGE).
4337       TmpOp0 = Op0;
4338       TmpOp1 = Op1;
4339       Opc = ISD::OR;
4340       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4341       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4342       break;
4343     }
4344   } else {
4345     // Integer comparisons.
4346     switch (SetCCOpcode) {
4347     default: llvm_unreachable("Illegal integer comparison");
4348     case ISD::SETNE:  Invert = true;
4349     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4350     case ISD::SETLT:  Swap = true;
4351     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4352     case ISD::SETLE:  Swap = true;
4353     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4354     case ISD::SETULT: Swap = true;
4355     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4356     case ISD::SETULE: Swap = true;
4357     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4358     }
4359
4360     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4361     if (Opc == ARMISD::VCEQ) {
4362
4363       SDValue AndOp;
4364       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4365         AndOp = Op0;
4366       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4367         AndOp = Op1;
4368
4369       // Ignore bitconvert.
4370       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4371         AndOp = AndOp.getOperand(0);
4372
4373       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4374         Opc = ARMISD::VTST;
4375         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4376         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4377         Invert = !Invert;
4378       }
4379     }
4380   }
4381
4382   if (Swap)
4383     std::swap(Op0, Op1);
4384
4385   // If one of the operands is a constant vector zero, attempt to fold the
4386   // comparison to a specialized compare-against-zero form.
4387   SDValue SingleOp;
4388   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4389     SingleOp = Op0;
4390   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4391     if (Opc == ARMISD::VCGE)
4392       Opc = ARMISD::VCLEZ;
4393     else if (Opc == ARMISD::VCGT)
4394       Opc = ARMISD::VCLTZ;
4395     SingleOp = Op1;
4396   }
4397
4398   SDValue Result;
4399   if (SingleOp.getNode()) {
4400     switch (Opc) {
4401     case ARMISD::VCEQ:
4402       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4403     case ARMISD::VCGE:
4404       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4405     case ARMISD::VCLEZ:
4406       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4407     case ARMISD::VCGT:
4408       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4409     case ARMISD::VCLTZ:
4410       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4411     default:
4412       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4413     }
4414   } else {
4415      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4416   }
4417
4418   if (Invert)
4419     Result = DAG.getNOT(dl, Result, VT);
4420
4421   return Result;
4422 }
4423
4424 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4425 /// valid vector constant for a NEON instruction with a "modified immediate"
4426 /// operand (e.g., VMOV).  If so, return the encoded value.
4427 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4428                                  unsigned SplatBitSize, SelectionDAG &DAG,
4429                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4430   unsigned OpCmode, Imm;
4431
4432   // SplatBitSize is set to the smallest size that splats the vector, so a
4433   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4434   // immediate instructions others than VMOV do not support the 8-bit encoding
4435   // of a zero vector, and the default encoding of zero is supposed to be the
4436   // 32-bit version.
4437   if (SplatBits == 0)
4438     SplatBitSize = 32;
4439
4440   switch (SplatBitSize) {
4441   case 8:
4442     if (type != VMOVModImm)
4443       return SDValue();
4444     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4445     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4446     OpCmode = 0xe;
4447     Imm = SplatBits;
4448     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4449     break;
4450
4451   case 16:
4452     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4453     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4454     if ((SplatBits & ~0xff) == 0) {
4455       // Value = 0x00nn: Op=x, Cmode=100x.
4456       OpCmode = 0x8;
4457       Imm = SplatBits;
4458       break;
4459     }
4460     if ((SplatBits & ~0xff00) == 0) {
4461       // Value = 0xnn00: Op=x, Cmode=101x.
4462       OpCmode = 0xa;
4463       Imm = SplatBits >> 8;
4464       break;
4465     }
4466     return SDValue();
4467
4468   case 32:
4469     // NEON's 32-bit VMOV supports splat values where:
4470     // * only one byte is nonzero, or
4471     // * the least significant byte is 0xff and the second byte is nonzero, or
4472     // * the least significant 2 bytes are 0xff and the third is nonzero.
4473     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4474     if ((SplatBits & ~0xff) == 0) {
4475       // Value = 0x000000nn: Op=x, Cmode=000x.
4476       OpCmode = 0;
4477       Imm = SplatBits;
4478       break;
4479     }
4480     if ((SplatBits & ~0xff00) == 0) {
4481       // Value = 0x0000nn00: Op=x, Cmode=001x.
4482       OpCmode = 0x2;
4483       Imm = SplatBits >> 8;
4484       break;
4485     }
4486     if ((SplatBits & ~0xff0000) == 0) {
4487       // Value = 0x00nn0000: Op=x, Cmode=010x.
4488       OpCmode = 0x4;
4489       Imm = SplatBits >> 16;
4490       break;
4491     }
4492     if ((SplatBits & ~0xff000000) == 0) {
4493       // Value = 0xnn000000: Op=x, Cmode=011x.
4494       OpCmode = 0x6;
4495       Imm = SplatBits >> 24;
4496       break;
4497     }
4498
4499     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4500     if (type == OtherModImm) return SDValue();
4501
4502     if ((SplatBits & ~0xffff) == 0 &&
4503         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4504       // Value = 0x0000nnff: Op=x, Cmode=1100.
4505       OpCmode = 0xc;
4506       Imm = SplatBits >> 8;
4507       break;
4508     }
4509
4510     if ((SplatBits & ~0xffffff) == 0 &&
4511         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4512       // Value = 0x00nnffff: Op=x, Cmode=1101.
4513       OpCmode = 0xd;
4514       Imm = SplatBits >> 16;
4515       break;
4516     }
4517
4518     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4519     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4520     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4521     // and fall through here to test for a valid 64-bit splat.  But, then the
4522     // caller would also need to check and handle the change in size.
4523     return SDValue();
4524
4525   case 64: {
4526     if (type != VMOVModImm)
4527       return SDValue();
4528     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4529     uint64_t BitMask = 0xff;
4530     uint64_t Val = 0;
4531     unsigned ImmMask = 1;
4532     Imm = 0;
4533     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4534       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4535         Val |= BitMask;
4536         Imm |= ImmMask;
4537       } else if ((SplatBits & BitMask) != 0) {
4538         return SDValue();
4539       }
4540       BitMask <<= 8;
4541       ImmMask <<= 1;
4542     }
4543
4544     if (DAG.getTargetLoweringInfo().isBigEndian())
4545       // swap higher and lower 32 bit word
4546       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4547
4548     // Op=1, Cmode=1110.
4549     OpCmode = 0x1e;
4550     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4551     break;
4552   }
4553
4554   default:
4555     llvm_unreachable("unexpected size for isNEONModifiedImm");
4556   }
4557
4558   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4559   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4560 }
4561
4562 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4563                                            const ARMSubtarget *ST) const {
4564   if (!ST->hasVFP3())
4565     return SDValue();
4566
4567   bool IsDouble = Op.getValueType() == MVT::f64;
4568   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4569
4570   // Try splatting with a VMOV.f32...
4571   APFloat FPVal = CFP->getValueAPF();
4572   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4573
4574   if (ImmVal != -1) {
4575     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4576       // We have code in place to select a valid ConstantFP already, no need to
4577       // do any mangling.
4578       return Op;
4579     }
4580
4581     // It's a float and we are trying to use NEON operations where
4582     // possible. Lower it to a splat followed by an extract.
4583     SDLoc DL(Op);
4584     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4585     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4586                                       NewVal);
4587     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4588                        DAG.getConstant(0, MVT::i32));
4589   }
4590
4591   // The rest of our options are NEON only, make sure that's allowed before
4592   // proceeding..
4593   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4594     return SDValue();
4595
4596   EVT VMovVT;
4597   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4598
4599   // It wouldn't really be worth bothering for doubles except for one very
4600   // important value, which does happen to match: 0.0. So make sure we don't do
4601   // anything stupid.
4602   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4603     return SDValue();
4604
4605   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4606   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4607                                      false, VMOVModImm);
4608   if (NewVal != SDValue()) {
4609     SDLoc DL(Op);
4610     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4611                                       NewVal);
4612     if (IsDouble)
4613       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4614
4615     // It's a float: cast and extract a vector element.
4616     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4617                                        VecConstant);
4618     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4619                        DAG.getConstant(0, MVT::i32));
4620   }
4621
4622   // Finally, try a VMVN.i32
4623   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4624                              false, VMVNModImm);
4625   if (NewVal != SDValue()) {
4626     SDLoc DL(Op);
4627     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4628
4629     if (IsDouble)
4630       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4631
4632     // It's a float: cast and extract a vector element.
4633     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4634                                        VecConstant);
4635     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4636                        DAG.getConstant(0, MVT::i32));
4637   }
4638
4639   return SDValue();
4640 }
4641
4642 // check if an VEXT instruction can handle the shuffle mask when the
4643 // vector sources of the shuffle are the same.
4644 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4645   unsigned NumElts = VT.getVectorNumElements();
4646
4647   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4648   if (M[0] < 0)
4649     return false;
4650
4651   Imm = M[0];
4652
4653   // If this is a VEXT shuffle, the immediate value is the index of the first
4654   // element.  The other shuffle indices must be the successive elements after
4655   // the first one.
4656   unsigned ExpectedElt = Imm;
4657   for (unsigned i = 1; i < NumElts; ++i) {
4658     // Increment the expected index.  If it wraps around, just follow it
4659     // back to index zero and keep going.
4660     ++ExpectedElt;
4661     if (ExpectedElt == NumElts)
4662       ExpectedElt = 0;
4663
4664     if (M[i] < 0) continue; // ignore UNDEF indices
4665     if (ExpectedElt != static_cast<unsigned>(M[i]))
4666       return false;
4667   }
4668
4669   return true;
4670 }
4671
4672
4673 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4674                        bool &ReverseVEXT, unsigned &Imm) {
4675   unsigned NumElts = VT.getVectorNumElements();
4676   ReverseVEXT = false;
4677
4678   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4679   if (M[0] < 0)
4680     return false;
4681
4682   Imm = M[0];
4683
4684   // If this is a VEXT shuffle, the immediate value is the index of the first
4685   // element.  The other shuffle indices must be the successive elements after
4686   // the first one.
4687   unsigned ExpectedElt = Imm;
4688   for (unsigned i = 1; i < NumElts; ++i) {
4689     // Increment the expected index.  If it wraps around, it may still be
4690     // a VEXT but the source vectors must be swapped.
4691     ExpectedElt += 1;
4692     if (ExpectedElt == NumElts * 2) {
4693       ExpectedElt = 0;
4694       ReverseVEXT = true;
4695     }
4696
4697     if (M[i] < 0) continue; // ignore UNDEF indices
4698     if (ExpectedElt != static_cast<unsigned>(M[i]))
4699       return false;
4700   }
4701
4702   // Adjust the index value if the source operands will be swapped.
4703   if (ReverseVEXT)
4704     Imm -= NumElts;
4705
4706   return true;
4707 }
4708
4709 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4710 /// instruction with the specified blocksize.  (The order of the elements
4711 /// within each block of the vector is reversed.)
4712 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4713   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4714          "Only possible block sizes for VREV are: 16, 32, 64");
4715
4716   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4717   if (EltSz == 64)
4718     return false;
4719
4720   unsigned NumElts = VT.getVectorNumElements();
4721   unsigned BlockElts = M[0] + 1;
4722   // If the first shuffle index is UNDEF, be optimistic.
4723   if (M[0] < 0)
4724     BlockElts = BlockSize / EltSz;
4725
4726   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4727     return false;
4728
4729   for (unsigned i = 0; i < NumElts; ++i) {
4730     if (M[i] < 0) continue; // ignore UNDEF indices
4731     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4732       return false;
4733   }
4734
4735   return true;
4736 }
4737
4738 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4739   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4740   // range, then 0 is placed into the resulting vector. So pretty much any mask
4741   // of 8 elements can work here.
4742   return VT == MVT::v8i8 && M.size() == 8;
4743 }
4744
4745 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4746   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4747   if (EltSz == 64)
4748     return false;
4749
4750   unsigned NumElts = VT.getVectorNumElements();
4751   WhichResult = (M[0] == 0 ? 0 : 1);
4752   for (unsigned i = 0; i < NumElts; i += 2) {
4753     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4754         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4755       return false;
4756   }
4757   return true;
4758 }
4759
4760 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4761 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4762 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4763 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4764   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4765   if (EltSz == 64)
4766     return false;
4767
4768   unsigned NumElts = VT.getVectorNumElements();
4769   WhichResult = (M[0] == 0 ? 0 : 1);
4770   for (unsigned i = 0; i < NumElts; i += 2) {
4771     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4772         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4773       return false;
4774   }
4775   return true;
4776 }
4777
4778 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4779   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4780   if (EltSz == 64)
4781     return false;
4782
4783   unsigned NumElts = VT.getVectorNumElements();
4784   WhichResult = (M[0] == 0 ? 0 : 1);
4785   for (unsigned i = 0; i != NumElts; ++i) {
4786     if (M[i] < 0) continue; // ignore UNDEF indices
4787     if ((unsigned) M[i] != 2 * i + WhichResult)
4788       return false;
4789   }
4790
4791   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4792   if (VT.is64BitVector() && EltSz == 32)
4793     return false;
4794
4795   return true;
4796 }
4797
4798 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4799 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4800 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4801 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4802   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4803   if (EltSz == 64)
4804     return false;
4805
4806   unsigned Half = VT.getVectorNumElements() / 2;
4807   WhichResult = (M[0] == 0 ? 0 : 1);
4808   for (unsigned j = 0; j != 2; ++j) {
4809     unsigned Idx = WhichResult;
4810     for (unsigned i = 0; i != Half; ++i) {
4811       int MIdx = M[i + j * Half];
4812       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4813         return false;
4814       Idx += 2;
4815     }
4816   }
4817
4818   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4819   if (VT.is64BitVector() && EltSz == 32)
4820     return false;
4821
4822   return true;
4823 }
4824
4825 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4826   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4827   if (EltSz == 64)
4828     return false;
4829
4830   unsigned NumElts = VT.getVectorNumElements();
4831   WhichResult = (M[0] == 0 ? 0 : 1);
4832   unsigned Idx = WhichResult * NumElts / 2;
4833   for (unsigned i = 0; i != NumElts; i += 2) {
4834     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4835         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4836       return false;
4837     Idx += 1;
4838   }
4839
4840   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4841   if (VT.is64BitVector() && EltSz == 32)
4842     return false;
4843
4844   return true;
4845 }
4846
4847 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4848 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4849 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4850 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4851   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4852   if (EltSz == 64)
4853     return false;
4854
4855   unsigned NumElts = VT.getVectorNumElements();
4856   WhichResult = (M[0] == 0 ? 0 : 1);
4857   unsigned Idx = WhichResult * NumElts / 2;
4858   for (unsigned i = 0; i != NumElts; i += 2) {
4859     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4860         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4861       return false;
4862     Idx += 1;
4863   }
4864
4865   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4866   if (VT.is64BitVector() && EltSz == 32)
4867     return false;
4868
4869   return true;
4870 }
4871
4872 /// \return true if this is a reverse operation on an vector.
4873 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4874   unsigned NumElts = VT.getVectorNumElements();
4875   // Make sure the mask has the right size.
4876   if (NumElts != M.size())
4877       return false;
4878
4879   // Look for <15, ..., 3, -1, 1, 0>.
4880   for (unsigned i = 0; i != NumElts; ++i)
4881     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4882       return false;
4883
4884   return true;
4885 }
4886
4887 // If N is an integer constant that can be moved into a register in one
4888 // instruction, return an SDValue of such a constant (will become a MOV
4889 // instruction).  Otherwise return null.
4890 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4891                                      const ARMSubtarget *ST, SDLoc dl) {
4892   uint64_t Val;
4893   if (!isa<ConstantSDNode>(N))
4894     return SDValue();
4895   Val = cast<ConstantSDNode>(N)->getZExtValue();
4896
4897   if (ST->isThumb1Only()) {
4898     if (Val <= 255 || ~Val <= 255)
4899       return DAG.getConstant(Val, MVT::i32);
4900   } else {
4901     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4902       return DAG.getConstant(Val, MVT::i32);
4903   }
4904   return SDValue();
4905 }
4906
4907 // If this is a case we can't handle, return null and let the default
4908 // expansion code take care of it.
4909 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4910                                              const ARMSubtarget *ST) const {
4911   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4912   SDLoc dl(Op);
4913   EVT VT = Op.getValueType();
4914
4915   APInt SplatBits, SplatUndef;
4916   unsigned SplatBitSize;
4917   bool HasAnyUndefs;
4918   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4919     if (SplatBitSize <= 64) {
4920       // Check if an immediate VMOV works.
4921       EVT VmovVT;
4922       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4923                                       SplatUndef.getZExtValue(), SplatBitSize,
4924                                       DAG, VmovVT, VT.is128BitVector(),
4925                                       VMOVModImm);
4926       if (Val.getNode()) {
4927         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4928         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4929       }
4930
4931       // Try an immediate VMVN.
4932       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4933       Val = isNEONModifiedImm(NegatedImm,
4934                                       SplatUndef.getZExtValue(), SplatBitSize,
4935                                       DAG, VmovVT, VT.is128BitVector(),
4936                                       VMVNModImm);
4937       if (Val.getNode()) {
4938         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4939         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4940       }
4941
4942       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4943       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4944         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4945         if (ImmVal != -1) {
4946           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4947           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4948         }
4949       }
4950     }
4951   }
4952
4953   // Scan through the operands to see if only one value is used.
4954   //
4955   // As an optimisation, even if more than one value is used it may be more
4956   // profitable to splat with one value then change some lanes.
4957   //
4958   // Heuristically we decide to do this if the vector has a "dominant" value,
4959   // defined as splatted to more than half of the lanes.
4960   unsigned NumElts = VT.getVectorNumElements();
4961   bool isOnlyLowElement = true;
4962   bool usesOnlyOneValue = true;
4963   bool hasDominantValue = false;
4964   bool isConstant = true;
4965
4966   // Map of the number of times a particular SDValue appears in the
4967   // element list.
4968   DenseMap<SDValue, unsigned> ValueCounts;
4969   SDValue Value;
4970   for (unsigned i = 0; i < NumElts; ++i) {
4971     SDValue V = Op.getOperand(i);
4972     if (V.getOpcode() == ISD::UNDEF)
4973       continue;
4974     if (i > 0)
4975       isOnlyLowElement = false;
4976     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4977       isConstant = false;
4978
4979     ValueCounts.insert(std::make_pair(V, 0));
4980     unsigned &Count = ValueCounts[V];
4981
4982     // Is this value dominant? (takes up more than half of the lanes)
4983     if (++Count > (NumElts / 2)) {
4984       hasDominantValue = true;
4985       Value = V;
4986     }
4987   }
4988   if (ValueCounts.size() != 1)
4989     usesOnlyOneValue = false;
4990   if (!Value.getNode() && ValueCounts.size() > 0)
4991     Value = ValueCounts.begin()->first;
4992
4993   if (ValueCounts.size() == 0)
4994     return DAG.getUNDEF(VT);
4995
4996   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4997   // Keep going if we are hitting this case.
4998   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4999     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5000
5001   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5002
5003   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5004   // i32 and try again.
5005   if (hasDominantValue && EltSize <= 32) {
5006     if (!isConstant) {
5007       SDValue N;
5008
5009       // If we are VDUPing a value that comes directly from a vector, that will
5010       // cause an unnecessary move to and from a GPR, where instead we could
5011       // just use VDUPLANE. We can only do this if the lane being extracted
5012       // is at a constant index, as the VDUP from lane instructions only have
5013       // constant-index forms.
5014       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5015           isa<ConstantSDNode>(Value->getOperand(1))) {
5016         // We need to create a new undef vector to use for the VDUPLANE if the
5017         // size of the vector from which we get the value is different than the
5018         // size of the vector that we need to create. We will insert the element
5019         // such that the register coalescer will remove unnecessary copies.
5020         if (VT != Value->getOperand(0).getValueType()) {
5021           ConstantSDNode *constIndex;
5022           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5023           assert(constIndex && "The index is not a constant!");
5024           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5025                              VT.getVectorNumElements();
5026           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5027                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5028                         Value, DAG.getConstant(index, MVT::i32)),
5029                            DAG.getConstant(index, MVT::i32));
5030         } else
5031           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5032                         Value->getOperand(0), Value->getOperand(1));
5033       } else
5034         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5035
5036       if (!usesOnlyOneValue) {
5037         // The dominant value was splatted as 'N', but we now have to insert
5038         // all differing elements.
5039         for (unsigned I = 0; I < NumElts; ++I) {
5040           if (Op.getOperand(I) == Value)
5041             continue;
5042           SmallVector<SDValue, 3> Ops;
5043           Ops.push_back(N);
5044           Ops.push_back(Op.getOperand(I));
5045           Ops.push_back(DAG.getConstant(I, MVT::i32));
5046           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5047         }
5048       }
5049       return N;
5050     }
5051     if (VT.getVectorElementType().isFloatingPoint()) {
5052       SmallVector<SDValue, 8> Ops;
5053       for (unsigned i = 0; i < NumElts; ++i)
5054         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5055                                   Op.getOperand(i)));
5056       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5057       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5058       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5059       if (Val.getNode())
5060         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5061     }
5062     if (usesOnlyOneValue) {
5063       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5064       if (isConstant && Val.getNode())
5065         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5066     }
5067   }
5068
5069   // If all elements are constants and the case above didn't get hit, fall back
5070   // to the default expansion, which will generate a load from the constant
5071   // pool.
5072   if (isConstant)
5073     return SDValue();
5074
5075   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5076   if (NumElts >= 4) {
5077     SDValue shuffle = ReconstructShuffle(Op, DAG);
5078     if (shuffle != SDValue())
5079       return shuffle;
5080   }
5081
5082   // Vectors with 32- or 64-bit elements can be built by directly assigning
5083   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5084   // will be legalized.
5085   if (EltSize >= 32) {
5086     // Do the expansion with floating-point types, since that is what the VFP
5087     // registers are defined to use, and since i64 is not legal.
5088     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5089     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5090     SmallVector<SDValue, 8> Ops;
5091     for (unsigned i = 0; i < NumElts; ++i)
5092       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5093     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5094     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5095   }
5096
5097   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5098   // know the default expansion would otherwise fall back on something even
5099   // worse. For a vector with one or two non-undef values, that's
5100   // scalar_to_vector for the elements followed by a shuffle (provided the
5101   // shuffle is valid for the target) and materialization element by element
5102   // on the stack followed by a load for everything else.
5103   if (!isConstant && !usesOnlyOneValue) {
5104     SDValue Vec = DAG.getUNDEF(VT);
5105     for (unsigned i = 0 ; i < NumElts; ++i) {
5106       SDValue V = Op.getOperand(i);
5107       if (V.getOpcode() == ISD::UNDEF)
5108         continue;
5109       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5110       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5111     }
5112     return Vec;
5113   }
5114
5115   return SDValue();
5116 }
5117
5118 // Gather data to see if the operation can be modelled as a
5119 // shuffle in combination with VEXTs.
5120 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5121                                               SelectionDAG &DAG) const {
5122   SDLoc dl(Op);
5123   EVT VT = Op.getValueType();
5124   unsigned NumElts = VT.getVectorNumElements();
5125
5126   SmallVector<SDValue, 2> SourceVecs;
5127   SmallVector<unsigned, 2> MinElts;
5128   SmallVector<unsigned, 2> MaxElts;
5129
5130   for (unsigned i = 0; i < NumElts; ++i) {
5131     SDValue V = Op.getOperand(i);
5132     if (V.getOpcode() == ISD::UNDEF)
5133       continue;
5134     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5135       // A shuffle can only come from building a vector from various
5136       // elements of other vectors.
5137       return SDValue();
5138     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5139                VT.getVectorElementType()) {
5140       // This code doesn't know how to handle shuffles where the vector
5141       // element types do not match (this happens because type legalization
5142       // promotes the return type of EXTRACT_VECTOR_ELT).
5143       // FIXME: It might be appropriate to extend this code to handle
5144       // mismatched types.
5145       return SDValue();
5146     }
5147
5148     // Record this extraction against the appropriate vector if possible...
5149     SDValue SourceVec = V.getOperand(0);
5150     // If the element number isn't a constant, we can't effectively
5151     // analyze what's going on.
5152     if (!isa<ConstantSDNode>(V.getOperand(1)))
5153       return SDValue();
5154     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5155     bool FoundSource = false;
5156     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5157       if (SourceVecs[j] == SourceVec) {
5158         if (MinElts[j] > EltNo)
5159           MinElts[j] = EltNo;
5160         if (MaxElts[j] < EltNo)
5161           MaxElts[j] = EltNo;
5162         FoundSource = true;
5163         break;
5164       }
5165     }
5166
5167     // Or record a new source if not...
5168     if (!FoundSource) {
5169       SourceVecs.push_back(SourceVec);
5170       MinElts.push_back(EltNo);
5171       MaxElts.push_back(EltNo);
5172     }
5173   }
5174
5175   // Currently only do something sane when at most two source vectors
5176   // involved.
5177   if (SourceVecs.size() > 2)
5178     return SDValue();
5179
5180   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5181   int VEXTOffsets[2] = {0, 0};
5182
5183   // This loop extracts the usage patterns of the source vectors
5184   // and prepares appropriate SDValues for a shuffle if possible.
5185   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5186     if (SourceVecs[i].getValueType() == VT) {
5187       // No VEXT necessary
5188       ShuffleSrcs[i] = SourceVecs[i];
5189       VEXTOffsets[i] = 0;
5190       continue;
5191     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5192       // It probably isn't worth padding out a smaller vector just to
5193       // break it down again in a shuffle.
5194       return SDValue();
5195     }
5196
5197     // Since only 64-bit and 128-bit vectors are legal on ARM and
5198     // we've eliminated the other cases...
5199     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5200            "unexpected vector sizes in ReconstructShuffle");
5201
5202     if (MaxElts[i] - MinElts[i] >= NumElts) {
5203       // Span too large for a VEXT to cope
5204       return SDValue();
5205     }
5206
5207     if (MinElts[i] >= NumElts) {
5208       // The extraction can just take the second half
5209       VEXTOffsets[i] = NumElts;
5210       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5211                                    SourceVecs[i],
5212                                    DAG.getIntPtrConstant(NumElts));
5213     } else if (MaxElts[i] < NumElts) {
5214       // The extraction can just take the first half
5215       VEXTOffsets[i] = 0;
5216       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5217                                    SourceVecs[i],
5218                                    DAG.getIntPtrConstant(0));
5219     } else {
5220       // An actual VEXT is needed
5221       VEXTOffsets[i] = MinElts[i];
5222       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5223                                      SourceVecs[i],
5224                                      DAG.getIntPtrConstant(0));
5225       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5226                                      SourceVecs[i],
5227                                      DAG.getIntPtrConstant(NumElts));
5228       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5229                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5230     }
5231   }
5232
5233   SmallVector<int, 8> Mask;
5234
5235   for (unsigned i = 0; i < NumElts; ++i) {
5236     SDValue Entry = Op.getOperand(i);
5237     if (Entry.getOpcode() == ISD::UNDEF) {
5238       Mask.push_back(-1);
5239       continue;
5240     }
5241
5242     SDValue ExtractVec = Entry.getOperand(0);
5243     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5244                                           .getOperand(1))->getSExtValue();
5245     if (ExtractVec == SourceVecs[0]) {
5246       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5247     } else {
5248       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5249     }
5250   }
5251
5252   // Final check before we try to produce nonsense...
5253   if (isShuffleMaskLegal(Mask, VT))
5254     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5255                                 &Mask[0]);
5256
5257   return SDValue();
5258 }
5259
5260 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5261 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5262 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5263 /// are assumed to be legal.
5264 bool
5265 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5266                                       EVT VT) const {
5267   if (VT.getVectorNumElements() == 4 &&
5268       (VT.is128BitVector() || VT.is64BitVector())) {
5269     unsigned PFIndexes[4];
5270     for (unsigned i = 0; i != 4; ++i) {
5271       if (M[i] < 0)
5272         PFIndexes[i] = 8;
5273       else
5274         PFIndexes[i] = M[i];
5275     }
5276
5277     // Compute the index in the perfect shuffle table.
5278     unsigned PFTableIndex =
5279       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5280     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5281     unsigned Cost = (PFEntry >> 30);
5282
5283     if (Cost <= 4)
5284       return true;
5285   }
5286
5287   bool ReverseVEXT;
5288   unsigned Imm, WhichResult;
5289
5290   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5291   return (EltSize >= 32 ||
5292           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5293           isVREVMask(M, VT, 64) ||
5294           isVREVMask(M, VT, 32) ||
5295           isVREVMask(M, VT, 16) ||
5296           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5297           isVTBLMask(M, VT) ||
5298           isVTRNMask(M, VT, WhichResult) ||
5299           isVUZPMask(M, VT, WhichResult) ||
5300           isVZIPMask(M, VT, WhichResult) ||
5301           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5302           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5303           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5304           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5305 }
5306
5307 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5308 /// the specified operations to build the shuffle.
5309 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5310                                       SDValue RHS, SelectionDAG &DAG,
5311                                       SDLoc dl) {
5312   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5313   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5314   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5315
5316   enum {
5317     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5318     OP_VREV,
5319     OP_VDUP0,
5320     OP_VDUP1,
5321     OP_VDUP2,
5322     OP_VDUP3,
5323     OP_VEXT1,
5324     OP_VEXT2,
5325     OP_VEXT3,
5326     OP_VUZPL, // VUZP, left result
5327     OP_VUZPR, // VUZP, right result
5328     OP_VZIPL, // VZIP, left result
5329     OP_VZIPR, // VZIP, right result
5330     OP_VTRNL, // VTRN, left result
5331     OP_VTRNR  // VTRN, right result
5332   };
5333
5334   if (OpNum == OP_COPY) {
5335     if (LHSID == (1*9+2)*9+3) return LHS;
5336     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5337     return RHS;
5338   }
5339
5340   SDValue OpLHS, OpRHS;
5341   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5342   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5343   EVT VT = OpLHS.getValueType();
5344
5345   switch (OpNum) {
5346   default: llvm_unreachable("Unknown shuffle opcode!");
5347   case OP_VREV:
5348     // VREV divides the vector in half and swaps within the half.
5349     if (VT.getVectorElementType() == MVT::i32 ||
5350         VT.getVectorElementType() == MVT::f32)
5351       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5352     // vrev <4 x i16> -> VREV32
5353     if (VT.getVectorElementType() == MVT::i16)
5354       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5355     // vrev <4 x i8> -> VREV16
5356     assert(VT.getVectorElementType() == MVT::i8);
5357     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5358   case OP_VDUP0:
5359   case OP_VDUP1:
5360   case OP_VDUP2:
5361   case OP_VDUP3:
5362     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5363                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5364   case OP_VEXT1:
5365   case OP_VEXT2:
5366   case OP_VEXT3:
5367     return DAG.getNode(ARMISD::VEXT, dl, VT,
5368                        OpLHS, OpRHS,
5369                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5370   case OP_VUZPL:
5371   case OP_VUZPR:
5372     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5373                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5374   case OP_VZIPL:
5375   case OP_VZIPR:
5376     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5377                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5378   case OP_VTRNL:
5379   case OP_VTRNR:
5380     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5381                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5382   }
5383 }
5384
5385 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5386                                        ArrayRef<int> ShuffleMask,
5387                                        SelectionDAG &DAG) {
5388   // Check to see if we can use the VTBL instruction.
5389   SDValue V1 = Op.getOperand(0);
5390   SDValue V2 = Op.getOperand(1);
5391   SDLoc DL(Op);
5392
5393   SmallVector<SDValue, 8> VTBLMask;
5394   for (ArrayRef<int>::iterator
5395          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5396     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5397
5398   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5399     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5400                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5401
5402   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5403                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5404 }
5405
5406 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5407                                                       SelectionDAG &DAG) {
5408   SDLoc DL(Op);
5409   SDValue OpLHS = Op.getOperand(0);
5410   EVT VT = OpLHS.getValueType();
5411
5412   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5413          "Expect an v8i16/v16i8 type");
5414   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5415   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5416   // extract the first 8 bytes into the top double word and the last 8 bytes
5417   // into the bottom double word. The v8i16 case is similar.
5418   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5419   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5420                      DAG.getConstant(ExtractNum, MVT::i32));
5421 }
5422
5423 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5424   SDValue V1 = Op.getOperand(0);
5425   SDValue V2 = Op.getOperand(1);
5426   SDLoc dl(Op);
5427   EVT VT = Op.getValueType();
5428   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5429
5430   // Convert shuffles that are directly supported on NEON to target-specific
5431   // DAG nodes, instead of keeping them as shuffles and matching them again
5432   // during code selection.  This is more efficient and avoids the possibility
5433   // of inconsistencies between legalization and selection.
5434   // FIXME: floating-point vectors should be canonicalized to integer vectors
5435   // of the same time so that they get CSEd properly.
5436   ArrayRef<int> ShuffleMask = SVN->getMask();
5437
5438   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5439   if (EltSize <= 32) {
5440     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5441       int Lane = SVN->getSplatIndex();
5442       // If this is undef splat, generate it via "just" vdup, if possible.
5443       if (Lane == -1) Lane = 0;
5444
5445       // Test if V1 is a SCALAR_TO_VECTOR.
5446       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5447         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5448       }
5449       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5450       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5451       // reaches it).
5452       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5453           !isa<ConstantSDNode>(V1.getOperand(0))) {
5454         bool IsScalarToVector = true;
5455         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5456           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5457             IsScalarToVector = false;
5458             break;
5459           }
5460         if (IsScalarToVector)
5461           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5462       }
5463       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5464                          DAG.getConstant(Lane, MVT::i32));
5465     }
5466
5467     bool ReverseVEXT;
5468     unsigned Imm;
5469     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5470       if (ReverseVEXT)
5471         std::swap(V1, V2);
5472       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5473                          DAG.getConstant(Imm, MVT::i32));
5474     }
5475
5476     if (isVREVMask(ShuffleMask, VT, 64))
5477       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5478     if (isVREVMask(ShuffleMask, VT, 32))
5479       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5480     if (isVREVMask(ShuffleMask, VT, 16))
5481       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5482
5483     if (V2->getOpcode() == ISD::UNDEF &&
5484         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5485       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5486                          DAG.getConstant(Imm, MVT::i32));
5487     }
5488
5489     // Check for Neon shuffles that modify both input vectors in place.
5490     // If both results are used, i.e., if there are two shuffles with the same
5491     // source operands and with masks corresponding to both results of one of
5492     // these operations, DAG memoization will ensure that a single node is
5493     // used for both shuffles.
5494     unsigned WhichResult;
5495     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5496       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5497                          V1, V2).getValue(WhichResult);
5498     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5499       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5500                          V1, V2).getValue(WhichResult);
5501     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5502       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5503                          V1, V2).getValue(WhichResult);
5504
5505     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5506       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5507                          V1, V1).getValue(WhichResult);
5508     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5509       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5510                          V1, V1).getValue(WhichResult);
5511     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5512       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5513                          V1, V1).getValue(WhichResult);
5514   }
5515
5516   // If the shuffle is not directly supported and it has 4 elements, use
5517   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5518   unsigned NumElts = VT.getVectorNumElements();
5519   if (NumElts == 4) {
5520     unsigned PFIndexes[4];
5521     for (unsigned i = 0; i != 4; ++i) {
5522       if (ShuffleMask[i] < 0)
5523         PFIndexes[i] = 8;
5524       else
5525         PFIndexes[i] = ShuffleMask[i];
5526     }
5527
5528     // Compute the index in the perfect shuffle table.
5529     unsigned PFTableIndex =
5530       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5531     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5532     unsigned Cost = (PFEntry >> 30);
5533
5534     if (Cost <= 4)
5535       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5536   }
5537
5538   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5539   if (EltSize >= 32) {
5540     // Do the expansion with floating-point types, since that is what the VFP
5541     // registers are defined to use, and since i64 is not legal.
5542     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5543     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5544     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5545     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5546     SmallVector<SDValue, 8> Ops;
5547     for (unsigned i = 0; i < NumElts; ++i) {
5548       if (ShuffleMask[i] < 0)
5549         Ops.push_back(DAG.getUNDEF(EltVT));
5550       else
5551         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5552                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5553                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5554                                                   MVT::i32)));
5555     }
5556     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5557     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5558   }
5559
5560   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5561     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5562
5563   if (VT == MVT::v8i8) {
5564     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5565     if (NewOp.getNode())
5566       return NewOp;
5567   }
5568
5569   return SDValue();
5570 }
5571
5572 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5573   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5574   SDValue Lane = Op.getOperand(2);
5575   if (!isa<ConstantSDNode>(Lane))
5576     return SDValue();
5577
5578   return Op;
5579 }
5580
5581 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5582   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5583   SDValue Lane = Op.getOperand(1);
5584   if (!isa<ConstantSDNode>(Lane))
5585     return SDValue();
5586
5587   SDValue Vec = Op.getOperand(0);
5588   if (Op.getValueType() == MVT::i32 &&
5589       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5590     SDLoc dl(Op);
5591     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5592   }
5593
5594   return Op;
5595 }
5596
5597 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5598   // The only time a CONCAT_VECTORS operation can have legal types is when
5599   // two 64-bit vectors are concatenated to a 128-bit vector.
5600   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5601          "unexpected CONCAT_VECTORS");
5602   SDLoc dl(Op);
5603   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5604   SDValue Op0 = Op.getOperand(0);
5605   SDValue Op1 = Op.getOperand(1);
5606   if (Op0.getOpcode() != ISD::UNDEF)
5607     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5608                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5609                       DAG.getIntPtrConstant(0));
5610   if (Op1.getOpcode() != ISD::UNDEF)
5611     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5612                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5613                       DAG.getIntPtrConstant(1));
5614   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5615 }
5616
5617 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5618 /// element has been zero/sign-extended, depending on the isSigned parameter,
5619 /// from an integer type half its size.
5620 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5621                                    bool isSigned) {
5622   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5623   EVT VT = N->getValueType(0);
5624   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5625     SDNode *BVN = N->getOperand(0).getNode();
5626     if (BVN->getValueType(0) != MVT::v4i32 ||
5627         BVN->getOpcode() != ISD::BUILD_VECTOR)
5628       return false;
5629     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5630     unsigned HiElt = 1 - LoElt;
5631     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5632     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5633     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5634     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5635     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5636       return false;
5637     if (isSigned) {
5638       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5639           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5640         return true;
5641     } else {
5642       if (Hi0->isNullValue() && Hi1->isNullValue())
5643         return true;
5644     }
5645     return false;
5646   }
5647
5648   if (N->getOpcode() != ISD::BUILD_VECTOR)
5649     return false;
5650
5651   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5652     SDNode *Elt = N->getOperand(i).getNode();
5653     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5654       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5655       unsigned HalfSize = EltSize / 2;
5656       if (isSigned) {
5657         if (!isIntN(HalfSize, C->getSExtValue()))
5658           return false;
5659       } else {
5660         if (!isUIntN(HalfSize, C->getZExtValue()))
5661           return false;
5662       }
5663       continue;
5664     }
5665     return false;
5666   }
5667
5668   return true;
5669 }
5670
5671 /// isSignExtended - Check if a node is a vector value that is sign-extended
5672 /// or a constant BUILD_VECTOR with sign-extended elements.
5673 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5674   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5675     return true;
5676   if (isExtendedBUILD_VECTOR(N, DAG, true))
5677     return true;
5678   return false;
5679 }
5680
5681 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5682 /// or a constant BUILD_VECTOR with zero-extended elements.
5683 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5684   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5685     return true;
5686   if (isExtendedBUILD_VECTOR(N, DAG, false))
5687     return true;
5688   return false;
5689 }
5690
5691 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5692   if (OrigVT.getSizeInBits() >= 64)
5693     return OrigVT;
5694
5695   assert(OrigVT.isSimple() && "Expecting a simple value type");
5696
5697   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5698   switch (OrigSimpleTy) {
5699   default: llvm_unreachable("Unexpected Vector Type");
5700   case MVT::v2i8:
5701   case MVT::v2i16:
5702      return MVT::v2i32;
5703   case MVT::v4i8:
5704     return  MVT::v4i16;
5705   }
5706 }
5707
5708 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5709 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5710 /// We insert the required extension here to get the vector to fill a D register.
5711 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5712                                             const EVT &OrigTy,
5713                                             const EVT &ExtTy,
5714                                             unsigned ExtOpcode) {
5715   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5716   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5717   // 64-bits we need to insert a new extension so that it will be 64-bits.
5718   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5719   if (OrigTy.getSizeInBits() >= 64)
5720     return N;
5721
5722   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5723   EVT NewVT = getExtensionTo64Bits(OrigTy);
5724
5725   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5726 }
5727
5728 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5729 /// does not do any sign/zero extension. If the original vector is less
5730 /// than 64 bits, an appropriate extension will be added after the load to
5731 /// reach a total size of 64 bits. We have to add the extension separately
5732 /// because ARM does not have a sign/zero extending load for vectors.
5733 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5734   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5735
5736   // The load already has the right type.
5737   if (ExtendedTy == LD->getMemoryVT())
5738     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5739                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5740                 LD->isNonTemporal(), LD->isInvariant(),
5741                 LD->getAlignment());
5742
5743   // We need to create a zextload/sextload. We cannot just create a load
5744   // followed by a zext/zext node because LowerMUL is also run during normal
5745   // operation legalization where we can't create illegal types.
5746   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5747                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5748                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
5749                         LD->isNonTemporal(), LD->getAlignment());
5750 }
5751
5752 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5753 /// extending load, or BUILD_VECTOR with extended elements, return the
5754 /// unextended value. The unextended vector should be 64 bits so that it can
5755 /// be used as an operand to a VMULL instruction. If the original vector size
5756 /// before extension is less than 64 bits we add a an extension to resize
5757 /// the vector to 64 bits.
5758 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5759   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5760     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5761                                         N->getOperand(0)->getValueType(0),
5762                                         N->getValueType(0),
5763                                         N->getOpcode());
5764
5765   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5766     return SkipLoadExtensionForVMULL(LD, DAG);
5767
5768   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5769   // have been legalized as a BITCAST from v4i32.
5770   if (N->getOpcode() == ISD::BITCAST) {
5771     SDNode *BVN = N->getOperand(0).getNode();
5772     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5773            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5774     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5775     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5776                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5777   }
5778   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5779   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5780   EVT VT = N->getValueType(0);
5781   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5782   unsigned NumElts = VT.getVectorNumElements();
5783   MVT TruncVT = MVT::getIntegerVT(EltSize);
5784   SmallVector<SDValue, 8> Ops;
5785   for (unsigned i = 0; i != NumElts; ++i) {
5786     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5787     const APInt &CInt = C->getAPIntValue();
5788     // Element types smaller than 32 bits are not legal, so use i32 elements.
5789     // The values are implicitly truncated so sext vs. zext doesn't matter.
5790     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5791   }
5792   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5793                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5794 }
5795
5796 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5797   unsigned Opcode = N->getOpcode();
5798   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5799     SDNode *N0 = N->getOperand(0).getNode();
5800     SDNode *N1 = N->getOperand(1).getNode();
5801     return N0->hasOneUse() && N1->hasOneUse() &&
5802       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5803   }
5804   return false;
5805 }
5806
5807 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5808   unsigned Opcode = N->getOpcode();
5809   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5810     SDNode *N0 = N->getOperand(0).getNode();
5811     SDNode *N1 = N->getOperand(1).getNode();
5812     return N0->hasOneUse() && N1->hasOneUse() &&
5813       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5814   }
5815   return false;
5816 }
5817
5818 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5819   // Multiplications are only custom-lowered for 128-bit vectors so that
5820   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5821   EVT VT = Op.getValueType();
5822   assert(VT.is128BitVector() && VT.isInteger() &&
5823          "unexpected type for custom-lowering ISD::MUL");
5824   SDNode *N0 = Op.getOperand(0).getNode();
5825   SDNode *N1 = Op.getOperand(1).getNode();
5826   unsigned NewOpc = 0;
5827   bool isMLA = false;
5828   bool isN0SExt = isSignExtended(N0, DAG);
5829   bool isN1SExt = isSignExtended(N1, DAG);
5830   if (isN0SExt && isN1SExt)
5831     NewOpc = ARMISD::VMULLs;
5832   else {
5833     bool isN0ZExt = isZeroExtended(N0, DAG);
5834     bool isN1ZExt = isZeroExtended(N1, DAG);
5835     if (isN0ZExt && isN1ZExt)
5836       NewOpc = ARMISD::VMULLu;
5837     else if (isN1SExt || isN1ZExt) {
5838       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5839       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5840       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5841         NewOpc = ARMISD::VMULLs;
5842         isMLA = true;
5843       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5844         NewOpc = ARMISD::VMULLu;
5845         isMLA = true;
5846       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5847         std::swap(N0, N1);
5848         NewOpc = ARMISD::VMULLu;
5849         isMLA = true;
5850       }
5851     }
5852
5853     if (!NewOpc) {
5854       if (VT == MVT::v2i64)
5855         // Fall through to expand this.  It is not legal.
5856         return SDValue();
5857       else
5858         // Other vector multiplications are legal.
5859         return Op;
5860     }
5861   }
5862
5863   // Legalize to a VMULL instruction.
5864   SDLoc DL(Op);
5865   SDValue Op0;
5866   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5867   if (!isMLA) {
5868     Op0 = SkipExtensionForVMULL(N0, DAG);
5869     assert(Op0.getValueType().is64BitVector() &&
5870            Op1.getValueType().is64BitVector() &&
5871            "unexpected types for extended operands to VMULL");
5872     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5873   }
5874
5875   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5876   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5877   //   vmull q0, d4, d6
5878   //   vmlal q0, d5, d6
5879   // is faster than
5880   //   vaddl q0, d4, d5
5881   //   vmovl q1, d6
5882   //   vmul  q0, q0, q1
5883   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5884   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5885   EVT Op1VT = Op1.getValueType();
5886   return DAG.getNode(N0->getOpcode(), DL, VT,
5887                      DAG.getNode(NewOpc, DL, VT,
5888                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5889                      DAG.getNode(NewOpc, DL, VT,
5890                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5891 }
5892
5893 static SDValue
5894 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5895   // Convert to float
5896   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5897   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5898   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5899   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5900   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5901   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5902   // Get reciprocal estimate.
5903   // float4 recip = vrecpeq_f32(yf);
5904   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5905                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5906   // Because char has a smaller range than uchar, we can actually get away
5907   // without any newton steps.  This requires that we use a weird bias
5908   // of 0xb000, however (again, this has been exhaustively tested).
5909   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5910   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5911   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5912   Y = DAG.getConstant(0xb000, MVT::i32);
5913   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5914   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5915   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5916   // Convert back to short.
5917   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5918   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5919   return X;
5920 }
5921
5922 static SDValue
5923 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5924   SDValue N2;
5925   // Convert to float.
5926   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5927   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5928   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5929   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5930   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5931   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5932
5933   // Use reciprocal estimate and one refinement step.
5934   // float4 recip = vrecpeq_f32(yf);
5935   // recip *= vrecpsq_f32(yf, recip);
5936   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5937                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5938   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5939                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5940                    N1, N2);
5941   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5942   // Because short has a smaller range than ushort, we can actually get away
5943   // with only a single newton step.  This requires that we use a weird bias
5944   // of 89, however (again, this has been exhaustively tested).
5945   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5946   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5947   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5948   N1 = DAG.getConstant(0x89, MVT::i32);
5949   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5950   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5951   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5952   // Convert back to integer and return.
5953   // return vmovn_s32(vcvt_s32_f32(result));
5954   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5955   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5956   return N0;
5957 }
5958
5959 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5960   EVT VT = Op.getValueType();
5961   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5962          "unexpected type for custom-lowering ISD::SDIV");
5963
5964   SDLoc dl(Op);
5965   SDValue N0 = Op.getOperand(0);
5966   SDValue N1 = Op.getOperand(1);
5967   SDValue N2, N3;
5968
5969   if (VT == MVT::v8i8) {
5970     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5971     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5972
5973     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5974                      DAG.getIntPtrConstant(4));
5975     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5976                      DAG.getIntPtrConstant(4));
5977     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5978                      DAG.getIntPtrConstant(0));
5979     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5980                      DAG.getIntPtrConstant(0));
5981
5982     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5983     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5984
5985     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5986     N0 = LowerCONCAT_VECTORS(N0, DAG);
5987
5988     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5989     return N0;
5990   }
5991   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5992 }
5993
5994 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5995   EVT VT = Op.getValueType();
5996   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5997          "unexpected type for custom-lowering ISD::UDIV");
5998
5999   SDLoc dl(Op);
6000   SDValue N0 = Op.getOperand(0);
6001   SDValue N1 = Op.getOperand(1);
6002   SDValue N2, N3;
6003
6004   if (VT == MVT::v8i8) {
6005     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6006     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6007
6008     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6009                      DAG.getIntPtrConstant(4));
6010     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6011                      DAG.getIntPtrConstant(4));
6012     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6013                      DAG.getIntPtrConstant(0));
6014     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6015                      DAG.getIntPtrConstant(0));
6016
6017     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6018     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6019
6020     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6021     N0 = LowerCONCAT_VECTORS(N0, DAG);
6022
6023     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6024                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
6025                      N0);
6026     return N0;
6027   }
6028
6029   // v4i16 sdiv ... Convert to float.
6030   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6031   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6032   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6033   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6034   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6035   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6036
6037   // Use reciprocal estimate and two refinement steps.
6038   // float4 recip = vrecpeq_f32(yf);
6039   // recip *= vrecpsq_f32(yf, recip);
6040   // recip *= vrecpsq_f32(yf, recip);
6041   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6042                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6043   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6044                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6045                    BN1, N2);
6046   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6047   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6048                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6049                    BN1, N2);
6050   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6051   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6052   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6053   // and that it will never cause us to return an answer too large).
6054   // float4 result = as_float4(as_int4(xf*recip) + 2);
6055   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6056   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6057   N1 = DAG.getConstant(2, MVT::i32);
6058   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6059   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6060   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6061   // Convert back to integer and return.
6062   // return vmovn_u32(vcvt_s32_f32(result));
6063   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6064   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6065   return N0;
6066 }
6067
6068 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6069   EVT VT = Op.getNode()->getValueType(0);
6070   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6071
6072   unsigned Opc;
6073   bool ExtraOp = false;
6074   switch (Op.getOpcode()) {
6075   default: llvm_unreachable("Invalid code");
6076   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6077   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6078   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6079   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6080   }
6081
6082   if (!ExtraOp)
6083     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6084                        Op.getOperand(1));
6085   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6086                      Op.getOperand(1), Op.getOperand(2));
6087 }
6088
6089 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6090   assert(Subtarget->isTargetDarwin());
6091
6092   // For iOS, we want to call an alternative entry point: __sincos_stret,
6093   // return values are passed via sret.
6094   SDLoc dl(Op);
6095   SDValue Arg = Op.getOperand(0);
6096   EVT ArgVT = Arg.getValueType();
6097   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6098
6099   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6100   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6101
6102   // Pair of floats / doubles used to pass the result.
6103   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6104
6105   // Create stack object for sret.
6106   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6107   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6108   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6109   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6110
6111   ArgListTy Args;
6112   ArgListEntry Entry;
6113
6114   Entry.Node = SRet;
6115   Entry.Ty = RetTy->getPointerTo();
6116   Entry.isSExt = false;
6117   Entry.isZExt = false;
6118   Entry.isSRet = true;
6119   Args.push_back(Entry);
6120
6121   Entry.Node = Arg;
6122   Entry.Ty = ArgTy;
6123   Entry.isSExt = false;
6124   Entry.isZExt = false;
6125   Args.push_back(Entry);
6126
6127   const char *LibcallName  = (ArgVT == MVT::f64)
6128   ? "__sincos_stret" : "__sincosf_stret";
6129   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6130
6131   TargetLowering::CallLoweringInfo CLI(DAG);
6132   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6133     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6134                std::move(Args), 0)
6135     .setDiscardResult();
6136
6137   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6138
6139   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6140                                 MachinePointerInfo(), false, false, false, 0);
6141
6142   // Address of cos field.
6143   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6144                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6145   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6146                                 MachinePointerInfo(), false, false, false, 0);
6147
6148   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6149   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6150                      LoadSin.getValue(0), LoadCos.getValue(0));
6151 }
6152
6153 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6154   // Monotonic load/store is legal for all targets
6155   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6156     return Op;
6157
6158   // Acquire/Release load/store is not legal for targets without a
6159   // dmb or equivalent available.
6160   return SDValue();
6161 }
6162
6163 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6164                                     SmallVectorImpl<SDValue> &Results,
6165                                     SelectionDAG &DAG,
6166                                     const ARMSubtarget *Subtarget) {
6167   SDLoc DL(N);
6168   SDValue Cycles32, OutChain;
6169
6170   if (Subtarget->hasPerfMon()) {
6171     // Under Power Management extensions, the cycle-count is:
6172     //    mrc p15, #0, <Rt>, c9, c13, #0
6173     SDValue Ops[] = { N->getOperand(0), // Chain
6174                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6175                       DAG.getConstant(15, MVT::i32),
6176                       DAG.getConstant(0, MVT::i32),
6177                       DAG.getConstant(9, MVT::i32),
6178                       DAG.getConstant(13, MVT::i32),
6179                       DAG.getConstant(0, MVT::i32)
6180     };
6181
6182     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6183                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6184     OutChain = Cycles32.getValue(1);
6185   } else {
6186     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6187     // there are older ARM CPUs that have implementation-specific ways of
6188     // obtaining this information (FIXME!).
6189     Cycles32 = DAG.getConstant(0, MVT::i32);
6190     OutChain = DAG.getEntryNode();
6191   }
6192
6193
6194   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6195                                  Cycles32, DAG.getConstant(0, MVT::i32));
6196   Results.push_back(Cycles64);
6197   Results.push_back(OutChain);
6198 }
6199
6200 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6201   switch (Op.getOpcode()) {
6202   default: llvm_unreachable("Don't know how to custom lower this!");
6203   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6204   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6205   case ISD::GlobalAddress:
6206     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6207     default: llvm_unreachable("unknown object format");
6208     case Triple::COFF:
6209       return LowerGlobalAddressWindows(Op, DAG);
6210     case Triple::ELF:
6211       return LowerGlobalAddressELF(Op, DAG);
6212     case Triple::MachO:
6213       return LowerGlobalAddressDarwin(Op, DAG);
6214     }
6215   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6216   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6217   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6218   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6219   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6220   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6221   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6222   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6223   case ISD::SINT_TO_FP:
6224   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6225   case ISD::FP_TO_SINT:
6226   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6227   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6228   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6229   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6230   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6231   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6232   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6233   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6234                                                                Subtarget);
6235   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6236   case ISD::SHL:
6237   case ISD::SRL:
6238   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6239   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6240   case ISD::SRL_PARTS:
6241   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6242   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6243   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6244   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6245   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6246   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6247   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6248   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6249   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6250   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6251   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6252   case ISD::MUL:           return LowerMUL(Op, DAG);
6253   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6254   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6255   case ISD::ADDC:
6256   case ISD::ADDE:
6257   case ISD::SUBC:
6258   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6259   case ISD::SADDO:
6260   case ISD::UADDO:
6261   case ISD::SSUBO:
6262   case ISD::USUBO:
6263     return LowerXALUO(Op, DAG);
6264   case ISD::ATOMIC_LOAD:
6265   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6266   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6267   case ISD::SDIVREM:
6268   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6269   case ISD::DYNAMIC_STACKALLOC:
6270     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6271       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6272     llvm_unreachable("Don't know how to custom lower this!");
6273   }
6274 }
6275
6276 /// ReplaceNodeResults - Replace the results of node with an illegal result
6277 /// type with new values built out of custom code.
6278 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6279                                            SmallVectorImpl<SDValue>&Results,
6280                                            SelectionDAG &DAG) const {
6281   SDValue Res;
6282   switch (N->getOpcode()) {
6283   default:
6284     llvm_unreachable("Don't know how to custom expand this!");
6285   case ISD::BITCAST:
6286     Res = ExpandBITCAST(N, DAG);
6287     break;
6288   case ISD::SRL:
6289   case ISD::SRA:
6290     Res = Expand64BitShift(N, DAG, Subtarget);
6291     break;
6292   case ISD::READCYCLECOUNTER:
6293     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6294     return;
6295   }
6296   if (Res.getNode())
6297     Results.push_back(Res);
6298 }
6299
6300 //===----------------------------------------------------------------------===//
6301 //                           ARM Scheduler Hooks
6302 //===----------------------------------------------------------------------===//
6303
6304 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6305 /// registers the function context.
6306 void ARMTargetLowering::
6307 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6308                        MachineBasicBlock *DispatchBB, int FI) const {
6309   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6310   DebugLoc dl = MI->getDebugLoc();
6311   MachineFunction *MF = MBB->getParent();
6312   MachineRegisterInfo *MRI = &MF->getRegInfo();
6313   MachineConstantPool *MCP = MF->getConstantPool();
6314   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6315   const Function *F = MF->getFunction();
6316
6317   bool isThumb = Subtarget->isThumb();
6318   bool isThumb2 = Subtarget->isThumb2();
6319
6320   unsigned PCLabelId = AFI->createPICLabelUId();
6321   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6322   ARMConstantPoolValue *CPV =
6323     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6324   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6325
6326   const TargetRegisterClass *TRC = isThumb ?
6327     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6328     (const TargetRegisterClass*)&ARM::GPRRegClass;
6329
6330   // Grab constant pool and fixed stack memory operands.
6331   MachineMemOperand *CPMMO =
6332     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6333                              MachineMemOperand::MOLoad, 4, 4);
6334
6335   MachineMemOperand *FIMMOSt =
6336     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6337                              MachineMemOperand::MOStore, 4, 4);
6338
6339   // Load the address of the dispatch MBB into the jump buffer.
6340   if (isThumb2) {
6341     // Incoming value: jbuf
6342     //   ldr.n  r5, LCPI1_1
6343     //   orr    r5, r5, #1
6344     //   add    r5, pc
6345     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6346     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6347     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6348                    .addConstantPoolIndex(CPI)
6349                    .addMemOperand(CPMMO));
6350     // Set the low bit because of thumb mode.
6351     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6352     AddDefaultCC(
6353       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6354                      .addReg(NewVReg1, RegState::Kill)
6355                      .addImm(0x01)));
6356     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6357     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6358       .addReg(NewVReg2, RegState::Kill)
6359       .addImm(PCLabelId);
6360     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6361                    .addReg(NewVReg3, RegState::Kill)
6362                    .addFrameIndex(FI)
6363                    .addImm(36)  // &jbuf[1] :: pc
6364                    .addMemOperand(FIMMOSt));
6365   } else if (isThumb) {
6366     // Incoming value: jbuf
6367     //   ldr.n  r1, LCPI1_4
6368     //   add    r1, pc
6369     //   mov    r2, #1
6370     //   orrs   r1, r2
6371     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6372     //   str    r1, [r2]
6373     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6374     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6375                    .addConstantPoolIndex(CPI)
6376                    .addMemOperand(CPMMO));
6377     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6378     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6379       .addReg(NewVReg1, RegState::Kill)
6380       .addImm(PCLabelId);
6381     // Set the low bit because of thumb mode.
6382     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6383     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6384                    .addReg(ARM::CPSR, RegState::Define)
6385                    .addImm(1));
6386     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6387     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6388                    .addReg(ARM::CPSR, RegState::Define)
6389                    .addReg(NewVReg2, RegState::Kill)
6390                    .addReg(NewVReg3, RegState::Kill));
6391     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6392     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6393                    .addFrameIndex(FI)
6394                    .addImm(36)); // &jbuf[1] :: pc
6395     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6396                    .addReg(NewVReg4, RegState::Kill)
6397                    .addReg(NewVReg5, RegState::Kill)
6398                    .addImm(0)
6399                    .addMemOperand(FIMMOSt));
6400   } else {
6401     // Incoming value: jbuf
6402     //   ldr  r1, LCPI1_1
6403     //   add  r1, pc, r1
6404     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6405     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6406     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6407                    .addConstantPoolIndex(CPI)
6408                    .addImm(0)
6409                    .addMemOperand(CPMMO));
6410     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6411     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6412                    .addReg(NewVReg1, RegState::Kill)
6413                    .addImm(PCLabelId));
6414     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6415                    .addReg(NewVReg2, RegState::Kill)
6416                    .addFrameIndex(FI)
6417                    .addImm(36)  // &jbuf[1] :: pc
6418                    .addMemOperand(FIMMOSt));
6419   }
6420 }
6421
6422 MachineBasicBlock *ARMTargetLowering::
6423 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6424   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6425   DebugLoc dl = MI->getDebugLoc();
6426   MachineFunction *MF = MBB->getParent();
6427   MachineRegisterInfo *MRI = &MF->getRegInfo();
6428   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6429   MachineFrameInfo *MFI = MF->getFrameInfo();
6430   int FI = MFI->getFunctionContextIndex();
6431
6432   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6433     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6434     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6435
6436   // Get a mapping of the call site numbers to all of the landing pads they're
6437   // associated with.
6438   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6439   unsigned MaxCSNum = 0;
6440   MachineModuleInfo &MMI = MF->getMMI();
6441   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6442        ++BB) {
6443     if (!BB->isLandingPad()) continue;
6444
6445     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6446     // pad.
6447     for (MachineBasicBlock::iterator
6448            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6449       if (!II->isEHLabel()) continue;
6450
6451       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6452       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6453
6454       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6455       for (SmallVectorImpl<unsigned>::iterator
6456              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6457            CSI != CSE; ++CSI) {
6458         CallSiteNumToLPad[*CSI].push_back(BB);
6459         MaxCSNum = std::max(MaxCSNum, *CSI);
6460       }
6461       break;
6462     }
6463   }
6464
6465   // Get an ordered list of the machine basic blocks for the jump table.
6466   std::vector<MachineBasicBlock*> LPadList;
6467   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6468   LPadList.reserve(CallSiteNumToLPad.size());
6469   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6470     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6471     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6472            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6473       LPadList.push_back(*II);
6474       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6475     }
6476   }
6477
6478   assert(!LPadList.empty() &&
6479          "No landing pad destinations for the dispatch jump table!");
6480
6481   // Create the jump table and associated information.
6482   MachineJumpTableInfo *JTI =
6483     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6484   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6485   unsigned UId = AFI->createJumpTableUId();
6486   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6487
6488   // Create the MBBs for the dispatch code.
6489
6490   // Shove the dispatch's address into the return slot in the function context.
6491   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6492   DispatchBB->setIsLandingPad();
6493
6494   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6495   unsigned trap_opcode;
6496   if (Subtarget->isThumb())
6497     trap_opcode = ARM::tTRAP;
6498   else
6499     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6500
6501   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6502   DispatchBB->addSuccessor(TrapBB);
6503
6504   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6505   DispatchBB->addSuccessor(DispContBB);
6506
6507   // Insert and MBBs.
6508   MF->insert(MF->end(), DispatchBB);
6509   MF->insert(MF->end(), DispContBB);
6510   MF->insert(MF->end(), TrapBB);
6511
6512   // Insert code into the entry block that creates and registers the function
6513   // context.
6514   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6515
6516   MachineMemOperand *FIMMOLd =
6517     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6518                              MachineMemOperand::MOLoad |
6519                              MachineMemOperand::MOVolatile, 4, 4);
6520
6521   MachineInstrBuilder MIB;
6522   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6523
6524   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6525   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6526
6527   // Add a register mask with no preserved registers.  This results in all
6528   // registers being marked as clobbered.
6529   MIB.addRegMask(RI.getNoPreservedMask());
6530
6531   unsigned NumLPads = LPadList.size();
6532   if (Subtarget->isThumb2()) {
6533     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6534     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6535                    .addFrameIndex(FI)
6536                    .addImm(4)
6537                    .addMemOperand(FIMMOLd));
6538
6539     if (NumLPads < 256) {
6540       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6541                      .addReg(NewVReg1)
6542                      .addImm(LPadList.size()));
6543     } else {
6544       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6545       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6546                      .addImm(NumLPads & 0xFFFF));
6547
6548       unsigned VReg2 = VReg1;
6549       if ((NumLPads & 0xFFFF0000) != 0) {
6550         VReg2 = MRI->createVirtualRegister(TRC);
6551         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6552                        .addReg(VReg1)
6553                        .addImm(NumLPads >> 16));
6554       }
6555
6556       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6557                      .addReg(NewVReg1)
6558                      .addReg(VReg2));
6559     }
6560
6561     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6562       .addMBB(TrapBB)
6563       .addImm(ARMCC::HI)
6564       .addReg(ARM::CPSR);
6565
6566     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6567     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6568                    .addJumpTableIndex(MJTI)
6569                    .addImm(UId));
6570
6571     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6572     AddDefaultCC(
6573       AddDefaultPred(
6574         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6575         .addReg(NewVReg3, RegState::Kill)
6576         .addReg(NewVReg1)
6577         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6578
6579     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6580       .addReg(NewVReg4, RegState::Kill)
6581       .addReg(NewVReg1)
6582       .addJumpTableIndex(MJTI)
6583       .addImm(UId);
6584   } else if (Subtarget->isThumb()) {
6585     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6586     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6587                    .addFrameIndex(FI)
6588                    .addImm(1)
6589                    .addMemOperand(FIMMOLd));
6590
6591     if (NumLPads < 256) {
6592       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6593                      .addReg(NewVReg1)
6594                      .addImm(NumLPads));
6595     } else {
6596       MachineConstantPool *ConstantPool = MF->getConstantPool();
6597       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6598       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6599
6600       // MachineConstantPool wants an explicit alignment.
6601       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6602       if (Align == 0)
6603         Align = getDataLayout()->getTypeAllocSize(C->getType());
6604       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6605
6606       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6607       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6608                      .addReg(VReg1, RegState::Define)
6609                      .addConstantPoolIndex(Idx));
6610       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6611                      .addReg(NewVReg1)
6612                      .addReg(VReg1));
6613     }
6614
6615     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6616       .addMBB(TrapBB)
6617       .addImm(ARMCC::HI)
6618       .addReg(ARM::CPSR);
6619
6620     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6621     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6622                    .addReg(ARM::CPSR, RegState::Define)
6623                    .addReg(NewVReg1)
6624                    .addImm(2));
6625
6626     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6627     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6628                    .addJumpTableIndex(MJTI)
6629                    .addImm(UId));
6630
6631     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6632     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6633                    .addReg(ARM::CPSR, RegState::Define)
6634                    .addReg(NewVReg2, RegState::Kill)
6635                    .addReg(NewVReg3));
6636
6637     MachineMemOperand *JTMMOLd =
6638       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6639                                MachineMemOperand::MOLoad, 4, 4);
6640
6641     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6642     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6643                    .addReg(NewVReg4, RegState::Kill)
6644                    .addImm(0)
6645                    .addMemOperand(JTMMOLd));
6646
6647     unsigned NewVReg6 = NewVReg5;
6648     if (RelocM == Reloc::PIC_) {
6649       NewVReg6 = MRI->createVirtualRegister(TRC);
6650       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6651                      .addReg(ARM::CPSR, RegState::Define)
6652                      .addReg(NewVReg5, RegState::Kill)
6653                      .addReg(NewVReg3));
6654     }
6655
6656     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6657       .addReg(NewVReg6, RegState::Kill)
6658       .addJumpTableIndex(MJTI)
6659       .addImm(UId);
6660   } else {
6661     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6662     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6663                    .addFrameIndex(FI)
6664                    .addImm(4)
6665                    .addMemOperand(FIMMOLd));
6666
6667     if (NumLPads < 256) {
6668       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6669                      .addReg(NewVReg1)
6670                      .addImm(NumLPads));
6671     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6672       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6673       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6674                      .addImm(NumLPads & 0xFFFF));
6675
6676       unsigned VReg2 = VReg1;
6677       if ((NumLPads & 0xFFFF0000) != 0) {
6678         VReg2 = MRI->createVirtualRegister(TRC);
6679         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6680                        .addReg(VReg1)
6681                        .addImm(NumLPads >> 16));
6682       }
6683
6684       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6685                      .addReg(NewVReg1)
6686                      .addReg(VReg2));
6687     } else {
6688       MachineConstantPool *ConstantPool = MF->getConstantPool();
6689       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6690       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6691
6692       // MachineConstantPool wants an explicit alignment.
6693       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6694       if (Align == 0)
6695         Align = getDataLayout()->getTypeAllocSize(C->getType());
6696       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6697
6698       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6699       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6700                      .addReg(VReg1, RegState::Define)
6701                      .addConstantPoolIndex(Idx)
6702                      .addImm(0));
6703       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6704                      .addReg(NewVReg1)
6705                      .addReg(VReg1, RegState::Kill));
6706     }
6707
6708     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6709       .addMBB(TrapBB)
6710       .addImm(ARMCC::HI)
6711       .addReg(ARM::CPSR);
6712
6713     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6714     AddDefaultCC(
6715       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6716                      .addReg(NewVReg1)
6717                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6718     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6719     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6720                    .addJumpTableIndex(MJTI)
6721                    .addImm(UId));
6722
6723     MachineMemOperand *JTMMOLd =
6724       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6725                                MachineMemOperand::MOLoad, 4, 4);
6726     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6727     AddDefaultPred(
6728       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6729       .addReg(NewVReg3, RegState::Kill)
6730       .addReg(NewVReg4)
6731       .addImm(0)
6732       .addMemOperand(JTMMOLd));
6733
6734     if (RelocM == Reloc::PIC_) {
6735       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6736         .addReg(NewVReg5, RegState::Kill)
6737         .addReg(NewVReg4)
6738         .addJumpTableIndex(MJTI)
6739         .addImm(UId);
6740     } else {
6741       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6742         .addReg(NewVReg5, RegState::Kill)
6743         .addJumpTableIndex(MJTI)
6744         .addImm(UId);
6745     }
6746   }
6747
6748   // Add the jump table entries as successors to the MBB.
6749   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6750   for (std::vector<MachineBasicBlock*>::iterator
6751          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6752     MachineBasicBlock *CurMBB = *I;
6753     if (SeenMBBs.insert(CurMBB))
6754       DispContBB->addSuccessor(CurMBB);
6755   }
6756
6757   // N.B. the order the invoke BBs are processed in doesn't matter here.
6758   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6759   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6760   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6761          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6762     MachineBasicBlock *BB = *I;
6763
6764     // Remove the landing pad successor from the invoke block and replace it
6765     // with the new dispatch block.
6766     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6767                                                   BB->succ_end());
6768     while (!Successors.empty()) {
6769       MachineBasicBlock *SMBB = Successors.pop_back_val();
6770       if (SMBB->isLandingPad()) {
6771         BB->removeSuccessor(SMBB);
6772         MBBLPads.push_back(SMBB);
6773       }
6774     }
6775
6776     BB->addSuccessor(DispatchBB);
6777
6778     // Find the invoke call and mark all of the callee-saved registers as
6779     // 'implicit defined' so that they're spilled. This prevents code from
6780     // moving instructions to before the EH block, where they will never be
6781     // executed.
6782     for (MachineBasicBlock::reverse_iterator
6783            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6784       if (!II->isCall()) continue;
6785
6786       DenseMap<unsigned, bool> DefRegs;
6787       for (MachineInstr::mop_iterator
6788              OI = II->operands_begin(), OE = II->operands_end();
6789            OI != OE; ++OI) {
6790         if (!OI->isReg()) continue;
6791         DefRegs[OI->getReg()] = true;
6792       }
6793
6794       MachineInstrBuilder MIB(*MF, &*II);
6795
6796       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6797         unsigned Reg = SavedRegs[i];
6798         if (Subtarget->isThumb2() &&
6799             !ARM::tGPRRegClass.contains(Reg) &&
6800             !ARM::hGPRRegClass.contains(Reg))
6801           continue;
6802         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6803           continue;
6804         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6805           continue;
6806         if (!DefRegs[Reg])
6807           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6808       }
6809
6810       break;
6811     }
6812   }
6813
6814   // Mark all former landing pads as non-landing pads. The dispatch is the only
6815   // landing pad now.
6816   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6817          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6818     (*I)->setIsLandingPad(false);
6819
6820   // The instruction is gone now.
6821   MI->eraseFromParent();
6822
6823   return MBB;
6824 }
6825
6826 static
6827 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6828   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6829        E = MBB->succ_end(); I != E; ++I)
6830     if (*I != Succ)
6831       return *I;
6832   llvm_unreachable("Expecting a BB with two successors!");
6833 }
6834
6835 /// Return the load opcode for a given load size. If load size >= 8,
6836 /// neon opcode will be returned.
6837 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6838   if (LdSize >= 8)
6839     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6840                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6841   if (IsThumb1)
6842     return LdSize == 4 ? ARM::tLDRi
6843                        : LdSize == 2 ? ARM::tLDRHi
6844                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6845   if (IsThumb2)
6846     return LdSize == 4 ? ARM::t2LDR_POST
6847                        : LdSize == 2 ? ARM::t2LDRH_POST
6848                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6849   return LdSize == 4 ? ARM::LDR_POST_IMM
6850                      : LdSize == 2 ? ARM::LDRH_POST
6851                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6852 }
6853
6854 /// Return the store opcode for a given store size. If store size >= 8,
6855 /// neon opcode will be returned.
6856 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6857   if (StSize >= 8)
6858     return StSize == 16 ? ARM::VST1q32wb_fixed
6859                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6860   if (IsThumb1)
6861     return StSize == 4 ? ARM::tSTRi
6862                        : StSize == 2 ? ARM::tSTRHi
6863                                      : StSize == 1 ? ARM::tSTRBi : 0;
6864   if (IsThumb2)
6865     return StSize == 4 ? ARM::t2STR_POST
6866                        : StSize == 2 ? ARM::t2STRH_POST
6867                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6868   return StSize == 4 ? ARM::STR_POST_IMM
6869                      : StSize == 2 ? ARM::STRH_POST
6870                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6871 }
6872
6873 /// Emit a post-increment load operation with given size. The instructions
6874 /// will be added to BB at Pos.
6875 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6876                        const TargetInstrInfo *TII, DebugLoc dl,
6877                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6878                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6879   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6880   assert(LdOpc != 0 && "Should have a load opcode");
6881   if (LdSize >= 8) {
6882     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6883                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6884                        .addImm(0));
6885   } else if (IsThumb1) {
6886     // load + update AddrIn
6887     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6888                        .addReg(AddrIn).addImm(0));
6889     MachineInstrBuilder MIB =
6890         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6891     MIB = AddDefaultT1CC(MIB);
6892     MIB.addReg(AddrIn).addImm(LdSize);
6893     AddDefaultPred(MIB);
6894   } else if (IsThumb2) {
6895     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6896                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6897                        .addImm(LdSize));
6898   } else { // arm
6899     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6900                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6901                        .addReg(0).addImm(LdSize));
6902   }
6903 }
6904
6905 /// Emit a post-increment store operation with given size. The instructions
6906 /// will be added to BB at Pos.
6907 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6908                        const TargetInstrInfo *TII, DebugLoc dl,
6909                        unsigned StSize, unsigned Data, unsigned AddrIn,
6910                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6911   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6912   assert(StOpc != 0 && "Should have a store opcode");
6913   if (StSize >= 8) {
6914     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6915                        .addReg(AddrIn).addImm(0).addReg(Data));
6916   } else if (IsThumb1) {
6917     // store + update AddrIn
6918     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6919                        .addReg(AddrIn).addImm(0));
6920     MachineInstrBuilder MIB =
6921         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6922     MIB = AddDefaultT1CC(MIB);
6923     MIB.addReg(AddrIn).addImm(StSize);
6924     AddDefaultPred(MIB);
6925   } else if (IsThumb2) {
6926     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6927                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6928   } else { // arm
6929     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6930                        .addReg(Data).addReg(AddrIn).addReg(0)
6931                        .addImm(StSize));
6932   }
6933 }
6934
6935 MachineBasicBlock *
6936 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6937                                    MachineBasicBlock *BB) const {
6938   // This pseudo instruction has 3 operands: dst, src, size
6939   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6940   // Otherwise, we will generate unrolled scalar copies.
6941   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6942   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6943   MachineFunction::iterator It = BB;
6944   ++It;
6945
6946   unsigned dest = MI->getOperand(0).getReg();
6947   unsigned src = MI->getOperand(1).getReg();
6948   unsigned SizeVal = MI->getOperand(2).getImm();
6949   unsigned Align = MI->getOperand(3).getImm();
6950   DebugLoc dl = MI->getDebugLoc();
6951
6952   MachineFunction *MF = BB->getParent();
6953   MachineRegisterInfo &MRI = MF->getRegInfo();
6954   unsigned UnitSize = 0;
6955   const TargetRegisterClass *TRC = nullptr;
6956   const TargetRegisterClass *VecTRC = nullptr;
6957
6958   bool IsThumb1 = Subtarget->isThumb1Only();
6959   bool IsThumb2 = Subtarget->isThumb2();
6960
6961   if (Align & 1) {
6962     UnitSize = 1;
6963   } else if (Align & 2) {
6964     UnitSize = 2;
6965   } else {
6966     // Check whether we can use NEON instructions.
6967     if (!MF->getFunction()->getAttributes().
6968           hasAttribute(AttributeSet::FunctionIndex,
6969                        Attribute::NoImplicitFloat) &&
6970         Subtarget->hasNEON()) {
6971       if ((Align % 16 == 0) && SizeVal >= 16)
6972         UnitSize = 16;
6973       else if ((Align % 8 == 0) && SizeVal >= 8)
6974         UnitSize = 8;
6975     }
6976     // Can't use NEON instructions.
6977     if (UnitSize == 0)
6978       UnitSize = 4;
6979   }
6980
6981   // Select the correct opcode and register class for unit size load/store
6982   bool IsNeon = UnitSize >= 8;
6983   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6984                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6985   if (IsNeon)
6986     VecTRC = UnitSize == 16
6987                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6988                  : UnitSize == 8
6989                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6990                        : nullptr;
6991
6992   unsigned BytesLeft = SizeVal % UnitSize;
6993   unsigned LoopSize = SizeVal - BytesLeft;
6994
6995   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6996     // Use LDR and STR to copy.
6997     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6998     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6999     unsigned srcIn = src;
7000     unsigned destIn = dest;
7001     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7002       unsigned srcOut = MRI.createVirtualRegister(TRC);
7003       unsigned destOut = MRI.createVirtualRegister(TRC);
7004       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7005       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7006                  IsThumb1, IsThumb2);
7007       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7008                  IsThumb1, IsThumb2);
7009       srcIn = srcOut;
7010       destIn = destOut;
7011     }
7012
7013     // Handle the leftover bytes with LDRB and STRB.
7014     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7015     // [destOut] = STRB_POST(scratch, destIn, 1)
7016     for (unsigned i = 0; i < BytesLeft; i++) {
7017       unsigned srcOut = MRI.createVirtualRegister(TRC);
7018       unsigned destOut = MRI.createVirtualRegister(TRC);
7019       unsigned scratch = MRI.createVirtualRegister(TRC);
7020       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7021                  IsThumb1, IsThumb2);
7022       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7023                  IsThumb1, IsThumb2);
7024       srcIn = srcOut;
7025       destIn = destOut;
7026     }
7027     MI->eraseFromParent();   // The instruction is gone now.
7028     return BB;
7029   }
7030
7031   // Expand the pseudo op to a loop.
7032   // thisMBB:
7033   //   ...
7034   //   movw varEnd, # --> with thumb2
7035   //   movt varEnd, #
7036   //   ldrcp varEnd, idx --> without thumb2
7037   //   fallthrough --> loopMBB
7038   // loopMBB:
7039   //   PHI varPhi, varEnd, varLoop
7040   //   PHI srcPhi, src, srcLoop
7041   //   PHI destPhi, dst, destLoop
7042   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7043   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7044   //   subs varLoop, varPhi, #UnitSize
7045   //   bne loopMBB
7046   //   fallthrough --> exitMBB
7047   // exitMBB:
7048   //   epilogue to handle left-over bytes
7049   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7050   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7051   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7052   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7053   MF->insert(It, loopMBB);
7054   MF->insert(It, exitMBB);
7055
7056   // Transfer the remainder of BB and its successor edges to exitMBB.
7057   exitMBB->splice(exitMBB->begin(), BB,
7058                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7059   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7060
7061   // Load an immediate to varEnd.
7062   unsigned varEnd = MRI.createVirtualRegister(TRC);
7063   if (IsThumb2) {
7064     unsigned Vtmp = varEnd;
7065     if ((LoopSize & 0xFFFF0000) != 0)
7066       Vtmp = MRI.createVirtualRegister(TRC);
7067     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7068                        .addImm(LoopSize & 0xFFFF));
7069
7070     if ((LoopSize & 0xFFFF0000) != 0)
7071       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7072                          .addReg(Vtmp).addImm(LoopSize >> 16));
7073   } else {
7074     MachineConstantPool *ConstantPool = MF->getConstantPool();
7075     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7076     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7077
7078     // MachineConstantPool wants an explicit alignment.
7079     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7080     if (Align == 0)
7081       Align = getDataLayout()->getTypeAllocSize(C->getType());
7082     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7083
7084     if (IsThumb1)
7085       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7086           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7087     else
7088       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7089           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7090   }
7091   BB->addSuccessor(loopMBB);
7092
7093   // Generate the loop body:
7094   //   varPhi = PHI(varLoop, varEnd)
7095   //   srcPhi = PHI(srcLoop, src)
7096   //   destPhi = PHI(destLoop, dst)
7097   MachineBasicBlock *entryBB = BB;
7098   BB = loopMBB;
7099   unsigned varLoop = MRI.createVirtualRegister(TRC);
7100   unsigned varPhi = MRI.createVirtualRegister(TRC);
7101   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7102   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7103   unsigned destLoop = MRI.createVirtualRegister(TRC);
7104   unsigned destPhi = MRI.createVirtualRegister(TRC);
7105
7106   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7107     .addReg(varLoop).addMBB(loopMBB)
7108     .addReg(varEnd).addMBB(entryBB);
7109   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7110     .addReg(srcLoop).addMBB(loopMBB)
7111     .addReg(src).addMBB(entryBB);
7112   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7113     .addReg(destLoop).addMBB(loopMBB)
7114     .addReg(dest).addMBB(entryBB);
7115
7116   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7117   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7118   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7119   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7120              IsThumb1, IsThumb2);
7121   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7122              IsThumb1, IsThumb2);
7123
7124   // Decrement loop variable by UnitSize.
7125   if (IsThumb1) {
7126     MachineInstrBuilder MIB =
7127         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7128     MIB = AddDefaultT1CC(MIB);
7129     MIB.addReg(varPhi).addImm(UnitSize);
7130     AddDefaultPred(MIB);
7131   } else {
7132     MachineInstrBuilder MIB =
7133         BuildMI(*BB, BB->end(), dl,
7134                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7135     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7136     MIB->getOperand(5).setReg(ARM::CPSR);
7137     MIB->getOperand(5).setIsDef(true);
7138   }
7139   BuildMI(*BB, BB->end(), dl,
7140           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7141       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7142
7143   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7144   BB->addSuccessor(loopMBB);
7145   BB->addSuccessor(exitMBB);
7146
7147   // Add epilogue to handle BytesLeft.
7148   BB = exitMBB;
7149   MachineInstr *StartOfExit = exitMBB->begin();
7150
7151   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7152   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7153   unsigned srcIn = srcLoop;
7154   unsigned destIn = destLoop;
7155   for (unsigned i = 0; i < BytesLeft; i++) {
7156     unsigned srcOut = MRI.createVirtualRegister(TRC);
7157     unsigned destOut = MRI.createVirtualRegister(TRC);
7158     unsigned scratch = MRI.createVirtualRegister(TRC);
7159     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7160                IsThumb1, IsThumb2);
7161     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7162                IsThumb1, IsThumb2);
7163     srcIn = srcOut;
7164     destIn = destOut;
7165   }
7166
7167   MI->eraseFromParent();   // The instruction is gone now.
7168   return BB;
7169 }
7170
7171 MachineBasicBlock *
7172 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7173                                        MachineBasicBlock *MBB) const {
7174   const TargetMachine &TM = getTargetMachine();
7175   const TargetInstrInfo &TII = *TM.getInstrInfo();
7176   DebugLoc DL = MI->getDebugLoc();
7177
7178   assert(Subtarget->isTargetWindows() &&
7179          "__chkstk is only supported on Windows");
7180   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7181
7182   // __chkstk takes the number of words to allocate on the stack in R4, and
7183   // returns the stack adjustment in number of bytes in R4.  This will not
7184   // clober any other registers (other than the obvious lr).
7185   //
7186   // Although, technically, IP should be considered a register which may be
7187   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7188   // thumb-2 environment, so there is no interworking required.  As a result, we
7189   // do not expect a veneer to be emitted by the linker, clobbering IP.
7190   //
7191   // Each module receives its own copy of __chkstk, so no import thunk is
7192   // required, again, ensuring that IP is not clobbered.
7193   //
7194   // Finally, although some linkers may theoretically provide a trampoline for
7195   // out of range calls (which is quite common due to a 32M range limitation of
7196   // branches for Thumb), we can generate the long-call version via
7197   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7198   // IP.
7199
7200   switch (TM.getCodeModel()) {
7201   case CodeModel::Small:
7202   case CodeModel::Medium:
7203   case CodeModel::Default:
7204   case CodeModel::Kernel:
7205     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7206       .addImm((unsigned)ARMCC::AL).addReg(0)
7207       .addExternalSymbol("__chkstk")
7208       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7209       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7210       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7211     break;
7212   case CodeModel::Large:
7213   case CodeModel::JITDefault: {
7214     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7215     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7216
7217     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7218       .addExternalSymbol("__chkstk");
7219     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7220       .addImm((unsigned)ARMCC::AL).addReg(0)
7221       .addReg(Reg, RegState::Kill)
7222       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7223       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7224       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7225     break;
7226   }
7227   }
7228
7229   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7230                                       ARM::SP)
7231                               .addReg(ARM::SP).addReg(ARM::R4)));
7232
7233   MI->eraseFromParent();
7234   return MBB;
7235 }
7236
7237 MachineBasicBlock *
7238 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7239                                                MachineBasicBlock *BB) const {
7240   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7241   DebugLoc dl = MI->getDebugLoc();
7242   bool isThumb2 = Subtarget->isThumb2();
7243   switch (MI->getOpcode()) {
7244   default: {
7245     MI->dump();
7246     llvm_unreachable("Unexpected instr type to insert");
7247   }
7248   // The Thumb2 pre-indexed stores have the same MI operands, they just
7249   // define them differently in the .td files from the isel patterns, so
7250   // they need pseudos.
7251   case ARM::t2STR_preidx:
7252     MI->setDesc(TII->get(ARM::t2STR_PRE));
7253     return BB;
7254   case ARM::t2STRB_preidx:
7255     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7256     return BB;
7257   case ARM::t2STRH_preidx:
7258     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7259     return BB;
7260
7261   case ARM::STRi_preidx:
7262   case ARM::STRBi_preidx: {
7263     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7264       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7265     // Decode the offset.
7266     unsigned Offset = MI->getOperand(4).getImm();
7267     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7268     Offset = ARM_AM::getAM2Offset(Offset);
7269     if (isSub)
7270       Offset = -Offset;
7271
7272     MachineMemOperand *MMO = *MI->memoperands_begin();
7273     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7274       .addOperand(MI->getOperand(0))  // Rn_wb
7275       .addOperand(MI->getOperand(1))  // Rt
7276       .addOperand(MI->getOperand(2))  // Rn
7277       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7278       .addOperand(MI->getOperand(5))  // pred
7279       .addOperand(MI->getOperand(6))
7280       .addMemOperand(MMO);
7281     MI->eraseFromParent();
7282     return BB;
7283   }
7284   case ARM::STRr_preidx:
7285   case ARM::STRBr_preidx:
7286   case ARM::STRH_preidx: {
7287     unsigned NewOpc;
7288     switch (MI->getOpcode()) {
7289     default: llvm_unreachable("unexpected opcode!");
7290     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7291     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7292     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7293     }
7294     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7295     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7296       MIB.addOperand(MI->getOperand(i));
7297     MI->eraseFromParent();
7298     return BB;
7299   }
7300
7301   case ARM::tMOVCCr_pseudo: {
7302     // To "insert" a SELECT_CC instruction, we actually have to insert the
7303     // diamond control-flow pattern.  The incoming instruction knows the
7304     // destination vreg to set, the condition code register to branch on, the
7305     // true/false values to select between, and a branch opcode to use.
7306     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7307     MachineFunction::iterator It = BB;
7308     ++It;
7309
7310     //  thisMBB:
7311     //  ...
7312     //   TrueVal = ...
7313     //   cmpTY ccX, r1, r2
7314     //   bCC copy1MBB
7315     //   fallthrough --> copy0MBB
7316     MachineBasicBlock *thisMBB  = BB;
7317     MachineFunction *F = BB->getParent();
7318     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7319     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7320     F->insert(It, copy0MBB);
7321     F->insert(It, sinkMBB);
7322
7323     // Transfer the remainder of BB and its successor edges to sinkMBB.
7324     sinkMBB->splice(sinkMBB->begin(), BB,
7325                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7326     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7327
7328     BB->addSuccessor(copy0MBB);
7329     BB->addSuccessor(sinkMBB);
7330
7331     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7332       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7333
7334     //  copy0MBB:
7335     //   %FalseValue = ...
7336     //   # fallthrough to sinkMBB
7337     BB = copy0MBB;
7338
7339     // Update machine-CFG edges
7340     BB->addSuccessor(sinkMBB);
7341
7342     //  sinkMBB:
7343     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7344     //  ...
7345     BB = sinkMBB;
7346     BuildMI(*BB, BB->begin(), dl,
7347             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7348       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7349       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7350
7351     MI->eraseFromParent();   // The pseudo instruction is gone now.
7352     return BB;
7353   }
7354
7355   case ARM::BCCi64:
7356   case ARM::BCCZi64: {
7357     // If there is an unconditional branch to the other successor, remove it.
7358     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7359
7360     // Compare both parts that make up the double comparison separately for
7361     // equality.
7362     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7363
7364     unsigned LHS1 = MI->getOperand(1).getReg();
7365     unsigned LHS2 = MI->getOperand(2).getReg();
7366     if (RHSisZero) {
7367       AddDefaultPred(BuildMI(BB, dl,
7368                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7369                      .addReg(LHS1).addImm(0));
7370       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7371         .addReg(LHS2).addImm(0)
7372         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7373     } else {
7374       unsigned RHS1 = MI->getOperand(3).getReg();
7375       unsigned RHS2 = MI->getOperand(4).getReg();
7376       AddDefaultPred(BuildMI(BB, dl,
7377                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7378                      .addReg(LHS1).addReg(RHS1));
7379       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7380         .addReg(LHS2).addReg(RHS2)
7381         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7382     }
7383
7384     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7385     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7386     if (MI->getOperand(0).getImm() == ARMCC::NE)
7387       std::swap(destMBB, exitMBB);
7388
7389     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7390       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7391     if (isThumb2)
7392       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7393     else
7394       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7395
7396     MI->eraseFromParent();   // The pseudo instruction is gone now.
7397     return BB;
7398   }
7399
7400   case ARM::Int_eh_sjlj_setjmp:
7401   case ARM::Int_eh_sjlj_setjmp_nofp:
7402   case ARM::tInt_eh_sjlj_setjmp:
7403   case ARM::t2Int_eh_sjlj_setjmp:
7404   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7405     EmitSjLjDispatchBlock(MI, BB);
7406     return BB;
7407
7408   case ARM::ABS:
7409   case ARM::t2ABS: {
7410     // To insert an ABS instruction, we have to insert the
7411     // diamond control-flow pattern.  The incoming instruction knows the
7412     // source vreg to test against 0, the destination vreg to set,
7413     // the condition code register to branch on, the
7414     // true/false values to select between, and a branch opcode to use.
7415     // It transforms
7416     //     V1 = ABS V0
7417     // into
7418     //     V2 = MOVS V0
7419     //     BCC                      (branch to SinkBB if V0 >= 0)
7420     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7421     //     SinkBB: V1 = PHI(V2, V3)
7422     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7423     MachineFunction::iterator BBI = BB;
7424     ++BBI;
7425     MachineFunction *Fn = BB->getParent();
7426     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7427     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7428     Fn->insert(BBI, RSBBB);
7429     Fn->insert(BBI, SinkBB);
7430
7431     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7432     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7433     bool isThumb2 = Subtarget->isThumb2();
7434     MachineRegisterInfo &MRI = Fn->getRegInfo();
7435     // In Thumb mode S must not be specified if source register is the SP or
7436     // PC and if destination register is the SP, so restrict register class
7437     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7438       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7439       (const TargetRegisterClass*)&ARM::GPRRegClass);
7440
7441     // Transfer the remainder of BB and its successor edges to sinkMBB.
7442     SinkBB->splice(SinkBB->begin(), BB,
7443                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7444     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7445
7446     BB->addSuccessor(RSBBB);
7447     BB->addSuccessor(SinkBB);
7448
7449     // fall through to SinkMBB
7450     RSBBB->addSuccessor(SinkBB);
7451
7452     // insert a cmp at the end of BB
7453     AddDefaultPred(BuildMI(BB, dl,
7454                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7455                    .addReg(ABSSrcReg).addImm(0));
7456
7457     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7458     BuildMI(BB, dl,
7459       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7460       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7461
7462     // insert rsbri in RSBBB
7463     // Note: BCC and rsbri will be converted into predicated rsbmi
7464     // by if-conversion pass
7465     BuildMI(*RSBBB, RSBBB->begin(), dl,
7466       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7467       .addReg(ABSSrcReg, RegState::Kill)
7468       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7469
7470     // insert PHI in SinkBB,
7471     // reuse ABSDstReg to not change uses of ABS instruction
7472     BuildMI(*SinkBB, SinkBB->begin(), dl,
7473       TII->get(ARM::PHI), ABSDstReg)
7474       .addReg(NewRsbDstReg).addMBB(RSBBB)
7475       .addReg(ABSSrcReg).addMBB(BB);
7476
7477     // remove ABS instruction
7478     MI->eraseFromParent();
7479
7480     // return last added BB
7481     return SinkBB;
7482   }
7483   case ARM::COPY_STRUCT_BYVAL_I32:
7484     ++NumLoopByVals;
7485     return EmitStructByval(MI, BB);
7486   case ARM::WIN__CHKSTK:
7487     return EmitLowered__chkstk(MI, BB);
7488   }
7489 }
7490
7491 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7492                                                       SDNode *Node) const {
7493   if (!MI->hasPostISelHook()) {
7494     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7495            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7496     return;
7497   }
7498
7499   const MCInstrDesc *MCID = &MI->getDesc();
7500   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7501   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7502   // operand is still set to noreg. If needed, set the optional operand's
7503   // register to CPSR, and remove the redundant implicit def.
7504   //
7505   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7506
7507   // Rename pseudo opcodes.
7508   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7509   if (NewOpc) {
7510     const ARMBaseInstrInfo *TII =
7511       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7512     MCID = &TII->get(NewOpc);
7513
7514     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7515            "converted opcode should be the same except for cc_out");
7516
7517     MI->setDesc(*MCID);
7518
7519     // Add the optional cc_out operand
7520     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7521   }
7522   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7523
7524   // Any ARM instruction that sets the 's' bit should specify an optional
7525   // "cc_out" operand in the last operand position.
7526   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7527     assert(!NewOpc && "Optional cc_out operand required");
7528     return;
7529   }
7530   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7531   // since we already have an optional CPSR def.
7532   bool definesCPSR = false;
7533   bool deadCPSR = false;
7534   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7535        i != e; ++i) {
7536     const MachineOperand &MO = MI->getOperand(i);
7537     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7538       definesCPSR = true;
7539       if (MO.isDead())
7540         deadCPSR = true;
7541       MI->RemoveOperand(i);
7542       break;
7543     }
7544   }
7545   if (!definesCPSR) {
7546     assert(!NewOpc && "Optional cc_out operand required");
7547     return;
7548   }
7549   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7550   if (deadCPSR) {
7551     assert(!MI->getOperand(ccOutIdx).getReg() &&
7552            "expect uninitialized optional cc_out operand");
7553     return;
7554   }
7555
7556   // If this instruction was defined with an optional CPSR def and its dag node
7557   // had a live implicit CPSR def, then activate the optional CPSR def.
7558   MachineOperand &MO = MI->getOperand(ccOutIdx);
7559   MO.setReg(ARM::CPSR);
7560   MO.setIsDef(true);
7561 }
7562
7563 //===----------------------------------------------------------------------===//
7564 //                           ARM Optimization Hooks
7565 //===----------------------------------------------------------------------===//
7566
7567 // Helper function that checks if N is a null or all ones constant.
7568 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7569   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7570   if (!C)
7571     return false;
7572   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7573 }
7574
7575 // Return true if N is conditionally 0 or all ones.
7576 // Detects these expressions where cc is an i1 value:
7577 //
7578 //   (select cc 0, y)   [AllOnes=0]
7579 //   (select cc y, 0)   [AllOnes=0]
7580 //   (zext cc)          [AllOnes=0]
7581 //   (sext cc)          [AllOnes=0/1]
7582 //   (select cc -1, y)  [AllOnes=1]
7583 //   (select cc y, -1)  [AllOnes=1]
7584 //
7585 // Invert is set when N is the null/all ones constant when CC is false.
7586 // OtherOp is set to the alternative value of N.
7587 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7588                                        SDValue &CC, bool &Invert,
7589                                        SDValue &OtherOp,
7590                                        SelectionDAG &DAG) {
7591   switch (N->getOpcode()) {
7592   default: return false;
7593   case ISD::SELECT: {
7594     CC = N->getOperand(0);
7595     SDValue N1 = N->getOperand(1);
7596     SDValue N2 = N->getOperand(2);
7597     if (isZeroOrAllOnes(N1, AllOnes)) {
7598       Invert = false;
7599       OtherOp = N2;
7600       return true;
7601     }
7602     if (isZeroOrAllOnes(N2, AllOnes)) {
7603       Invert = true;
7604       OtherOp = N1;
7605       return true;
7606     }
7607     return false;
7608   }
7609   case ISD::ZERO_EXTEND:
7610     // (zext cc) can never be the all ones value.
7611     if (AllOnes)
7612       return false;
7613     // Fall through.
7614   case ISD::SIGN_EXTEND: {
7615     EVT VT = N->getValueType(0);
7616     CC = N->getOperand(0);
7617     if (CC.getValueType() != MVT::i1)
7618       return false;
7619     Invert = !AllOnes;
7620     if (AllOnes)
7621       // When looking for an AllOnes constant, N is an sext, and the 'other'
7622       // value is 0.
7623       OtherOp = DAG.getConstant(0, VT);
7624     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7625       // When looking for a 0 constant, N can be zext or sext.
7626       OtherOp = DAG.getConstant(1, VT);
7627     else
7628       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7629     return true;
7630   }
7631   }
7632 }
7633
7634 // Combine a constant select operand into its use:
7635 //
7636 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7637 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7638 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7639 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7640 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7641 //
7642 // The transform is rejected if the select doesn't have a constant operand that
7643 // is null, or all ones when AllOnes is set.
7644 //
7645 // Also recognize sext/zext from i1:
7646 //
7647 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7648 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7649 //
7650 // These transformations eventually create predicated instructions.
7651 //
7652 // @param N       The node to transform.
7653 // @param Slct    The N operand that is a select.
7654 // @param OtherOp The other N operand (x above).
7655 // @param DCI     Context.
7656 // @param AllOnes Require the select constant to be all ones instead of null.
7657 // @returns The new node, or SDValue() on failure.
7658 static
7659 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7660                             TargetLowering::DAGCombinerInfo &DCI,
7661                             bool AllOnes = false) {
7662   SelectionDAG &DAG = DCI.DAG;
7663   EVT VT = N->getValueType(0);
7664   SDValue NonConstantVal;
7665   SDValue CCOp;
7666   bool SwapSelectOps;
7667   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7668                                   NonConstantVal, DAG))
7669     return SDValue();
7670
7671   // Slct is now know to be the desired identity constant when CC is true.
7672   SDValue TrueVal = OtherOp;
7673   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7674                                  OtherOp, NonConstantVal);
7675   // Unless SwapSelectOps says CC should be false.
7676   if (SwapSelectOps)
7677     std::swap(TrueVal, FalseVal);
7678
7679   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7680                      CCOp, TrueVal, FalseVal);
7681 }
7682
7683 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7684 static
7685 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7686                                        TargetLowering::DAGCombinerInfo &DCI) {
7687   SDValue N0 = N->getOperand(0);
7688   SDValue N1 = N->getOperand(1);
7689   if (N0.getNode()->hasOneUse()) {
7690     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7691     if (Result.getNode())
7692       return Result;
7693   }
7694   if (N1.getNode()->hasOneUse()) {
7695     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7696     if (Result.getNode())
7697       return Result;
7698   }
7699   return SDValue();
7700 }
7701
7702 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7703 // (only after legalization).
7704 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7705                                  TargetLowering::DAGCombinerInfo &DCI,
7706                                  const ARMSubtarget *Subtarget) {
7707
7708   // Only perform optimization if after legalize, and if NEON is available. We
7709   // also expected both operands to be BUILD_VECTORs.
7710   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7711       || N0.getOpcode() != ISD::BUILD_VECTOR
7712       || N1.getOpcode() != ISD::BUILD_VECTOR)
7713     return SDValue();
7714
7715   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7716   EVT VT = N->getValueType(0);
7717   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7718     return SDValue();
7719
7720   // Check that the vector operands are of the right form.
7721   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7722   // operands, where N is the size of the formed vector.
7723   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7724   // index such that we have a pair wise add pattern.
7725
7726   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7727   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7728     return SDValue();
7729   SDValue Vec = N0->getOperand(0)->getOperand(0);
7730   SDNode *V = Vec.getNode();
7731   unsigned nextIndex = 0;
7732
7733   // For each operands to the ADD which are BUILD_VECTORs,
7734   // check to see if each of their operands are an EXTRACT_VECTOR with
7735   // the same vector and appropriate index.
7736   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7737     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7738         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7739
7740       SDValue ExtVec0 = N0->getOperand(i);
7741       SDValue ExtVec1 = N1->getOperand(i);
7742
7743       // First operand is the vector, verify its the same.
7744       if (V != ExtVec0->getOperand(0).getNode() ||
7745           V != ExtVec1->getOperand(0).getNode())
7746         return SDValue();
7747
7748       // Second is the constant, verify its correct.
7749       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7750       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7751
7752       // For the constant, we want to see all the even or all the odd.
7753       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7754           || C1->getZExtValue() != nextIndex+1)
7755         return SDValue();
7756
7757       // Increment index.
7758       nextIndex+=2;
7759     } else
7760       return SDValue();
7761   }
7762
7763   // Create VPADDL node.
7764   SelectionDAG &DAG = DCI.DAG;
7765   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7766
7767   // Build operand list.
7768   SmallVector<SDValue, 8> Ops;
7769   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7770                                 TLI.getPointerTy()));
7771
7772   // Input is the vector.
7773   Ops.push_back(Vec);
7774
7775   // Get widened type and narrowed type.
7776   MVT widenType;
7777   unsigned numElem = VT.getVectorNumElements();
7778   
7779   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7780   switch (inputLaneType.getSimpleVT().SimpleTy) {
7781     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7782     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7783     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7784     default:
7785       llvm_unreachable("Invalid vector element type for padd optimization.");
7786   }
7787
7788   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7789   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7790   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7791 }
7792
7793 static SDValue findMUL_LOHI(SDValue V) {
7794   if (V->getOpcode() == ISD::UMUL_LOHI ||
7795       V->getOpcode() == ISD::SMUL_LOHI)
7796     return V;
7797   return SDValue();
7798 }
7799
7800 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7801                                      TargetLowering::DAGCombinerInfo &DCI,
7802                                      const ARMSubtarget *Subtarget) {
7803
7804   if (Subtarget->isThumb1Only()) return SDValue();
7805
7806   // Only perform the checks after legalize when the pattern is available.
7807   if (DCI.isBeforeLegalize()) return SDValue();
7808
7809   // Look for multiply add opportunities.
7810   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7811   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7812   // a glue link from the first add to the second add.
7813   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7814   // a S/UMLAL instruction.
7815   //          loAdd   UMUL_LOHI
7816   //            \    / :lo    \ :hi
7817   //             \  /          \          [no multiline comment]
7818   //              ADDC         |  hiAdd
7819   //                 \ :glue  /  /
7820   //                  \      /  /
7821   //                    ADDE
7822   //
7823   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7824   SDValue AddcOp0 = AddcNode->getOperand(0);
7825   SDValue AddcOp1 = AddcNode->getOperand(1);
7826
7827   // Check if the two operands are from the same mul_lohi node.
7828   if (AddcOp0.getNode() == AddcOp1.getNode())
7829     return SDValue();
7830
7831   assert(AddcNode->getNumValues() == 2 &&
7832          AddcNode->getValueType(0) == MVT::i32 &&
7833          "Expect ADDC with two result values. First: i32");
7834
7835   // Check that we have a glued ADDC node.
7836   if (AddcNode->getValueType(1) != MVT::Glue)
7837     return SDValue();
7838
7839   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7840   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7841       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7842       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7843       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7844     return SDValue();
7845
7846   // Look for the glued ADDE.
7847   SDNode* AddeNode = AddcNode->getGluedUser();
7848   if (!AddeNode)
7849     return SDValue();
7850
7851   // Make sure it is really an ADDE.
7852   if (AddeNode->getOpcode() != ISD::ADDE)
7853     return SDValue();
7854
7855   assert(AddeNode->getNumOperands() == 3 &&
7856          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7857          "ADDE node has the wrong inputs");
7858
7859   // Check for the triangle shape.
7860   SDValue AddeOp0 = AddeNode->getOperand(0);
7861   SDValue AddeOp1 = AddeNode->getOperand(1);
7862
7863   // Make sure that the ADDE operands are not coming from the same node.
7864   if (AddeOp0.getNode() == AddeOp1.getNode())
7865     return SDValue();
7866
7867   // Find the MUL_LOHI node walking up ADDE's operands.
7868   bool IsLeftOperandMUL = false;
7869   SDValue MULOp = findMUL_LOHI(AddeOp0);
7870   if (MULOp == SDValue())
7871    MULOp = findMUL_LOHI(AddeOp1);
7872   else
7873     IsLeftOperandMUL = true;
7874   if (MULOp == SDValue())
7875      return SDValue();
7876
7877   // Figure out the right opcode.
7878   unsigned Opc = MULOp->getOpcode();
7879   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7880
7881   // Figure out the high and low input values to the MLAL node.
7882   SDValue* HiMul = &MULOp;
7883   SDValue* HiAdd = nullptr;
7884   SDValue* LoMul = nullptr;
7885   SDValue* LowAdd = nullptr;
7886
7887   if (IsLeftOperandMUL)
7888     HiAdd = &AddeOp1;
7889   else
7890     HiAdd = &AddeOp0;
7891
7892
7893   if (AddcOp0->getOpcode() == Opc) {
7894     LoMul = &AddcOp0;
7895     LowAdd = &AddcOp1;
7896   }
7897   if (AddcOp1->getOpcode() == Opc) {
7898     LoMul = &AddcOp1;
7899     LowAdd = &AddcOp0;
7900   }
7901
7902   if (!LoMul)
7903     return SDValue();
7904
7905   if (LoMul->getNode() != HiMul->getNode())
7906     return SDValue();
7907
7908   // Create the merged node.
7909   SelectionDAG &DAG = DCI.DAG;
7910
7911   // Build operand list.
7912   SmallVector<SDValue, 8> Ops;
7913   Ops.push_back(LoMul->getOperand(0));
7914   Ops.push_back(LoMul->getOperand(1));
7915   Ops.push_back(*LowAdd);
7916   Ops.push_back(*HiAdd);
7917
7918   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7919                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7920
7921   // Replace the ADDs' nodes uses by the MLA node's values.
7922   SDValue HiMLALResult(MLALNode.getNode(), 1);
7923   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7924
7925   SDValue LoMLALResult(MLALNode.getNode(), 0);
7926   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7927
7928   // Return original node to notify the driver to stop replacing.
7929   SDValue resNode(AddcNode, 0);
7930   return resNode;
7931 }
7932
7933 /// PerformADDCCombine - Target-specific dag combine transform from
7934 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7935 static SDValue PerformADDCCombine(SDNode *N,
7936                                  TargetLowering::DAGCombinerInfo &DCI,
7937                                  const ARMSubtarget *Subtarget) {
7938
7939   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7940
7941 }
7942
7943 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7944 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7945 /// called with the default operands, and if that fails, with commuted
7946 /// operands.
7947 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7948                                           TargetLowering::DAGCombinerInfo &DCI,
7949                                           const ARMSubtarget *Subtarget){
7950
7951   // Attempt to create vpaddl for this add.
7952   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7953   if (Result.getNode())
7954     return Result;
7955
7956   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7957   if (N0.getNode()->hasOneUse()) {
7958     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7959     if (Result.getNode()) return Result;
7960   }
7961   return SDValue();
7962 }
7963
7964 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7965 ///
7966 static SDValue PerformADDCombine(SDNode *N,
7967                                  TargetLowering::DAGCombinerInfo &DCI,
7968                                  const ARMSubtarget *Subtarget) {
7969   SDValue N0 = N->getOperand(0);
7970   SDValue N1 = N->getOperand(1);
7971
7972   // First try with the default operand order.
7973   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7974   if (Result.getNode())
7975     return Result;
7976
7977   // If that didn't work, try again with the operands commuted.
7978   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7979 }
7980
7981 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7982 ///
7983 static SDValue PerformSUBCombine(SDNode *N,
7984                                  TargetLowering::DAGCombinerInfo &DCI) {
7985   SDValue N0 = N->getOperand(0);
7986   SDValue N1 = N->getOperand(1);
7987
7988   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7989   if (N1.getNode()->hasOneUse()) {
7990     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7991     if (Result.getNode()) return Result;
7992   }
7993
7994   return SDValue();
7995 }
7996
7997 /// PerformVMULCombine
7998 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7999 /// special multiplier accumulator forwarding.
8000 ///   vmul d3, d0, d2
8001 ///   vmla d3, d1, d2
8002 /// is faster than
8003 ///   vadd d3, d0, d1
8004 ///   vmul d3, d3, d2
8005 //  However, for (A + B) * (A + B),
8006 //    vadd d2, d0, d1
8007 //    vmul d3, d0, d2
8008 //    vmla d3, d1, d2
8009 //  is slower than
8010 //    vadd d2, d0, d1
8011 //    vmul d3, d2, d2
8012 static SDValue PerformVMULCombine(SDNode *N,
8013                                   TargetLowering::DAGCombinerInfo &DCI,
8014                                   const ARMSubtarget *Subtarget) {
8015   if (!Subtarget->hasVMLxForwarding())
8016     return SDValue();
8017
8018   SelectionDAG &DAG = DCI.DAG;
8019   SDValue N0 = N->getOperand(0);
8020   SDValue N1 = N->getOperand(1);
8021   unsigned Opcode = N0.getOpcode();
8022   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8023       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8024     Opcode = N1.getOpcode();
8025     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8026         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8027       return SDValue();
8028     std::swap(N0, N1);
8029   }
8030
8031   if (N0 == N1)
8032     return SDValue();
8033
8034   EVT VT = N->getValueType(0);
8035   SDLoc DL(N);
8036   SDValue N00 = N0->getOperand(0);
8037   SDValue N01 = N0->getOperand(1);
8038   return DAG.getNode(Opcode, DL, VT,
8039                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8040                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8041 }
8042
8043 static SDValue PerformMULCombine(SDNode *N,
8044                                  TargetLowering::DAGCombinerInfo &DCI,
8045                                  const ARMSubtarget *Subtarget) {
8046   SelectionDAG &DAG = DCI.DAG;
8047
8048   if (Subtarget->isThumb1Only())
8049     return SDValue();
8050
8051   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8052     return SDValue();
8053
8054   EVT VT = N->getValueType(0);
8055   if (VT.is64BitVector() || VT.is128BitVector())
8056     return PerformVMULCombine(N, DCI, Subtarget);
8057   if (VT != MVT::i32)
8058     return SDValue();
8059
8060   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8061   if (!C)
8062     return SDValue();
8063
8064   int64_t MulAmt = C->getSExtValue();
8065   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8066
8067   ShiftAmt = ShiftAmt & (32 - 1);
8068   SDValue V = N->getOperand(0);
8069   SDLoc DL(N);
8070
8071   SDValue Res;
8072   MulAmt >>= ShiftAmt;
8073
8074   if (MulAmt >= 0) {
8075     if (isPowerOf2_32(MulAmt - 1)) {
8076       // (mul x, 2^N + 1) => (add (shl x, N), x)
8077       Res = DAG.getNode(ISD::ADD, DL, VT,
8078                         V,
8079                         DAG.getNode(ISD::SHL, DL, VT,
8080                                     V,
8081                                     DAG.getConstant(Log2_32(MulAmt - 1),
8082                                                     MVT::i32)));
8083     } else if (isPowerOf2_32(MulAmt + 1)) {
8084       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8085       Res = DAG.getNode(ISD::SUB, DL, VT,
8086                         DAG.getNode(ISD::SHL, DL, VT,
8087                                     V,
8088                                     DAG.getConstant(Log2_32(MulAmt + 1),
8089                                                     MVT::i32)),
8090                         V);
8091     } else
8092       return SDValue();
8093   } else {
8094     uint64_t MulAmtAbs = -MulAmt;
8095     if (isPowerOf2_32(MulAmtAbs + 1)) {
8096       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8097       Res = DAG.getNode(ISD::SUB, DL, VT,
8098                         V,
8099                         DAG.getNode(ISD::SHL, DL, VT,
8100                                     V,
8101                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8102                                                     MVT::i32)));
8103     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8104       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8105       Res = DAG.getNode(ISD::ADD, DL, VT,
8106                         V,
8107                         DAG.getNode(ISD::SHL, DL, VT,
8108                                     V,
8109                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8110                                                     MVT::i32)));
8111       Res = DAG.getNode(ISD::SUB, DL, VT,
8112                         DAG.getConstant(0, MVT::i32),Res);
8113
8114     } else
8115       return SDValue();
8116   }
8117
8118   if (ShiftAmt != 0)
8119     Res = DAG.getNode(ISD::SHL, DL, VT,
8120                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8121
8122   // Do not add new nodes to DAG combiner worklist.
8123   DCI.CombineTo(N, Res, false);
8124   return SDValue();
8125 }
8126
8127 static SDValue PerformANDCombine(SDNode *N,
8128                                  TargetLowering::DAGCombinerInfo &DCI,
8129                                  const ARMSubtarget *Subtarget) {
8130
8131   // Attempt to use immediate-form VBIC
8132   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8133   SDLoc dl(N);
8134   EVT VT = N->getValueType(0);
8135   SelectionDAG &DAG = DCI.DAG;
8136
8137   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8138     return SDValue();
8139
8140   APInt SplatBits, SplatUndef;
8141   unsigned SplatBitSize;
8142   bool HasAnyUndefs;
8143   if (BVN &&
8144       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8145     if (SplatBitSize <= 64) {
8146       EVT VbicVT;
8147       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8148                                       SplatUndef.getZExtValue(), SplatBitSize,
8149                                       DAG, VbicVT, VT.is128BitVector(),
8150                                       OtherModImm);
8151       if (Val.getNode()) {
8152         SDValue Input =
8153           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8154         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8155         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8156       }
8157     }
8158   }
8159
8160   if (!Subtarget->isThumb1Only()) {
8161     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8162     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8163     if (Result.getNode())
8164       return Result;
8165   }
8166
8167   return SDValue();
8168 }
8169
8170 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8171 static SDValue PerformORCombine(SDNode *N,
8172                                 TargetLowering::DAGCombinerInfo &DCI,
8173                                 const ARMSubtarget *Subtarget) {
8174   // Attempt to use immediate-form VORR
8175   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8176   SDLoc dl(N);
8177   EVT VT = N->getValueType(0);
8178   SelectionDAG &DAG = DCI.DAG;
8179
8180   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8181     return SDValue();
8182
8183   APInt SplatBits, SplatUndef;
8184   unsigned SplatBitSize;
8185   bool HasAnyUndefs;
8186   if (BVN && Subtarget->hasNEON() &&
8187       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8188     if (SplatBitSize <= 64) {
8189       EVT VorrVT;
8190       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8191                                       SplatUndef.getZExtValue(), SplatBitSize,
8192                                       DAG, VorrVT, VT.is128BitVector(),
8193                                       OtherModImm);
8194       if (Val.getNode()) {
8195         SDValue Input =
8196           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8197         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8198         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8199       }
8200     }
8201   }
8202
8203   if (!Subtarget->isThumb1Only()) {
8204     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8205     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8206     if (Result.getNode())
8207       return Result;
8208   }
8209
8210   // The code below optimizes (or (and X, Y), Z).
8211   // The AND operand needs to have a single user to make these optimizations
8212   // profitable.
8213   SDValue N0 = N->getOperand(0);
8214   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8215     return SDValue();
8216   SDValue N1 = N->getOperand(1);
8217
8218   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8219   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8220       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8221     APInt SplatUndef;
8222     unsigned SplatBitSize;
8223     bool HasAnyUndefs;
8224
8225     APInt SplatBits0, SplatBits1;
8226     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8227     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8228     // Ensure that the second operand of both ands are constants
8229     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8230                                       HasAnyUndefs) && !HasAnyUndefs) {
8231         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8232                                           HasAnyUndefs) && !HasAnyUndefs) {
8233             // Ensure that the bit width of the constants are the same and that
8234             // the splat arguments are logical inverses as per the pattern we
8235             // are trying to simplify.
8236             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8237                 SplatBits0 == ~SplatBits1) {
8238                 // Canonicalize the vector type to make instruction selection
8239                 // simpler.
8240                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8241                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8242                                              N0->getOperand(1),
8243                                              N0->getOperand(0),
8244                                              N1->getOperand(0));
8245                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8246             }
8247         }
8248     }
8249   }
8250
8251   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8252   // reasonable.
8253
8254   // BFI is only available on V6T2+
8255   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8256     return SDValue();
8257
8258   SDLoc DL(N);
8259   // 1) or (and A, mask), val => ARMbfi A, val, mask
8260   //      iff (val & mask) == val
8261   //
8262   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8263   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8264   //          && mask == ~mask2
8265   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8266   //          && ~mask == mask2
8267   //  (i.e., copy a bitfield value into another bitfield of the same width)
8268
8269   if (VT != MVT::i32)
8270     return SDValue();
8271
8272   SDValue N00 = N0.getOperand(0);
8273
8274   // The value and the mask need to be constants so we can verify this is
8275   // actually a bitfield set. If the mask is 0xffff, we can do better
8276   // via a movt instruction, so don't use BFI in that case.
8277   SDValue MaskOp = N0.getOperand(1);
8278   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8279   if (!MaskC)
8280     return SDValue();
8281   unsigned Mask = MaskC->getZExtValue();
8282   if (Mask == 0xffff)
8283     return SDValue();
8284   SDValue Res;
8285   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8286   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8287   if (N1C) {
8288     unsigned Val = N1C->getZExtValue();
8289     if ((Val & ~Mask) != Val)
8290       return SDValue();
8291
8292     if (ARM::isBitFieldInvertedMask(Mask)) {
8293       Val >>= countTrailingZeros(~Mask);
8294
8295       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8296                         DAG.getConstant(Val, MVT::i32),
8297                         DAG.getConstant(Mask, MVT::i32));
8298
8299       // Do not add new nodes to DAG combiner worklist.
8300       DCI.CombineTo(N, Res, false);
8301       return SDValue();
8302     }
8303   } else if (N1.getOpcode() == ISD::AND) {
8304     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8305     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8306     if (!N11C)
8307       return SDValue();
8308     unsigned Mask2 = N11C->getZExtValue();
8309
8310     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8311     // as is to match.
8312     if (ARM::isBitFieldInvertedMask(Mask) &&
8313         (Mask == ~Mask2)) {
8314       // The pack halfword instruction works better for masks that fit it,
8315       // so use that when it's available.
8316       if (Subtarget->hasT2ExtractPack() &&
8317           (Mask == 0xffff || Mask == 0xffff0000))
8318         return SDValue();
8319       // 2a
8320       unsigned amt = countTrailingZeros(Mask2);
8321       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8322                         DAG.getConstant(amt, MVT::i32));
8323       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8324                         DAG.getConstant(Mask, MVT::i32));
8325       // Do not add new nodes to DAG combiner worklist.
8326       DCI.CombineTo(N, Res, false);
8327       return SDValue();
8328     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8329                (~Mask == Mask2)) {
8330       // The pack halfword instruction works better for masks that fit it,
8331       // so use that when it's available.
8332       if (Subtarget->hasT2ExtractPack() &&
8333           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8334         return SDValue();
8335       // 2b
8336       unsigned lsb = countTrailingZeros(Mask);
8337       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8338                         DAG.getConstant(lsb, MVT::i32));
8339       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8340                         DAG.getConstant(Mask2, MVT::i32));
8341       // Do not add new nodes to DAG combiner worklist.
8342       DCI.CombineTo(N, Res, false);
8343       return SDValue();
8344     }
8345   }
8346
8347   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8348       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8349       ARM::isBitFieldInvertedMask(~Mask)) {
8350     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8351     // where lsb(mask) == #shamt and masked bits of B are known zero.
8352     SDValue ShAmt = N00.getOperand(1);
8353     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8354     unsigned LSB = countTrailingZeros(Mask);
8355     if (ShAmtC != LSB)
8356       return SDValue();
8357
8358     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8359                       DAG.getConstant(~Mask, MVT::i32));
8360
8361     // Do not add new nodes to DAG combiner worklist.
8362     DCI.CombineTo(N, Res, false);
8363   }
8364
8365   return SDValue();
8366 }
8367
8368 static SDValue PerformXORCombine(SDNode *N,
8369                                  TargetLowering::DAGCombinerInfo &DCI,
8370                                  const ARMSubtarget *Subtarget) {
8371   EVT VT = N->getValueType(0);
8372   SelectionDAG &DAG = DCI.DAG;
8373
8374   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8375     return SDValue();
8376
8377   if (!Subtarget->isThumb1Only()) {
8378     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8379     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8380     if (Result.getNode())
8381       return Result;
8382   }
8383
8384   return SDValue();
8385 }
8386
8387 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8388 /// the bits being cleared by the AND are not demanded by the BFI.
8389 static SDValue PerformBFICombine(SDNode *N,
8390                                  TargetLowering::DAGCombinerInfo &DCI) {
8391   SDValue N1 = N->getOperand(1);
8392   if (N1.getOpcode() == ISD::AND) {
8393     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8394     if (!N11C)
8395       return SDValue();
8396     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8397     unsigned LSB = countTrailingZeros(~InvMask);
8398     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8399     unsigned Mask = (1 << Width)-1;
8400     unsigned Mask2 = N11C->getZExtValue();
8401     if ((Mask & (~Mask2)) == 0)
8402       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8403                              N->getOperand(0), N1.getOperand(0),
8404                              N->getOperand(2));
8405   }
8406   return SDValue();
8407 }
8408
8409 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8410 /// ARMISD::VMOVRRD.
8411 static SDValue PerformVMOVRRDCombine(SDNode *N,
8412                                      TargetLowering::DAGCombinerInfo &DCI) {
8413   // vmovrrd(vmovdrr x, y) -> x,y
8414   SDValue InDouble = N->getOperand(0);
8415   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8416     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8417
8418   // vmovrrd(load f64) -> (load i32), (load i32)
8419   SDNode *InNode = InDouble.getNode();
8420   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8421       InNode->getValueType(0) == MVT::f64 &&
8422       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8423       !cast<LoadSDNode>(InNode)->isVolatile()) {
8424     // TODO: Should this be done for non-FrameIndex operands?
8425     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8426
8427     SelectionDAG &DAG = DCI.DAG;
8428     SDLoc DL(LD);
8429     SDValue BasePtr = LD->getBasePtr();
8430     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8431                                  LD->getPointerInfo(), LD->isVolatile(),
8432                                  LD->isNonTemporal(), LD->isInvariant(),
8433                                  LD->getAlignment());
8434
8435     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8436                                     DAG.getConstant(4, MVT::i32));
8437     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8438                                  LD->getPointerInfo(), LD->isVolatile(),
8439                                  LD->isNonTemporal(), LD->isInvariant(),
8440                                  std::min(4U, LD->getAlignment() / 2));
8441
8442     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8443     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8444       std::swap (NewLD1, NewLD2);
8445     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8446     return Result;
8447   }
8448
8449   return SDValue();
8450 }
8451
8452 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8453 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8454 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8455   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8456   SDValue Op0 = N->getOperand(0);
8457   SDValue Op1 = N->getOperand(1);
8458   if (Op0.getOpcode() == ISD::BITCAST)
8459     Op0 = Op0.getOperand(0);
8460   if (Op1.getOpcode() == ISD::BITCAST)
8461     Op1 = Op1.getOperand(0);
8462   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8463       Op0.getNode() == Op1.getNode() &&
8464       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8465     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8466                        N->getValueType(0), Op0.getOperand(0));
8467   return SDValue();
8468 }
8469
8470 /// PerformSTORECombine - Target-specific dag combine xforms for
8471 /// ISD::STORE.
8472 static SDValue PerformSTORECombine(SDNode *N,
8473                                    TargetLowering::DAGCombinerInfo &DCI) {
8474   StoreSDNode *St = cast<StoreSDNode>(N);
8475   if (St->isVolatile())
8476     return SDValue();
8477
8478   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8479   // pack all of the elements in one place.  Next, store to memory in fewer
8480   // chunks.
8481   SDValue StVal = St->getValue();
8482   EVT VT = StVal.getValueType();
8483   if (St->isTruncatingStore() && VT.isVector()) {
8484     SelectionDAG &DAG = DCI.DAG;
8485     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8486     EVT StVT = St->getMemoryVT();
8487     unsigned NumElems = VT.getVectorNumElements();
8488     assert(StVT != VT && "Cannot truncate to the same type");
8489     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8490     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8491
8492     // From, To sizes and ElemCount must be pow of two
8493     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8494
8495     // We are going to use the original vector elt for storing.
8496     // Accumulated smaller vector elements must be a multiple of the store size.
8497     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8498
8499     unsigned SizeRatio  = FromEltSz / ToEltSz;
8500     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8501
8502     // Create a type on which we perform the shuffle.
8503     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8504                                      NumElems*SizeRatio);
8505     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8506
8507     SDLoc DL(St);
8508     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8509     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8510     for (unsigned i = 0; i < NumElems; ++i)
8511       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8512
8513     // Can't shuffle using an illegal type.
8514     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8515
8516     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8517                                 DAG.getUNDEF(WideVec.getValueType()),
8518                                 ShuffleVec.data());
8519     // At this point all of the data is stored at the bottom of the
8520     // register. We now need to save it to mem.
8521
8522     // Find the largest store unit
8523     MVT StoreType = MVT::i8;
8524     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8525          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8526       MVT Tp = (MVT::SimpleValueType)tp;
8527       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8528         StoreType = Tp;
8529     }
8530     // Didn't find a legal store type.
8531     if (!TLI.isTypeLegal(StoreType))
8532       return SDValue();
8533
8534     // Bitcast the original vector into a vector of store-size units
8535     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8536             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8537     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8538     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8539     SmallVector<SDValue, 8> Chains;
8540     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8541                                         TLI.getPointerTy());
8542     SDValue BasePtr = St->getBasePtr();
8543
8544     // Perform one or more big stores into memory.
8545     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8546     for (unsigned I = 0; I < E; I++) {
8547       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8548                                    StoreType, ShuffWide,
8549                                    DAG.getIntPtrConstant(I));
8550       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8551                                 St->getPointerInfo(), St->isVolatile(),
8552                                 St->isNonTemporal(), St->getAlignment());
8553       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8554                             Increment);
8555       Chains.push_back(Ch);
8556     }
8557     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8558   }
8559
8560   if (!ISD::isNormalStore(St))
8561     return SDValue();
8562
8563   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8564   // ARM stores of arguments in the same cache line.
8565   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8566       StVal.getNode()->hasOneUse()) {
8567     SelectionDAG  &DAG = DCI.DAG;
8568     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8569     SDLoc DL(St);
8570     SDValue BasePtr = St->getBasePtr();
8571     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8572                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8573                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8574                                   St->isNonTemporal(), St->getAlignment());
8575
8576     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8577                                     DAG.getConstant(4, MVT::i32));
8578     return DAG.getStore(NewST1.getValue(0), DL,
8579                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8580                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8581                         St->isNonTemporal(),
8582                         std::min(4U, St->getAlignment() / 2));
8583   }
8584
8585   if (StVal.getValueType() != MVT::i64 ||
8586       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8587     return SDValue();
8588
8589   // Bitcast an i64 store extracted from a vector to f64.
8590   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8591   SelectionDAG &DAG = DCI.DAG;
8592   SDLoc dl(StVal);
8593   SDValue IntVec = StVal.getOperand(0);
8594   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8595                                  IntVec.getValueType().getVectorNumElements());
8596   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8597   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8598                                Vec, StVal.getOperand(1));
8599   dl = SDLoc(N);
8600   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8601   // Make the DAGCombiner fold the bitcasts.
8602   DCI.AddToWorklist(Vec.getNode());
8603   DCI.AddToWorklist(ExtElt.getNode());
8604   DCI.AddToWorklist(V.getNode());
8605   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8606                       St->getPointerInfo(), St->isVolatile(),
8607                       St->isNonTemporal(), St->getAlignment(),
8608                       St->getAAInfo());
8609 }
8610
8611 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8612 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8613 /// i64 vector to have f64 elements, since the value can then be loaded
8614 /// directly into a VFP register.
8615 static bool hasNormalLoadOperand(SDNode *N) {
8616   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8617   for (unsigned i = 0; i < NumElts; ++i) {
8618     SDNode *Elt = N->getOperand(i).getNode();
8619     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8620       return true;
8621   }
8622   return false;
8623 }
8624
8625 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8626 /// ISD::BUILD_VECTOR.
8627 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8628                                           TargetLowering::DAGCombinerInfo &DCI){
8629   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8630   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8631   // into a pair of GPRs, which is fine when the value is used as a scalar,
8632   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8633   SelectionDAG &DAG = DCI.DAG;
8634   if (N->getNumOperands() == 2) {
8635     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8636     if (RV.getNode())
8637       return RV;
8638   }
8639
8640   // Load i64 elements as f64 values so that type legalization does not split
8641   // them up into i32 values.
8642   EVT VT = N->getValueType(0);
8643   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8644     return SDValue();
8645   SDLoc dl(N);
8646   SmallVector<SDValue, 8> Ops;
8647   unsigned NumElts = VT.getVectorNumElements();
8648   for (unsigned i = 0; i < NumElts; ++i) {
8649     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8650     Ops.push_back(V);
8651     // Make the DAGCombiner fold the bitcast.
8652     DCI.AddToWorklist(V.getNode());
8653   }
8654   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8655   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8656   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8657 }
8658
8659 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8660 static SDValue
8661 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8662   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8663   // At that time, we may have inserted bitcasts from integer to float.
8664   // If these bitcasts have survived DAGCombine, change the lowering of this
8665   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8666   // force to use floating point types.
8667
8668   // Make sure we can change the type of the vector.
8669   // This is possible iff:
8670   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8671   //    1.1. Vector is used only once.
8672   //    1.2. Use is a bit convert to an integer type.
8673   // 2. The size of its operands are 32-bits (64-bits are not legal).
8674   EVT VT = N->getValueType(0);
8675   EVT EltVT = VT.getVectorElementType();
8676
8677   // Check 1.1. and 2.
8678   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8679     return SDValue();
8680
8681   // By construction, the input type must be float.
8682   assert(EltVT == MVT::f32 && "Unexpected type!");
8683
8684   // Check 1.2.
8685   SDNode *Use = *N->use_begin();
8686   if (Use->getOpcode() != ISD::BITCAST ||
8687       Use->getValueType(0).isFloatingPoint())
8688     return SDValue();
8689
8690   // Check profitability.
8691   // Model is, if more than half of the relevant operands are bitcast from
8692   // i32, turn the build_vector into a sequence of insert_vector_elt.
8693   // Relevant operands are everything that is not statically
8694   // (i.e., at compile time) bitcasted.
8695   unsigned NumOfBitCastedElts = 0;
8696   unsigned NumElts = VT.getVectorNumElements();
8697   unsigned NumOfRelevantElts = NumElts;
8698   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8699     SDValue Elt = N->getOperand(Idx);
8700     if (Elt->getOpcode() == ISD::BITCAST) {
8701       // Assume only bit cast to i32 will go away.
8702       if (Elt->getOperand(0).getValueType() == MVT::i32)
8703         ++NumOfBitCastedElts;
8704     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8705       // Constants are statically casted, thus do not count them as
8706       // relevant operands.
8707       --NumOfRelevantElts;
8708   }
8709
8710   // Check if more than half of the elements require a non-free bitcast.
8711   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8712     return SDValue();
8713
8714   SelectionDAG &DAG = DCI.DAG;
8715   // Create the new vector type.
8716   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8717   // Check if the type is legal.
8718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8719   if (!TLI.isTypeLegal(VecVT))
8720     return SDValue();
8721
8722   // Combine:
8723   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8724   // => BITCAST INSERT_VECTOR_ELT
8725   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8726   //                      (BITCAST EN), N.
8727   SDValue Vec = DAG.getUNDEF(VecVT);
8728   SDLoc dl(N);
8729   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8730     SDValue V = N->getOperand(Idx);
8731     if (V.getOpcode() == ISD::UNDEF)
8732       continue;
8733     if (V.getOpcode() == ISD::BITCAST &&
8734         V->getOperand(0).getValueType() == MVT::i32)
8735       // Fold obvious case.
8736       V = V.getOperand(0);
8737     else {
8738       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8739       // Make the DAGCombiner fold the bitcasts.
8740       DCI.AddToWorklist(V.getNode());
8741     }
8742     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8743     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8744   }
8745   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8746   // Make the DAGCombiner fold the bitcasts.
8747   DCI.AddToWorklist(Vec.getNode());
8748   return Vec;
8749 }
8750
8751 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8752 /// ISD::INSERT_VECTOR_ELT.
8753 static SDValue PerformInsertEltCombine(SDNode *N,
8754                                        TargetLowering::DAGCombinerInfo &DCI) {
8755   // Bitcast an i64 load inserted into a vector to f64.
8756   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8757   EVT VT = N->getValueType(0);
8758   SDNode *Elt = N->getOperand(1).getNode();
8759   if (VT.getVectorElementType() != MVT::i64 ||
8760       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8761     return SDValue();
8762
8763   SelectionDAG &DAG = DCI.DAG;
8764   SDLoc dl(N);
8765   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8766                                  VT.getVectorNumElements());
8767   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8768   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8769   // Make the DAGCombiner fold the bitcasts.
8770   DCI.AddToWorklist(Vec.getNode());
8771   DCI.AddToWorklist(V.getNode());
8772   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8773                                Vec, V, N->getOperand(2));
8774   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8775 }
8776
8777 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8778 /// ISD::VECTOR_SHUFFLE.
8779 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8780   // The LLVM shufflevector instruction does not require the shuffle mask
8781   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8782   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8783   // operands do not match the mask length, they are extended by concatenating
8784   // them with undef vectors.  That is probably the right thing for other
8785   // targets, but for NEON it is better to concatenate two double-register
8786   // size vector operands into a single quad-register size vector.  Do that
8787   // transformation here:
8788   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8789   //   shuffle(concat(v1, v2), undef)
8790   SDValue Op0 = N->getOperand(0);
8791   SDValue Op1 = N->getOperand(1);
8792   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8793       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8794       Op0.getNumOperands() != 2 ||
8795       Op1.getNumOperands() != 2)
8796     return SDValue();
8797   SDValue Concat0Op1 = Op0.getOperand(1);
8798   SDValue Concat1Op1 = Op1.getOperand(1);
8799   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8800       Concat1Op1.getOpcode() != ISD::UNDEF)
8801     return SDValue();
8802   // Skip the transformation if any of the types are illegal.
8803   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8804   EVT VT = N->getValueType(0);
8805   if (!TLI.isTypeLegal(VT) ||
8806       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8807       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8808     return SDValue();
8809
8810   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8811                                   Op0.getOperand(0), Op1.getOperand(0));
8812   // Translate the shuffle mask.
8813   SmallVector<int, 16> NewMask;
8814   unsigned NumElts = VT.getVectorNumElements();
8815   unsigned HalfElts = NumElts/2;
8816   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8817   for (unsigned n = 0; n < NumElts; ++n) {
8818     int MaskElt = SVN->getMaskElt(n);
8819     int NewElt = -1;
8820     if (MaskElt < (int)HalfElts)
8821       NewElt = MaskElt;
8822     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8823       NewElt = HalfElts + MaskElt - NumElts;
8824     NewMask.push_back(NewElt);
8825   }
8826   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8827                               DAG.getUNDEF(VT), NewMask.data());
8828 }
8829
8830 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8831 /// NEON load/store intrinsics to merge base address updates.
8832 static SDValue CombineBaseUpdate(SDNode *N,
8833                                  TargetLowering::DAGCombinerInfo &DCI) {
8834   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8835     return SDValue();
8836
8837   SelectionDAG &DAG = DCI.DAG;
8838   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8839                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8840   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8841   SDValue Addr = N->getOperand(AddrOpIdx);
8842
8843   // Search for a use of the address operand that is an increment.
8844   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8845          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8846     SDNode *User = *UI;
8847     if (User->getOpcode() != ISD::ADD ||
8848         UI.getUse().getResNo() != Addr.getResNo())
8849       continue;
8850
8851     // Check that the add is independent of the load/store.  Otherwise, folding
8852     // it would create a cycle.
8853     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8854       continue;
8855
8856     // Find the new opcode for the updating load/store.
8857     bool isLoad = true;
8858     bool isLaneOp = false;
8859     unsigned NewOpc = 0;
8860     unsigned NumVecs = 0;
8861     if (isIntrinsic) {
8862       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8863       switch (IntNo) {
8864       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8865       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8866         NumVecs = 1; break;
8867       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8868         NumVecs = 2; break;
8869       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8870         NumVecs = 3; break;
8871       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8872         NumVecs = 4; break;
8873       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8874         NumVecs = 2; isLaneOp = true; break;
8875       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8876         NumVecs = 3; isLaneOp = true; break;
8877       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8878         NumVecs = 4; isLaneOp = true; break;
8879       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8880         NumVecs = 1; isLoad = false; break;
8881       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8882         NumVecs = 2; isLoad = false; break;
8883       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8884         NumVecs = 3; isLoad = false; break;
8885       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8886         NumVecs = 4; isLoad = false; break;
8887       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8888         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8889       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8890         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8891       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8892         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8893       }
8894     } else {
8895       isLaneOp = true;
8896       switch (N->getOpcode()) {
8897       default: llvm_unreachable("unexpected opcode for Neon base update");
8898       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8899       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8900       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8901       }
8902     }
8903
8904     // Find the size of memory referenced by the load/store.
8905     EVT VecTy;
8906     if (isLoad)
8907       VecTy = N->getValueType(0);
8908     else
8909       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8910     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8911     if (isLaneOp)
8912       NumBytes /= VecTy.getVectorNumElements();
8913
8914     // If the increment is a constant, it must match the memory ref size.
8915     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8916     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8917       uint64_t IncVal = CInc->getZExtValue();
8918       if (IncVal != NumBytes)
8919         continue;
8920     } else if (NumBytes >= 3 * 16) {
8921       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8922       // separate instructions that make it harder to use a non-constant update.
8923       continue;
8924     }
8925
8926     // Create the new updating load/store node.
8927     EVT Tys[6];
8928     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8929     unsigned n;
8930     for (n = 0; n < NumResultVecs; ++n)
8931       Tys[n] = VecTy;
8932     Tys[n++] = MVT::i32;
8933     Tys[n] = MVT::Other;
8934     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8935     SmallVector<SDValue, 8> Ops;
8936     Ops.push_back(N->getOperand(0)); // incoming chain
8937     Ops.push_back(N->getOperand(AddrOpIdx));
8938     Ops.push_back(Inc);
8939     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8940       Ops.push_back(N->getOperand(i));
8941     }
8942     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8943     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8944                                            Ops, MemInt->getMemoryVT(),
8945                                            MemInt->getMemOperand());
8946
8947     // Update the uses.
8948     std::vector<SDValue> NewResults;
8949     for (unsigned i = 0; i < NumResultVecs; ++i) {
8950       NewResults.push_back(SDValue(UpdN.getNode(), i));
8951     }
8952     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8953     DCI.CombineTo(N, NewResults);
8954     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8955
8956     break;
8957   }
8958   return SDValue();
8959 }
8960
8961 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8962 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8963 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8964 /// return true.
8965 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8966   SelectionDAG &DAG = DCI.DAG;
8967   EVT VT = N->getValueType(0);
8968   // vldN-dup instructions only support 64-bit vectors for N > 1.
8969   if (!VT.is64BitVector())
8970     return false;
8971
8972   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8973   SDNode *VLD = N->getOperand(0).getNode();
8974   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8975     return false;
8976   unsigned NumVecs = 0;
8977   unsigned NewOpc = 0;
8978   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8979   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8980     NumVecs = 2;
8981     NewOpc = ARMISD::VLD2DUP;
8982   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8983     NumVecs = 3;
8984     NewOpc = ARMISD::VLD3DUP;
8985   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8986     NumVecs = 4;
8987     NewOpc = ARMISD::VLD4DUP;
8988   } else {
8989     return false;
8990   }
8991
8992   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8993   // numbers match the load.
8994   unsigned VLDLaneNo =
8995     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8996   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8997        UI != UE; ++UI) {
8998     // Ignore uses of the chain result.
8999     if (UI.getUse().getResNo() == NumVecs)
9000       continue;
9001     SDNode *User = *UI;
9002     if (User->getOpcode() != ARMISD::VDUPLANE ||
9003         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9004       return false;
9005   }
9006
9007   // Create the vldN-dup node.
9008   EVT Tys[5];
9009   unsigned n;
9010   for (n = 0; n < NumVecs; ++n)
9011     Tys[n] = VT;
9012   Tys[n] = MVT::Other;
9013   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
9014   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9015   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9016   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9017                                            Ops, VLDMemInt->getMemoryVT(),
9018                                            VLDMemInt->getMemOperand());
9019
9020   // Update the uses.
9021   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9022        UI != UE; ++UI) {
9023     unsigned ResNo = UI.getUse().getResNo();
9024     // Ignore uses of the chain result.
9025     if (ResNo == NumVecs)
9026       continue;
9027     SDNode *User = *UI;
9028     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9029   }
9030
9031   // Now the vldN-lane intrinsic is dead except for its chain result.
9032   // Update uses of the chain.
9033   std::vector<SDValue> VLDDupResults;
9034   for (unsigned n = 0; n < NumVecs; ++n)
9035     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9036   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9037   DCI.CombineTo(VLD, VLDDupResults);
9038
9039   return true;
9040 }
9041
9042 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9043 /// ARMISD::VDUPLANE.
9044 static SDValue PerformVDUPLANECombine(SDNode *N,
9045                                       TargetLowering::DAGCombinerInfo &DCI) {
9046   SDValue Op = N->getOperand(0);
9047
9048   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9049   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9050   if (CombineVLDDUP(N, DCI))
9051     return SDValue(N, 0);
9052
9053   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9054   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9055   while (Op.getOpcode() == ISD::BITCAST)
9056     Op = Op.getOperand(0);
9057   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9058     return SDValue();
9059
9060   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9061   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9062   // The canonical VMOV for a zero vector uses a 32-bit element size.
9063   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9064   unsigned EltBits;
9065   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9066     EltSize = 8;
9067   EVT VT = N->getValueType(0);
9068   if (EltSize > VT.getVectorElementType().getSizeInBits())
9069     return SDValue();
9070
9071   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9072 }
9073
9074 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9075 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9076 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9077 {
9078   integerPart cN;
9079   integerPart c0 = 0;
9080   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9081        I != E; I++) {
9082     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9083     if (!C)
9084       return false;
9085
9086     bool isExact;
9087     APFloat APF = C->getValueAPF();
9088     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9089         != APFloat::opOK || !isExact)
9090       return false;
9091
9092     c0 = (I == 0) ? cN : c0;
9093     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9094       return false;
9095   }
9096   C = c0;
9097   return true;
9098 }
9099
9100 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9101 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9102 /// when the VMUL has a constant operand that is a power of 2.
9103 ///
9104 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9105 ///  vmul.f32        d16, d17, d16
9106 ///  vcvt.s32.f32    d16, d16
9107 /// becomes:
9108 ///  vcvt.s32.f32    d16, d16, #3
9109 static SDValue PerformVCVTCombine(SDNode *N,
9110                                   TargetLowering::DAGCombinerInfo &DCI,
9111                                   const ARMSubtarget *Subtarget) {
9112   SelectionDAG &DAG = DCI.DAG;
9113   SDValue Op = N->getOperand(0);
9114
9115   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9116       Op.getOpcode() != ISD::FMUL)
9117     return SDValue();
9118
9119   uint64_t C;
9120   SDValue N0 = Op->getOperand(0);
9121   SDValue ConstVec = Op->getOperand(1);
9122   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9123
9124   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9125       !isConstVecPow2(ConstVec, isSigned, C))
9126     return SDValue();
9127
9128   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9129   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9130   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9131     // These instructions only exist converting from f32 to i32. We can handle
9132     // smaller integers by generating an extra truncate, but larger ones would
9133     // be lossy.
9134     return SDValue();
9135   }
9136
9137   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9138     Intrinsic::arm_neon_vcvtfp2fxu;
9139   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9140   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9141                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9142                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9143                                  DAG.getConstant(Log2_64(C), MVT::i32));
9144
9145   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9146     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9147
9148   return FixConv;
9149 }
9150
9151 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9152 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9153 /// when the VDIV has a constant operand that is a power of 2.
9154 ///
9155 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9156 ///  vcvt.f32.s32    d16, d16
9157 ///  vdiv.f32        d16, d17, d16
9158 /// becomes:
9159 ///  vcvt.f32.s32    d16, d16, #3
9160 static SDValue PerformVDIVCombine(SDNode *N,
9161                                   TargetLowering::DAGCombinerInfo &DCI,
9162                                   const ARMSubtarget *Subtarget) {
9163   SelectionDAG &DAG = DCI.DAG;
9164   SDValue Op = N->getOperand(0);
9165   unsigned OpOpcode = Op.getNode()->getOpcode();
9166
9167   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9168       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9169     return SDValue();
9170
9171   uint64_t C;
9172   SDValue ConstVec = N->getOperand(1);
9173   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9174
9175   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9176       !isConstVecPow2(ConstVec, isSigned, C))
9177     return SDValue();
9178
9179   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9180   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9181   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9182     // These instructions only exist converting from i32 to f32. We can handle
9183     // smaller integers by generating an extra extend, but larger ones would
9184     // be lossy.
9185     return SDValue();
9186   }
9187
9188   SDValue ConvInput = Op.getOperand(0);
9189   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9190   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9191     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9192                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9193                             ConvInput);
9194
9195   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9196     Intrinsic::arm_neon_vcvtfxu2fp;
9197   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9198                      Op.getValueType(),
9199                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9200                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9201 }
9202
9203 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9204 /// operand of a vector shift operation, where all the elements of the
9205 /// build_vector must have the same constant integer value.
9206 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9207   // Ignore bit_converts.
9208   while (Op.getOpcode() == ISD::BITCAST)
9209     Op = Op.getOperand(0);
9210   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9211   APInt SplatBits, SplatUndef;
9212   unsigned SplatBitSize;
9213   bool HasAnyUndefs;
9214   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9215                                       HasAnyUndefs, ElementBits) ||
9216       SplatBitSize > ElementBits)
9217     return false;
9218   Cnt = SplatBits.getSExtValue();
9219   return true;
9220 }
9221
9222 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9223 /// operand of a vector shift left operation.  That value must be in the range:
9224 ///   0 <= Value < ElementBits for a left shift; or
9225 ///   0 <= Value <= ElementBits for a long left shift.
9226 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9227   assert(VT.isVector() && "vector shift count is not a vector type");
9228   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9229   if (! getVShiftImm(Op, ElementBits, Cnt))
9230     return false;
9231   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9232 }
9233
9234 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9235 /// operand of a vector shift right operation.  For a shift opcode, the value
9236 /// is positive, but for an intrinsic the value count must be negative. The
9237 /// absolute value must be in the range:
9238 ///   1 <= |Value| <= ElementBits for a right shift; or
9239 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9240 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9241                          int64_t &Cnt) {
9242   assert(VT.isVector() && "vector shift count is not a vector type");
9243   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9244   if (! getVShiftImm(Op, ElementBits, Cnt))
9245     return false;
9246   if (isIntrinsic)
9247     Cnt = -Cnt;
9248   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9249 }
9250
9251 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9252 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9253   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9254   switch (IntNo) {
9255   default:
9256     // Don't do anything for most intrinsics.
9257     break;
9258
9259   // Vector shifts: check for immediate versions and lower them.
9260   // Note: This is done during DAG combining instead of DAG legalizing because
9261   // the build_vectors for 64-bit vector element shift counts are generally
9262   // not legal, and it is hard to see their values after they get legalized to
9263   // loads from a constant pool.
9264   case Intrinsic::arm_neon_vshifts:
9265   case Intrinsic::arm_neon_vshiftu:
9266   case Intrinsic::arm_neon_vrshifts:
9267   case Intrinsic::arm_neon_vrshiftu:
9268   case Intrinsic::arm_neon_vrshiftn:
9269   case Intrinsic::arm_neon_vqshifts:
9270   case Intrinsic::arm_neon_vqshiftu:
9271   case Intrinsic::arm_neon_vqshiftsu:
9272   case Intrinsic::arm_neon_vqshiftns:
9273   case Intrinsic::arm_neon_vqshiftnu:
9274   case Intrinsic::arm_neon_vqshiftnsu:
9275   case Intrinsic::arm_neon_vqrshiftns:
9276   case Intrinsic::arm_neon_vqrshiftnu:
9277   case Intrinsic::arm_neon_vqrshiftnsu: {
9278     EVT VT = N->getOperand(1).getValueType();
9279     int64_t Cnt;
9280     unsigned VShiftOpc = 0;
9281
9282     switch (IntNo) {
9283     case Intrinsic::arm_neon_vshifts:
9284     case Intrinsic::arm_neon_vshiftu:
9285       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9286         VShiftOpc = ARMISD::VSHL;
9287         break;
9288       }
9289       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9290         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9291                      ARMISD::VSHRs : ARMISD::VSHRu);
9292         break;
9293       }
9294       return SDValue();
9295
9296     case Intrinsic::arm_neon_vrshifts:
9297     case Intrinsic::arm_neon_vrshiftu:
9298       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9299         break;
9300       return SDValue();
9301
9302     case Intrinsic::arm_neon_vqshifts:
9303     case Intrinsic::arm_neon_vqshiftu:
9304       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9305         break;
9306       return SDValue();
9307
9308     case Intrinsic::arm_neon_vqshiftsu:
9309       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9310         break;
9311       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9312
9313     case Intrinsic::arm_neon_vrshiftn:
9314     case Intrinsic::arm_neon_vqshiftns:
9315     case Intrinsic::arm_neon_vqshiftnu:
9316     case Intrinsic::arm_neon_vqshiftnsu:
9317     case Intrinsic::arm_neon_vqrshiftns:
9318     case Intrinsic::arm_neon_vqrshiftnu:
9319     case Intrinsic::arm_neon_vqrshiftnsu:
9320       // Narrowing shifts require an immediate right shift.
9321       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9322         break;
9323       llvm_unreachable("invalid shift count for narrowing vector shift "
9324                        "intrinsic");
9325
9326     default:
9327       llvm_unreachable("unhandled vector shift");
9328     }
9329
9330     switch (IntNo) {
9331     case Intrinsic::arm_neon_vshifts:
9332     case Intrinsic::arm_neon_vshiftu:
9333       // Opcode already set above.
9334       break;
9335     case Intrinsic::arm_neon_vrshifts:
9336       VShiftOpc = ARMISD::VRSHRs; break;
9337     case Intrinsic::arm_neon_vrshiftu:
9338       VShiftOpc = ARMISD::VRSHRu; break;
9339     case Intrinsic::arm_neon_vrshiftn:
9340       VShiftOpc = ARMISD::VRSHRN; break;
9341     case Intrinsic::arm_neon_vqshifts:
9342       VShiftOpc = ARMISD::VQSHLs; break;
9343     case Intrinsic::arm_neon_vqshiftu:
9344       VShiftOpc = ARMISD::VQSHLu; break;
9345     case Intrinsic::arm_neon_vqshiftsu:
9346       VShiftOpc = ARMISD::VQSHLsu; break;
9347     case Intrinsic::arm_neon_vqshiftns:
9348       VShiftOpc = ARMISD::VQSHRNs; break;
9349     case Intrinsic::arm_neon_vqshiftnu:
9350       VShiftOpc = ARMISD::VQSHRNu; break;
9351     case Intrinsic::arm_neon_vqshiftnsu:
9352       VShiftOpc = ARMISD::VQSHRNsu; break;
9353     case Intrinsic::arm_neon_vqrshiftns:
9354       VShiftOpc = ARMISD::VQRSHRNs; break;
9355     case Intrinsic::arm_neon_vqrshiftnu:
9356       VShiftOpc = ARMISD::VQRSHRNu; break;
9357     case Intrinsic::arm_neon_vqrshiftnsu:
9358       VShiftOpc = ARMISD::VQRSHRNsu; break;
9359     }
9360
9361     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9362                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9363   }
9364
9365   case Intrinsic::arm_neon_vshiftins: {
9366     EVT VT = N->getOperand(1).getValueType();
9367     int64_t Cnt;
9368     unsigned VShiftOpc = 0;
9369
9370     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9371       VShiftOpc = ARMISD::VSLI;
9372     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9373       VShiftOpc = ARMISD::VSRI;
9374     else {
9375       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9376     }
9377
9378     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9379                        N->getOperand(1), N->getOperand(2),
9380                        DAG.getConstant(Cnt, MVT::i32));
9381   }
9382
9383   case Intrinsic::arm_neon_vqrshifts:
9384   case Intrinsic::arm_neon_vqrshiftu:
9385     // No immediate versions of these to check for.
9386     break;
9387   }
9388
9389   return SDValue();
9390 }
9391
9392 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9393 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9394 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9395 /// vector element shift counts are generally not legal, and it is hard to see
9396 /// their values after they get legalized to loads from a constant pool.
9397 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9398                                    const ARMSubtarget *ST) {
9399   EVT VT = N->getValueType(0);
9400   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9401     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9402     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9403     SDValue N1 = N->getOperand(1);
9404     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9405       SDValue N0 = N->getOperand(0);
9406       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9407           DAG.MaskedValueIsZero(N0.getOperand(0),
9408                                 APInt::getHighBitsSet(32, 16)))
9409         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9410     }
9411   }
9412
9413   // Nothing to be done for scalar shifts.
9414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9415   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9416     return SDValue();
9417
9418   assert(ST->hasNEON() && "unexpected vector shift");
9419   int64_t Cnt;
9420
9421   switch (N->getOpcode()) {
9422   default: llvm_unreachable("unexpected shift opcode");
9423
9424   case ISD::SHL:
9425     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9426       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9427                          DAG.getConstant(Cnt, MVT::i32));
9428     break;
9429
9430   case ISD::SRA:
9431   case ISD::SRL:
9432     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9433       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9434                             ARMISD::VSHRs : ARMISD::VSHRu);
9435       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9436                          DAG.getConstant(Cnt, MVT::i32));
9437     }
9438   }
9439   return SDValue();
9440 }
9441
9442 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9443 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9444 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9445                                     const ARMSubtarget *ST) {
9446   SDValue N0 = N->getOperand(0);
9447
9448   // Check for sign- and zero-extensions of vector extract operations of 8-
9449   // and 16-bit vector elements.  NEON supports these directly.  They are
9450   // handled during DAG combining because type legalization will promote them
9451   // to 32-bit types and it is messy to recognize the operations after that.
9452   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9453     SDValue Vec = N0.getOperand(0);
9454     SDValue Lane = N0.getOperand(1);
9455     EVT VT = N->getValueType(0);
9456     EVT EltVT = N0.getValueType();
9457     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9458
9459     if (VT == MVT::i32 &&
9460         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9461         TLI.isTypeLegal(Vec.getValueType()) &&
9462         isa<ConstantSDNode>(Lane)) {
9463
9464       unsigned Opc = 0;
9465       switch (N->getOpcode()) {
9466       default: llvm_unreachable("unexpected opcode");
9467       case ISD::SIGN_EXTEND:
9468         Opc = ARMISD::VGETLANEs;
9469         break;
9470       case ISD::ZERO_EXTEND:
9471       case ISD::ANY_EXTEND:
9472         Opc = ARMISD::VGETLANEu;
9473         break;
9474       }
9475       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9476     }
9477   }
9478
9479   return SDValue();
9480 }
9481
9482 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9483 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9484 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9485                                        const ARMSubtarget *ST) {
9486   // If the target supports NEON, try to use vmax/vmin instructions for f32
9487   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9488   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9489   // a NaN; only do the transformation when it matches that behavior.
9490
9491   // For now only do this when using NEON for FP operations; if using VFP, it
9492   // is not obvious that the benefit outweighs the cost of switching to the
9493   // NEON pipeline.
9494   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9495       N->getValueType(0) != MVT::f32)
9496     return SDValue();
9497
9498   SDValue CondLHS = N->getOperand(0);
9499   SDValue CondRHS = N->getOperand(1);
9500   SDValue LHS = N->getOperand(2);
9501   SDValue RHS = N->getOperand(3);
9502   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9503
9504   unsigned Opcode = 0;
9505   bool IsReversed;
9506   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9507     IsReversed = false; // x CC y ? x : y
9508   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9509     IsReversed = true ; // x CC y ? y : x
9510   } else {
9511     return SDValue();
9512   }
9513
9514   bool IsUnordered;
9515   switch (CC) {
9516   default: break;
9517   case ISD::SETOLT:
9518   case ISD::SETOLE:
9519   case ISD::SETLT:
9520   case ISD::SETLE:
9521   case ISD::SETULT:
9522   case ISD::SETULE:
9523     // If LHS is NaN, an ordered comparison will be false and the result will
9524     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9525     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9526     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9527     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9528       break;
9529     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9530     // will return -0, so vmin can only be used for unsafe math or if one of
9531     // the operands is known to be nonzero.
9532     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9533         !DAG.getTarget().Options.UnsafeFPMath &&
9534         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9535       break;
9536     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9537     break;
9538
9539   case ISD::SETOGT:
9540   case ISD::SETOGE:
9541   case ISD::SETGT:
9542   case ISD::SETGE:
9543   case ISD::SETUGT:
9544   case ISD::SETUGE:
9545     // If LHS is NaN, an ordered comparison will be false and the result will
9546     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9547     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9548     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9549     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9550       break;
9551     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9552     // will return +0, so vmax can only be used for unsafe math or if one of
9553     // the operands is known to be nonzero.
9554     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9555         !DAG.getTarget().Options.UnsafeFPMath &&
9556         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9557       break;
9558     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9559     break;
9560   }
9561
9562   if (!Opcode)
9563     return SDValue();
9564   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9565 }
9566
9567 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9568 SDValue
9569 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9570   SDValue Cmp = N->getOperand(4);
9571   if (Cmp.getOpcode() != ARMISD::CMPZ)
9572     // Only looking at EQ and NE cases.
9573     return SDValue();
9574
9575   EVT VT = N->getValueType(0);
9576   SDLoc dl(N);
9577   SDValue LHS = Cmp.getOperand(0);
9578   SDValue RHS = Cmp.getOperand(1);
9579   SDValue FalseVal = N->getOperand(0);
9580   SDValue TrueVal = N->getOperand(1);
9581   SDValue ARMcc = N->getOperand(2);
9582   ARMCC::CondCodes CC =
9583     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9584
9585   // Simplify
9586   //   mov     r1, r0
9587   //   cmp     r1, x
9588   //   mov     r0, y
9589   //   moveq   r0, x
9590   // to
9591   //   cmp     r0, x
9592   //   movne   r0, y
9593   //
9594   //   mov     r1, r0
9595   //   cmp     r1, x
9596   //   mov     r0, x
9597   //   movne   r0, y
9598   // to
9599   //   cmp     r0, x
9600   //   movne   r0, y
9601   /// FIXME: Turn this into a target neutral optimization?
9602   SDValue Res;
9603   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9604     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9605                       N->getOperand(3), Cmp);
9606   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9607     SDValue ARMcc;
9608     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9609     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9610                       N->getOperand(3), NewCmp);
9611   }
9612
9613   if (Res.getNode()) {
9614     APInt KnownZero, KnownOne;
9615     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9616     // Capture demanded bits information that would be otherwise lost.
9617     if (KnownZero == 0xfffffffe)
9618       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9619                         DAG.getValueType(MVT::i1));
9620     else if (KnownZero == 0xffffff00)
9621       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9622                         DAG.getValueType(MVT::i8));
9623     else if (KnownZero == 0xffff0000)
9624       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9625                         DAG.getValueType(MVT::i16));
9626   }
9627
9628   return Res;
9629 }
9630
9631 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9632                                              DAGCombinerInfo &DCI) const {
9633   switch (N->getOpcode()) {
9634   default: break;
9635   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9636   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9637   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9638   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9639   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9640   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9641   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9642   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9643   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9644   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9645   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9646   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9647   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9648   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9649   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9650   case ISD::FP_TO_SINT:
9651   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9652   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9653   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9654   case ISD::SHL:
9655   case ISD::SRA:
9656   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9657   case ISD::SIGN_EXTEND:
9658   case ISD::ZERO_EXTEND:
9659   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9660   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9661   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9662   case ARMISD::VLD2DUP:
9663   case ARMISD::VLD3DUP:
9664   case ARMISD::VLD4DUP:
9665     return CombineBaseUpdate(N, DCI);
9666   case ARMISD::BUILD_VECTOR:
9667     return PerformARMBUILD_VECTORCombine(N, DCI);
9668   case ISD::INTRINSIC_VOID:
9669   case ISD::INTRINSIC_W_CHAIN:
9670     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9671     case Intrinsic::arm_neon_vld1:
9672     case Intrinsic::arm_neon_vld2:
9673     case Intrinsic::arm_neon_vld3:
9674     case Intrinsic::arm_neon_vld4:
9675     case Intrinsic::arm_neon_vld2lane:
9676     case Intrinsic::arm_neon_vld3lane:
9677     case Intrinsic::arm_neon_vld4lane:
9678     case Intrinsic::arm_neon_vst1:
9679     case Intrinsic::arm_neon_vst2:
9680     case Intrinsic::arm_neon_vst3:
9681     case Intrinsic::arm_neon_vst4:
9682     case Intrinsic::arm_neon_vst2lane:
9683     case Intrinsic::arm_neon_vst3lane:
9684     case Intrinsic::arm_neon_vst4lane:
9685       return CombineBaseUpdate(N, DCI);
9686     default: break;
9687     }
9688     break;
9689   }
9690   return SDValue();
9691 }
9692
9693 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9694                                                           EVT VT) const {
9695   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9696 }
9697
9698 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9699                                                        unsigned,
9700                                                        unsigned,
9701                                                        bool *Fast) const {
9702   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9703   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9704
9705   switch (VT.getSimpleVT().SimpleTy) {
9706   default:
9707     return false;
9708   case MVT::i8:
9709   case MVT::i16:
9710   case MVT::i32: {
9711     // Unaligned access can use (for example) LRDB, LRDH, LDR
9712     if (AllowsUnaligned) {
9713       if (Fast)
9714         *Fast = Subtarget->hasV7Ops();
9715       return true;
9716     }
9717     return false;
9718   }
9719   case MVT::f64:
9720   case MVT::v2f64: {
9721     // For any little-endian targets with neon, we can support unaligned ld/st
9722     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9723     // A big-endian target may also explicitly support unaligned accesses
9724     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9725       if (Fast)
9726         *Fast = true;
9727       return true;
9728     }
9729     return false;
9730   }
9731   }
9732 }
9733
9734 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9735                        unsigned AlignCheck) {
9736   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9737           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9738 }
9739
9740 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9741                                            unsigned DstAlign, unsigned SrcAlign,
9742                                            bool IsMemset, bool ZeroMemset,
9743                                            bool MemcpyStrSrc,
9744                                            MachineFunction &MF) const {
9745   const Function *F = MF.getFunction();
9746
9747   // See if we can use NEON instructions for this...
9748   if ((!IsMemset || ZeroMemset) &&
9749       Subtarget->hasNEON() &&
9750       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9751                                        Attribute::NoImplicitFloat)) {
9752     bool Fast;
9753     if (Size >= 16 &&
9754         (memOpAlign(SrcAlign, DstAlign, 16) ||
9755          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
9756       return MVT::v2f64;
9757     } else if (Size >= 8 &&
9758                (memOpAlign(SrcAlign, DstAlign, 8) ||
9759                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
9760                  Fast))) {
9761       return MVT::f64;
9762     }
9763   }
9764
9765   // Lowering to i32/i16 if the size permits.
9766   if (Size >= 4)
9767     return MVT::i32;
9768   else if (Size >= 2)
9769     return MVT::i16;
9770
9771   // Let the target-independent logic figure it out.
9772   return MVT::Other;
9773 }
9774
9775 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9776   if (Val.getOpcode() != ISD::LOAD)
9777     return false;
9778
9779   EVT VT1 = Val.getValueType();
9780   if (!VT1.isSimple() || !VT1.isInteger() ||
9781       !VT2.isSimple() || !VT2.isInteger())
9782     return false;
9783
9784   switch (VT1.getSimpleVT().SimpleTy) {
9785   default: break;
9786   case MVT::i1:
9787   case MVT::i8:
9788   case MVT::i16:
9789     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9790     return true;
9791   }
9792
9793   return false;
9794 }
9795
9796 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9797   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9798     return false;
9799
9800   if (!isTypeLegal(EVT::getEVT(Ty1)))
9801     return false;
9802
9803   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9804
9805   // Assuming the caller doesn't have a zeroext or signext return parameter,
9806   // truncation all the way down to i1 is valid.
9807   return true;
9808 }
9809
9810
9811 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9812   if (V < 0)
9813     return false;
9814
9815   unsigned Scale = 1;
9816   switch (VT.getSimpleVT().SimpleTy) {
9817   default: return false;
9818   case MVT::i1:
9819   case MVT::i8:
9820     // Scale == 1;
9821     break;
9822   case MVT::i16:
9823     // Scale == 2;
9824     Scale = 2;
9825     break;
9826   case MVT::i32:
9827     // Scale == 4;
9828     Scale = 4;
9829     break;
9830   }
9831
9832   if ((V & (Scale - 1)) != 0)
9833     return false;
9834   V /= Scale;
9835   return V == (V & ((1LL << 5) - 1));
9836 }
9837
9838 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9839                                       const ARMSubtarget *Subtarget) {
9840   bool isNeg = false;
9841   if (V < 0) {
9842     isNeg = true;
9843     V = - V;
9844   }
9845
9846   switch (VT.getSimpleVT().SimpleTy) {
9847   default: return false;
9848   case MVT::i1:
9849   case MVT::i8:
9850   case MVT::i16:
9851   case MVT::i32:
9852     // + imm12 or - imm8
9853     if (isNeg)
9854       return V == (V & ((1LL << 8) - 1));
9855     return V == (V & ((1LL << 12) - 1));
9856   case MVT::f32:
9857   case MVT::f64:
9858     // Same as ARM mode. FIXME: NEON?
9859     if (!Subtarget->hasVFP2())
9860       return false;
9861     if ((V & 3) != 0)
9862       return false;
9863     V >>= 2;
9864     return V == (V & ((1LL << 8) - 1));
9865   }
9866 }
9867
9868 /// isLegalAddressImmediate - Return true if the integer value can be used
9869 /// as the offset of the target addressing mode for load / store of the
9870 /// given type.
9871 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9872                                     const ARMSubtarget *Subtarget) {
9873   if (V == 0)
9874     return true;
9875
9876   if (!VT.isSimple())
9877     return false;
9878
9879   if (Subtarget->isThumb1Only())
9880     return isLegalT1AddressImmediate(V, VT);
9881   else if (Subtarget->isThumb2())
9882     return isLegalT2AddressImmediate(V, VT, Subtarget);
9883
9884   // ARM mode.
9885   if (V < 0)
9886     V = - V;
9887   switch (VT.getSimpleVT().SimpleTy) {
9888   default: return false;
9889   case MVT::i1:
9890   case MVT::i8:
9891   case MVT::i32:
9892     // +- imm12
9893     return V == (V & ((1LL << 12) - 1));
9894   case MVT::i16:
9895     // +- imm8
9896     return V == (V & ((1LL << 8) - 1));
9897   case MVT::f32:
9898   case MVT::f64:
9899     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9900       return false;
9901     if ((V & 3) != 0)
9902       return false;
9903     V >>= 2;
9904     return V == (V & ((1LL << 8) - 1));
9905   }
9906 }
9907
9908 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9909                                                       EVT VT) const {
9910   int Scale = AM.Scale;
9911   if (Scale < 0)
9912     return false;
9913
9914   switch (VT.getSimpleVT().SimpleTy) {
9915   default: return false;
9916   case MVT::i1:
9917   case MVT::i8:
9918   case MVT::i16:
9919   case MVT::i32:
9920     if (Scale == 1)
9921       return true;
9922     // r + r << imm
9923     Scale = Scale & ~1;
9924     return Scale == 2 || Scale == 4 || Scale == 8;
9925   case MVT::i64:
9926     // r + r
9927     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9928       return true;
9929     return false;
9930   case MVT::isVoid:
9931     // Note, we allow "void" uses (basically, uses that aren't loads or
9932     // stores), because arm allows folding a scale into many arithmetic
9933     // operations.  This should be made more precise and revisited later.
9934
9935     // Allow r << imm, but the imm has to be a multiple of two.
9936     if (Scale & 1) return false;
9937     return isPowerOf2_32(Scale);
9938   }
9939 }
9940
9941 /// isLegalAddressingMode - Return true if the addressing mode represented
9942 /// by AM is legal for this target, for a load/store of the specified type.
9943 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9944                                               Type *Ty) const {
9945   EVT VT = getValueType(Ty, true);
9946   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9947     return false;
9948
9949   // Can never fold addr of global into load/store.
9950   if (AM.BaseGV)
9951     return false;
9952
9953   switch (AM.Scale) {
9954   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9955     break;
9956   case 1:
9957     if (Subtarget->isThumb1Only())
9958       return false;
9959     // FALL THROUGH.
9960   default:
9961     // ARM doesn't support any R+R*scale+imm addr modes.
9962     if (AM.BaseOffs)
9963       return false;
9964
9965     if (!VT.isSimple())
9966       return false;
9967
9968     if (Subtarget->isThumb2())
9969       return isLegalT2ScaledAddressingMode(AM, VT);
9970
9971     int Scale = AM.Scale;
9972     switch (VT.getSimpleVT().SimpleTy) {
9973     default: return false;
9974     case MVT::i1:
9975     case MVT::i8:
9976     case MVT::i32:
9977       if (Scale < 0) Scale = -Scale;
9978       if (Scale == 1)
9979         return true;
9980       // r + r << imm
9981       return isPowerOf2_32(Scale & ~1);
9982     case MVT::i16:
9983     case MVT::i64:
9984       // r + r
9985       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9986         return true;
9987       return false;
9988
9989     case MVT::isVoid:
9990       // Note, we allow "void" uses (basically, uses that aren't loads or
9991       // stores), because arm allows folding a scale into many arithmetic
9992       // operations.  This should be made more precise and revisited later.
9993
9994       // Allow r << imm, but the imm has to be a multiple of two.
9995       if (Scale & 1) return false;
9996       return isPowerOf2_32(Scale);
9997     }
9998   }
9999   return true;
10000 }
10001
10002 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10003 /// icmp immediate, that is the target has icmp instructions which can compare
10004 /// a register against the immediate without having to materialize the
10005 /// immediate into a register.
10006 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10007   // Thumb2 and ARM modes can use cmn for negative immediates.
10008   if (!Subtarget->isThumb())
10009     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
10010   if (Subtarget->isThumb2())
10011     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
10012   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10013   return Imm >= 0 && Imm <= 255;
10014 }
10015
10016 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10017 /// *or sub* immediate, that is the target has add or sub instructions which can
10018 /// add a register with the immediate without having to materialize the
10019 /// immediate into a register.
10020 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10021   // Same encoding for add/sub, just flip the sign.
10022   int64_t AbsImm = llvm::abs64(Imm);
10023   if (!Subtarget->isThumb())
10024     return ARM_AM::getSOImmVal(AbsImm) != -1;
10025   if (Subtarget->isThumb2())
10026     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10027   // Thumb1 only has 8-bit unsigned immediate.
10028   return AbsImm >= 0 && AbsImm <= 255;
10029 }
10030
10031 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10032                                       bool isSEXTLoad, SDValue &Base,
10033                                       SDValue &Offset, bool &isInc,
10034                                       SelectionDAG &DAG) {
10035   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10036     return false;
10037
10038   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10039     // AddressingMode 3
10040     Base = Ptr->getOperand(0);
10041     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10042       int RHSC = (int)RHS->getZExtValue();
10043       if (RHSC < 0 && RHSC > -256) {
10044         assert(Ptr->getOpcode() == ISD::ADD);
10045         isInc = false;
10046         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10047         return true;
10048       }
10049     }
10050     isInc = (Ptr->getOpcode() == ISD::ADD);
10051     Offset = Ptr->getOperand(1);
10052     return true;
10053   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10054     // AddressingMode 2
10055     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10056       int RHSC = (int)RHS->getZExtValue();
10057       if (RHSC < 0 && RHSC > -0x1000) {
10058         assert(Ptr->getOpcode() == ISD::ADD);
10059         isInc = false;
10060         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10061         Base = Ptr->getOperand(0);
10062         return true;
10063       }
10064     }
10065
10066     if (Ptr->getOpcode() == ISD::ADD) {
10067       isInc = true;
10068       ARM_AM::ShiftOpc ShOpcVal=
10069         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10070       if (ShOpcVal != ARM_AM::no_shift) {
10071         Base = Ptr->getOperand(1);
10072         Offset = Ptr->getOperand(0);
10073       } else {
10074         Base = Ptr->getOperand(0);
10075         Offset = Ptr->getOperand(1);
10076       }
10077       return true;
10078     }
10079
10080     isInc = (Ptr->getOpcode() == ISD::ADD);
10081     Base = Ptr->getOperand(0);
10082     Offset = Ptr->getOperand(1);
10083     return true;
10084   }
10085
10086   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10087   return false;
10088 }
10089
10090 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10091                                      bool isSEXTLoad, SDValue &Base,
10092                                      SDValue &Offset, bool &isInc,
10093                                      SelectionDAG &DAG) {
10094   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10095     return false;
10096
10097   Base = Ptr->getOperand(0);
10098   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10099     int RHSC = (int)RHS->getZExtValue();
10100     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10101       assert(Ptr->getOpcode() == ISD::ADD);
10102       isInc = false;
10103       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10104       return true;
10105     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10106       isInc = Ptr->getOpcode() == ISD::ADD;
10107       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10108       return true;
10109     }
10110   }
10111
10112   return false;
10113 }
10114
10115 /// getPreIndexedAddressParts - returns true by value, base pointer and
10116 /// offset pointer and addressing mode by reference if the node's address
10117 /// can be legally represented as pre-indexed load / store address.
10118 bool
10119 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10120                                              SDValue &Offset,
10121                                              ISD::MemIndexedMode &AM,
10122                                              SelectionDAG &DAG) const {
10123   if (Subtarget->isThumb1Only())
10124     return false;
10125
10126   EVT VT;
10127   SDValue Ptr;
10128   bool isSEXTLoad = false;
10129   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10130     Ptr = LD->getBasePtr();
10131     VT  = LD->getMemoryVT();
10132     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10133   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10134     Ptr = ST->getBasePtr();
10135     VT  = ST->getMemoryVT();
10136   } else
10137     return false;
10138
10139   bool isInc;
10140   bool isLegal = false;
10141   if (Subtarget->isThumb2())
10142     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10143                                        Offset, isInc, DAG);
10144   else
10145     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10146                                         Offset, isInc, DAG);
10147   if (!isLegal)
10148     return false;
10149
10150   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10151   return true;
10152 }
10153
10154 /// getPostIndexedAddressParts - returns true by value, base pointer and
10155 /// offset pointer and addressing mode by reference if this node can be
10156 /// combined with a load / store to form a post-indexed load / store.
10157 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10158                                                    SDValue &Base,
10159                                                    SDValue &Offset,
10160                                                    ISD::MemIndexedMode &AM,
10161                                                    SelectionDAG &DAG) const {
10162   if (Subtarget->isThumb1Only())
10163     return false;
10164
10165   EVT VT;
10166   SDValue Ptr;
10167   bool isSEXTLoad = false;
10168   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10169     VT  = LD->getMemoryVT();
10170     Ptr = LD->getBasePtr();
10171     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10172   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10173     VT  = ST->getMemoryVT();
10174     Ptr = ST->getBasePtr();
10175   } else
10176     return false;
10177
10178   bool isInc;
10179   bool isLegal = false;
10180   if (Subtarget->isThumb2())
10181     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10182                                        isInc, DAG);
10183   else
10184     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10185                                         isInc, DAG);
10186   if (!isLegal)
10187     return false;
10188
10189   if (Ptr != Base) {
10190     // Swap base ptr and offset to catch more post-index load / store when
10191     // it's legal. In Thumb2 mode, offset must be an immediate.
10192     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10193         !Subtarget->isThumb2())
10194       std::swap(Base, Offset);
10195
10196     // Post-indexed load / store update the base pointer.
10197     if (Ptr != Base)
10198       return false;
10199   }
10200
10201   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10202   return true;
10203 }
10204
10205 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10206                                                       APInt &KnownZero,
10207                                                       APInt &KnownOne,
10208                                                       const SelectionDAG &DAG,
10209                                                       unsigned Depth) const {
10210   unsigned BitWidth = KnownOne.getBitWidth();
10211   KnownZero = KnownOne = APInt(BitWidth, 0);
10212   switch (Op.getOpcode()) {
10213   default: break;
10214   case ARMISD::ADDC:
10215   case ARMISD::ADDE:
10216   case ARMISD::SUBC:
10217   case ARMISD::SUBE:
10218     // These nodes' second result is a boolean
10219     if (Op.getResNo() == 0)
10220       break;
10221     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10222     break;
10223   case ARMISD::CMOV: {
10224     // Bits are known zero/one if known on the LHS and RHS.
10225     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10226     if (KnownZero == 0 && KnownOne == 0) return;
10227
10228     APInt KnownZeroRHS, KnownOneRHS;
10229     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10230     KnownZero &= KnownZeroRHS;
10231     KnownOne  &= KnownOneRHS;
10232     return;
10233   }
10234   case ISD::INTRINSIC_W_CHAIN: {
10235     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10236     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10237     switch (IntID) {
10238     default: return;
10239     case Intrinsic::arm_ldaex:
10240     case Intrinsic::arm_ldrex: {
10241       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10242       unsigned MemBits = VT.getScalarType().getSizeInBits();
10243       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10244       return;
10245     }
10246     }
10247   }
10248   }
10249 }
10250
10251 //===----------------------------------------------------------------------===//
10252 //                           ARM Inline Assembly Support
10253 //===----------------------------------------------------------------------===//
10254
10255 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10256   // Looking for "rev" which is V6+.
10257   if (!Subtarget->hasV6Ops())
10258     return false;
10259
10260   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10261   std::string AsmStr = IA->getAsmString();
10262   SmallVector<StringRef, 4> AsmPieces;
10263   SplitString(AsmStr, AsmPieces, ";\n");
10264
10265   switch (AsmPieces.size()) {
10266   default: return false;
10267   case 1:
10268     AsmStr = AsmPieces[0];
10269     AsmPieces.clear();
10270     SplitString(AsmStr, AsmPieces, " \t,");
10271
10272     // rev $0, $1
10273     if (AsmPieces.size() == 3 &&
10274         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10275         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10276       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10277       if (Ty && Ty->getBitWidth() == 32)
10278         return IntrinsicLowering::LowerToByteSwap(CI);
10279     }
10280     break;
10281   }
10282
10283   return false;
10284 }
10285
10286 /// getConstraintType - Given a constraint letter, return the type of
10287 /// constraint it is for this target.
10288 ARMTargetLowering::ConstraintType
10289 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10290   if (Constraint.size() == 1) {
10291     switch (Constraint[0]) {
10292     default:  break;
10293     case 'l': return C_RegisterClass;
10294     case 'w': return C_RegisterClass;
10295     case 'h': return C_RegisterClass;
10296     case 'x': return C_RegisterClass;
10297     case 't': return C_RegisterClass;
10298     case 'j': return C_Other; // Constant for movw.
10299       // An address with a single base register. Due to the way we
10300       // currently handle addresses it is the same as an 'r' memory constraint.
10301     case 'Q': return C_Memory;
10302     }
10303   } else if (Constraint.size() == 2) {
10304     switch (Constraint[0]) {
10305     default: break;
10306     // All 'U+' constraints are addresses.
10307     case 'U': return C_Memory;
10308     }
10309   }
10310   return TargetLowering::getConstraintType(Constraint);
10311 }
10312
10313 /// Examine constraint type and operand type and determine a weight value.
10314 /// This object must already have been set up with the operand type
10315 /// and the current alternative constraint selected.
10316 TargetLowering::ConstraintWeight
10317 ARMTargetLowering::getSingleConstraintMatchWeight(
10318     AsmOperandInfo &info, const char *constraint) const {
10319   ConstraintWeight weight = CW_Invalid;
10320   Value *CallOperandVal = info.CallOperandVal;
10321     // If we don't have a value, we can't do a match,
10322     // but allow it at the lowest weight.
10323   if (!CallOperandVal)
10324     return CW_Default;
10325   Type *type = CallOperandVal->getType();
10326   // Look at the constraint type.
10327   switch (*constraint) {
10328   default:
10329     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10330     break;
10331   case 'l':
10332     if (type->isIntegerTy()) {
10333       if (Subtarget->isThumb())
10334         weight = CW_SpecificReg;
10335       else
10336         weight = CW_Register;
10337     }
10338     break;
10339   case 'w':
10340     if (type->isFloatingPointTy())
10341       weight = CW_Register;
10342     break;
10343   }
10344   return weight;
10345 }
10346
10347 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10348 RCPair
10349 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10350                                                 MVT VT) const {
10351   if (Constraint.size() == 1) {
10352     // GCC ARM Constraint Letters
10353     switch (Constraint[0]) {
10354     case 'l': // Low regs or general regs.
10355       if (Subtarget->isThumb())
10356         return RCPair(0U, &ARM::tGPRRegClass);
10357       return RCPair(0U, &ARM::GPRRegClass);
10358     case 'h': // High regs or no regs.
10359       if (Subtarget->isThumb())
10360         return RCPair(0U, &ARM::hGPRRegClass);
10361       break;
10362     case 'r':
10363       return RCPair(0U, &ARM::GPRRegClass);
10364     case 'w':
10365       if (VT == MVT::Other)
10366         break;
10367       if (VT == MVT::f32)
10368         return RCPair(0U, &ARM::SPRRegClass);
10369       if (VT.getSizeInBits() == 64)
10370         return RCPair(0U, &ARM::DPRRegClass);
10371       if (VT.getSizeInBits() == 128)
10372         return RCPair(0U, &ARM::QPRRegClass);
10373       break;
10374     case 'x':
10375       if (VT == MVT::Other)
10376         break;
10377       if (VT == MVT::f32)
10378         return RCPair(0U, &ARM::SPR_8RegClass);
10379       if (VT.getSizeInBits() == 64)
10380         return RCPair(0U, &ARM::DPR_8RegClass);
10381       if (VT.getSizeInBits() == 128)
10382         return RCPair(0U, &ARM::QPR_8RegClass);
10383       break;
10384     case 't':
10385       if (VT == MVT::f32)
10386         return RCPair(0U, &ARM::SPRRegClass);
10387       break;
10388     }
10389   }
10390   if (StringRef("{cc}").equals_lower(Constraint))
10391     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10392
10393   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10394 }
10395
10396 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10397 /// vector.  If it is invalid, don't add anything to Ops.
10398 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10399                                                      std::string &Constraint,
10400                                                      std::vector<SDValue>&Ops,
10401                                                      SelectionDAG &DAG) const {
10402   SDValue Result;
10403
10404   // Currently only support length 1 constraints.
10405   if (Constraint.length() != 1) return;
10406
10407   char ConstraintLetter = Constraint[0];
10408   switch (ConstraintLetter) {
10409   default: break;
10410   case 'j':
10411   case 'I': case 'J': case 'K': case 'L':
10412   case 'M': case 'N': case 'O':
10413     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10414     if (!C)
10415       return;
10416
10417     int64_t CVal64 = C->getSExtValue();
10418     int CVal = (int) CVal64;
10419     // None of these constraints allow values larger than 32 bits.  Check
10420     // that the value fits in an int.
10421     if (CVal != CVal64)
10422       return;
10423
10424     switch (ConstraintLetter) {
10425       case 'j':
10426         // Constant suitable for movw, must be between 0 and
10427         // 65535.
10428         if (Subtarget->hasV6T2Ops())
10429           if (CVal >= 0 && CVal <= 65535)
10430             break;
10431         return;
10432       case 'I':
10433         if (Subtarget->isThumb1Only()) {
10434           // This must be a constant between 0 and 255, for ADD
10435           // immediates.
10436           if (CVal >= 0 && CVal <= 255)
10437             break;
10438         } else if (Subtarget->isThumb2()) {
10439           // A constant that can be used as an immediate value in a
10440           // data-processing instruction.
10441           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10442             break;
10443         } else {
10444           // A constant that can be used as an immediate value in a
10445           // data-processing instruction.
10446           if (ARM_AM::getSOImmVal(CVal) != -1)
10447             break;
10448         }
10449         return;
10450
10451       case 'J':
10452         if (Subtarget->isThumb()) {  // FIXME thumb2
10453           // This must be a constant between -255 and -1, for negated ADD
10454           // immediates. This can be used in GCC with an "n" modifier that
10455           // prints the negated value, for use with SUB instructions. It is
10456           // not useful otherwise but is implemented for compatibility.
10457           if (CVal >= -255 && CVal <= -1)
10458             break;
10459         } else {
10460           // This must be a constant between -4095 and 4095. It is not clear
10461           // what this constraint is intended for. Implemented for
10462           // compatibility with GCC.
10463           if (CVal >= -4095 && CVal <= 4095)
10464             break;
10465         }
10466         return;
10467
10468       case 'K':
10469         if (Subtarget->isThumb1Only()) {
10470           // A 32-bit value where only one byte has a nonzero value. Exclude
10471           // zero to match GCC. This constraint is used by GCC internally for
10472           // constants that can be loaded with a move/shift combination.
10473           // It is not useful otherwise but is implemented for compatibility.
10474           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10475             break;
10476         } else if (Subtarget->isThumb2()) {
10477           // A constant whose bitwise inverse can be used as an immediate
10478           // value in a data-processing instruction. This can be used in GCC
10479           // with a "B" modifier that prints the inverted value, for use with
10480           // BIC and MVN instructions. It is not useful otherwise but is
10481           // implemented for compatibility.
10482           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10483             break;
10484         } else {
10485           // A constant whose bitwise inverse can be used as an immediate
10486           // value in a data-processing instruction. This can be used in GCC
10487           // with a "B" modifier that prints the inverted value, for use with
10488           // BIC and MVN instructions. It is not useful otherwise but is
10489           // implemented for compatibility.
10490           if (ARM_AM::getSOImmVal(~CVal) != -1)
10491             break;
10492         }
10493         return;
10494
10495       case 'L':
10496         if (Subtarget->isThumb1Only()) {
10497           // This must be a constant between -7 and 7,
10498           // for 3-operand ADD/SUB immediate instructions.
10499           if (CVal >= -7 && CVal < 7)
10500             break;
10501         } else if (Subtarget->isThumb2()) {
10502           // A constant whose negation can be used as an immediate value in a
10503           // data-processing instruction. This can be used in GCC with an "n"
10504           // modifier that prints the negated value, for use with SUB
10505           // instructions. It is not useful otherwise but is implemented for
10506           // compatibility.
10507           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10508             break;
10509         } else {
10510           // A constant whose negation can be used as an immediate value in a
10511           // data-processing instruction. This can be used in GCC with an "n"
10512           // modifier that prints the negated value, for use with SUB
10513           // instructions. It is not useful otherwise but is implemented for
10514           // compatibility.
10515           if (ARM_AM::getSOImmVal(-CVal) != -1)
10516             break;
10517         }
10518         return;
10519
10520       case 'M':
10521         if (Subtarget->isThumb()) { // FIXME thumb2
10522           // This must be a multiple of 4 between 0 and 1020, for
10523           // ADD sp + immediate.
10524           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10525             break;
10526         } else {
10527           // A power of two or a constant between 0 and 32.  This is used in
10528           // GCC for the shift amount on shifted register operands, but it is
10529           // useful in general for any shift amounts.
10530           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10531             break;
10532         }
10533         return;
10534
10535       case 'N':
10536         if (Subtarget->isThumb()) {  // FIXME thumb2
10537           // This must be a constant between 0 and 31, for shift amounts.
10538           if (CVal >= 0 && CVal <= 31)
10539             break;
10540         }
10541         return;
10542
10543       case 'O':
10544         if (Subtarget->isThumb()) {  // FIXME thumb2
10545           // This must be a multiple of 4 between -508 and 508, for
10546           // ADD/SUB sp = sp + immediate.
10547           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10548             break;
10549         }
10550         return;
10551     }
10552     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10553     break;
10554   }
10555
10556   if (Result.getNode()) {
10557     Ops.push_back(Result);
10558     return;
10559   }
10560   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10561 }
10562
10563 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10564   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10565   unsigned Opcode = Op->getOpcode();
10566   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10567       "Invalid opcode for Div/Rem lowering");
10568   bool isSigned = (Opcode == ISD::SDIVREM);
10569   EVT VT = Op->getValueType(0);
10570   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10571
10572   RTLIB::Libcall LC;
10573   switch (VT.getSimpleVT().SimpleTy) {
10574   default: llvm_unreachable("Unexpected request for libcall!");
10575   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10576   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10577   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10578   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10579   }
10580
10581   SDValue InChain = DAG.getEntryNode();
10582
10583   TargetLowering::ArgListTy Args;
10584   TargetLowering::ArgListEntry Entry;
10585   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10586     EVT ArgVT = Op->getOperand(i).getValueType();
10587     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10588     Entry.Node = Op->getOperand(i);
10589     Entry.Ty = ArgTy;
10590     Entry.isSExt = isSigned;
10591     Entry.isZExt = !isSigned;
10592     Args.push_back(Entry);
10593   }
10594
10595   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10596                                          getPointerTy());
10597
10598   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10599
10600   SDLoc dl(Op);
10601   TargetLowering::CallLoweringInfo CLI(DAG);
10602   CLI.setDebugLoc(dl).setChain(InChain)
10603     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
10604     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10605
10606   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10607   return CallInfo.first;
10608 }
10609
10610 SDValue
10611 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10612   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10613   SDLoc DL(Op);
10614
10615   // Get the inputs.
10616   SDValue Chain = Op.getOperand(0);
10617   SDValue Size  = Op.getOperand(1);
10618
10619   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10620                               DAG.getConstant(2, MVT::i32));
10621
10622   SDValue Flag;
10623   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10624   Flag = Chain.getValue(1);
10625
10626   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10627   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10628
10629   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10630   Chain = NewSP.getValue(1);
10631
10632   SDValue Ops[2] = { NewSP, Chain };
10633   return DAG.getMergeValues(Ops, DL);
10634 }
10635
10636 bool
10637 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10638   // The ARM target isn't yet aware of offsets.
10639   return false;
10640 }
10641
10642 bool ARM::isBitFieldInvertedMask(unsigned v) {
10643   if (v == 0xffffffff)
10644     return false;
10645
10646   // there can be 1's on either or both "outsides", all the "inside"
10647   // bits must be 0's
10648   unsigned TO = CountTrailingOnes_32(v);
10649   unsigned LO = CountLeadingOnes_32(v);
10650   v = (v >> TO) << TO;
10651   v = (v << LO) >> LO;
10652   return v == 0;
10653 }
10654
10655 /// isFPImmLegal - Returns true if the target can instruction select the
10656 /// specified FP immediate natively. If false, the legalizer will
10657 /// materialize the FP immediate as a load from a constant pool.
10658 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10659   if (!Subtarget->hasVFP3())
10660     return false;
10661   if (VT == MVT::f32)
10662     return ARM_AM::getFP32Imm(Imm) != -1;
10663   if (VT == MVT::f64)
10664     return ARM_AM::getFP64Imm(Imm) != -1;
10665   return false;
10666 }
10667
10668 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10669 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10670 /// specified in the intrinsic calls.
10671 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10672                                            const CallInst &I,
10673                                            unsigned Intrinsic) const {
10674   switch (Intrinsic) {
10675   case Intrinsic::arm_neon_vld1:
10676   case Intrinsic::arm_neon_vld2:
10677   case Intrinsic::arm_neon_vld3:
10678   case Intrinsic::arm_neon_vld4:
10679   case Intrinsic::arm_neon_vld2lane:
10680   case Intrinsic::arm_neon_vld3lane:
10681   case Intrinsic::arm_neon_vld4lane: {
10682     Info.opc = ISD::INTRINSIC_W_CHAIN;
10683     // Conservatively set memVT to the entire set of vectors loaded.
10684     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10685     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10686     Info.ptrVal = I.getArgOperand(0);
10687     Info.offset = 0;
10688     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10689     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10690     Info.vol = false; // volatile loads with NEON intrinsics not supported
10691     Info.readMem = true;
10692     Info.writeMem = false;
10693     return true;
10694   }
10695   case Intrinsic::arm_neon_vst1:
10696   case Intrinsic::arm_neon_vst2:
10697   case Intrinsic::arm_neon_vst3:
10698   case Intrinsic::arm_neon_vst4:
10699   case Intrinsic::arm_neon_vst2lane:
10700   case Intrinsic::arm_neon_vst3lane:
10701   case Intrinsic::arm_neon_vst4lane: {
10702     Info.opc = ISD::INTRINSIC_VOID;
10703     // Conservatively set memVT to the entire set of vectors stored.
10704     unsigned NumElts = 0;
10705     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10706       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10707       if (!ArgTy->isVectorTy())
10708         break;
10709       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10710     }
10711     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10712     Info.ptrVal = I.getArgOperand(0);
10713     Info.offset = 0;
10714     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10715     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10716     Info.vol = false; // volatile stores with NEON intrinsics not supported
10717     Info.readMem = false;
10718     Info.writeMem = true;
10719     return true;
10720   }
10721   case Intrinsic::arm_ldaex:
10722   case Intrinsic::arm_ldrex: {
10723     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10724     Info.opc = ISD::INTRINSIC_W_CHAIN;
10725     Info.memVT = MVT::getVT(PtrTy->getElementType());
10726     Info.ptrVal = I.getArgOperand(0);
10727     Info.offset = 0;
10728     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10729     Info.vol = true;
10730     Info.readMem = true;
10731     Info.writeMem = false;
10732     return true;
10733   }
10734   case Intrinsic::arm_stlex:
10735   case Intrinsic::arm_strex: {
10736     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10737     Info.opc = ISD::INTRINSIC_W_CHAIN;
10738     Info.memVT = MVT::getVT(PtrTy->getElementType());
10739     Info.ptrVal = I.getArgOperand(1);
10740     Info.offset = 0;
10741     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10742     Info.vol = true;
10743     Info.readMem = false;
10744     Info.writeMem = true;
10745     return true;
10746   }
10747   case Intrinsic::arm_stlexd:
10748   case Intrinsic::arm_strexd: {
10749     Info.opc = ISD::INTRINSIC_W_CHAIN;
10750     Info.memVT = MVT::i64;
10751     Info.ptrVal = I.getArgOperand(2);
10752     Info.offset = 0;
10753     Info.align = 8;
10754     Info.vol = true;
10755     Info.readMem = false;
10756     Info.writeMem = true;
10757     return true;
10758   }
10759   case Intrinsic::arm_ldaexd:
10760   case Intrinsic::arm_ldrexd: {
10761     Info.opc = ISD::INTRINSIC_W_CHAIN;
10762     Info.memVT = MVT::i64;
10763     Info.ptrVal = I.getArgOperand(0);
10764     Info.offset = 0;
10765     Info.align = 8;
10766     Info.vol = true;
10767     Info.readMem = true;
10768     Info.writeMem = false;
10769     return true;
10770   }
10771   default:
10772     break;
10773   }
10774
10775   return false;
10776 }
10777
10778 /// \brief Returns true if it is beneficial to convert a load of a constant
10779 /// to just the constant itself.
10780 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10781                                                           Type *Ty) const {
10782   assert(Ty->isIntegerTy());
10783
10784   unsigned Bits = Ty->getPrimitiveSizeInBits();
10785   if (Bits == 0 || Bits > 32)
10786     return false;
10787   return true;
10788 }
10789
10790 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10791   // Loads and stores less than 64-bits are already atomic; ones above that
10792   // are doomed anyway, so defer to the default libcall and blame the OS when
10793   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10794   // anything for those.
10795   bool IsMClass = Subtarget->isMClass();
10796   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10797     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10798     return Size == 64 && !IsMClass;
10799   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10800     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10801   }
10802
10803   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10804   // and up to 64 bits on the non-M profiles
10805   unsigned AtomicLimit = IsMClass ? 32 : 64;
10806   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10807 }
10808
10809 // This has so far only been implemented for MachO.
10810 bool ARMTargetLowering::useLoadStackGuardNode() const {
10811   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO;
10812 }
10813
10814 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10815                                          AtomicOrdering Ord) const {
10816   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10817   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10818   bool IsAcquire =
10819       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10820
10821   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10822   // intrinsic must return {i32, i32} and we have to recombine them into a
10823   // single i64 here.
10824   if (ValTy->getPrimitiveSizeInBits() == 64) {
10825     Intrinsic::ID Int =
10826         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10827     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10828
10829     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10830     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10831
10832     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10833     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10834     if (!Subtarget->isLittle())
10835       std::swap (Lo, Hi);
10836     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10837     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10838     return Builder.CreateOr(
10839         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10840   }
10841
10842   Type *Tys[] = { Addr->getType() };
10843   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10844   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10845
10846   return Builder.CreateTruncOrBitCast(
10847       Builder.CreateCall(Ldrex, Addr),
10848       cast<PointerType>(Addr->getType())->getElementType());
10849 }
10850
10851 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10852                                                Value *Addr,
10853                                                AtomicOrdering Ord) const {
10854   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10855   bool IsRelease =
10856       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10857
10858   // Since the intrinsics must have legal type, the i64 intrinsics take two
10859   // parameters: "i32, i32". We must marshal Val into the appropriate form
10860   // before the call.
10861   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10862     Intrinsic::ID Int =
10863         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10864     Function *Strex = Intrinsic::getDeclaration(M, Int);
10865     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10866
10867     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10868     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10869     if (!Subtarget->isLittle())
10870       std::swap (Lo, Hi);
10871     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10872     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10873   }
10874
10875   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10876   Type *Tys[] = { Addr->getType() };
10877   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10878
10879   return Builder.CreateCall2(
10880       Strex, Builder.CreateZExtOrBitCast(
10881                  Val, Strex->getFunctionType()->getParamType(0)),
10882       Addr);
10883 }
10884
10885 enum HABaseType {
10886   HA_UNKNOWN = 0,
10887   HA_FLOAT,
10888   HA_DOUBLE,
10889   HA_VECT64,
10890   HA_VECT128
10891 };
10892
10893 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10894                                    uint64_t &Members) {
10895   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10896     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10897       uint64_t SubMembers = 0;
10898       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10899         return false;
10900       Members += SubMembers;
10901     }
10902   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10903     uint64_t SubMembers = 0;
10904     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10905       return false;
10906     Members += SubMembers * AT->getNumElements();
10907   } else if (Ty->isFloatTy()) {
10908     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10909       return false;
10910     Members = 1;
10911     Base = HA_FLOAT;
10912   } else if (Ty->isDoubleTy()) {
10913     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10914       return false;
10915     Members = 1;
10916     Base = HA_DOUBLE;
10917   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10918     Members = 1;
10919     switch (Base) {
10920     case HA_FLOAT:
10921     case HA_DOUBLE:
10922       return false;
10923     case HA_VECT64:
10924       return VT->getBitWidth() == 64;
10925     case HA_VECT128:
10926       return VT->getBitWidth() == 128;
10927     case HA_UNKNOWN:
10928       switch (VT->getBitWidth()) {
10929       case 64:
10930         Base = HA_VECT64;
10931         return true;
10932       case 128:
10933         Base = HA_VECT128;
10934         return true;
10935       default:
10936         return false;
10937       }
10938     }
10939   }
10940
10941   return (Members > 0 && Members <= 4);
10942 }
10943
10944 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10945 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10946     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10947   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10948       CallingConv::ARM_AAPCS_VFP)
10949     return false;
10950
10951   HABaseType Base = HA_UNKNOWN;
10952   uint64_t Members = 0;
10953   bool result = isHomogeneousAggregate(Ty, Base, Members);
10954   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10955   return result;
10956 }