9905526bf160bef79ffe5f704e01135010107de9
[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::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316
317       // Integer to floating-point conversions.
318       // RTABI chapter 4.1.2, Table 8
319       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
320       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
321       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
326       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
327
328       // Long long helper functions
329       // RTABI chapter 4.2, Table 9
330       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334
335       // Integer division functions
336       // RTABI chapter 4.3.1
337       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
343       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
344       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
345
346       // Memory operations
347       // RTABI chapter 4.3.4
348       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351     };
352
353     for (const auto &LC : LibraryCalls) {
354       setLibcallName(LC.Op, LC.Name);
355       setLibcallCallingConv(LC.Op, LC.CC);
356       if (LC.Cond != ISD::SETCC_INVALID)
357         setCmpLibcallCC(LC.Op, LC.Cond);
358     }
359   }
360
361   if (Subtarget->isTargetWindows()) {
362     static const struct {
363       const RTLIB::Libcall Op;
364       const char * const Name;
365       const CallingConv::ID CC;
366     } LibraryCalls[] = {
367       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
371       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
372       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
373       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
374       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
375     };
376
377     for (const auto &LC : LibraryCalls) {
378       setLibcallName(LC.Op, LC.Name);
379       setLibcallCallingConv(LC.Op, LC.CC);
380     }
381   }
382
383   // Use divmod compiler-rt calls for iOS 5.0 and later.
384   if (Subtarget->getTargetTriple().isiOS() &&
385       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
386     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
387     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
388   }
389
390   if (Subtarget->isThumb1Only())
391     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
392   else
393     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
394   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
395       !Subtarget->isThumb1Only()) {
396     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
397     if (!Subtarget->isFPOnlySP())
398       addRegisterClass(MVT::f64, &ARM::DPRRegClass);
399
400     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
401   }
402
403   for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404        VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
405     for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
406          InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
407       setTruncStoreAction((MVT::SimpleValueType)VT,
408                           (MVT::SimpleValueType)InnerVT, Expand);
409     setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
410     setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
411     setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
412
413     setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
414     setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
415     setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
416     setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
417
418     setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
419   }
420
421   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
422   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
423
424   if (Subtarget->hasNEON()) {
425     addDRTypeForNEON(MVT::v2f32);
426     addDRTypeForNEON(MVT::v8i8);
427     addDRTypeForNEON(MVT::v4i16);
428     addDRTypeForNEON(MVT::v2i32);
429     addDRTypeForNEON(MVT::v1i64);
430
431     addQRTypeForNEON(MVT::v4f32);
432     addQRTypeForNEON(MVT::v2f64);
433     addQRTypeForNEON(MVT::v16i8);
434     addQRTypeForNEON(MVT::v8i16);
435     addQRTypeForNEON(MVT::v4i32);
436     addQRTypeForNEON(MVT::v2i64);
437
438     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
439     // neither Neon nor VFP support any arithmetic operations on it.
440     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
441     // supported for v4f32.
442     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
443     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
444     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
445     // FIXME: Code duplication: FDIV and FREM are expanded always, see
446     // ARMTargetLowering::addTypeForNEON method for details.
447     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
448     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
449     // FIXME: Create unittest.
450     // In another words, find a way when "copysign" appears in DAG with vector
451     // operands.
452     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
453     // FIXME: Code duplication: SETCC has custom operation action, see
454     // ARMTargetLowering::addTypeForNEON method for details.
455     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
456     // FIXME: Create unittest for FNEG and for FABS.
457     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
458     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
459     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
460     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
461     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
462     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
463     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
464     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
466     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
467     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
468     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
469     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
470     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
471     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
472     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
473     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
474     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
475     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
476
477     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
478     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
479     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
480     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
481     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
482     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
483     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
484     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
485     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
486     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
487     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
488     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
489     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
490     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
491     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
492
493     // Mark v2f32 intrinsics.
494     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
495     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
496     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
497     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
498     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
499     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
500     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
501     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
502     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
503     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
504     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
505     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
506     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
507     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
508     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
509
510     // Neon does not support some operations on v1i64 and v2i64 types.
511     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
512     // Custom handling for some quad-vector types to detect VMULL.
513     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
516     // Custom handling for some vector types to avoid expensive expansions
517     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
518     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
519     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
520     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
521     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
522     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
523     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
524     // a destination type that is wider than the source, and nor does
525     // it have a FP_TO_[SU]INT instruction with a narrower destination than
526     // source.
527     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
528     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
529     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
530     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
531
532     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
533     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
534
535     // NEON does not have single instruction CTPOP for vectors with element
536     // types wider than 8-bits.  However, custom lowering can leverage the
537     // v8i8/v16i8 vcnt instruction.
538     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
539     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
540     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
541     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
542
543     // NEON only has FMA instructions as of VFP4.
544     if (!Subtarget->hasVFP4()) {
545       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
546       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
547     }
548
549     setTargetDAGCombine(ISD::INTRINSIC_VOID);
550     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
551     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552     setTargetDAGCombine(ISD::SHL);
553     setTargetDAGCombine(ISD::SRL);
554     setTargetDAGCombine(ISD::SRA);
555     setTargetDAGCombine(ISD::SIGN_EXTEND);
556     setTargetDAGCombine(ISD::ZERO_EXTEND);
557     setTargetDAGCombine(ISD::ANY_EXTEND);
558     setTargetDAGCombine(ISD::SELECT_CC);
559     setTargetDAGCombine(ISD::BUILD_VECTOR);
560     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
561     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
562     setTargetDAGCombine(ISD::STORE);
563     setTargetDAGCombine(ISD::FP_TO_SINT);
564     setTargetDAGCombine(ISD::FP_TO_UINT);
565     setTargetDAGCombine(ISD::FDIV);
566
567     // It is legal to extload from v4i8 to v4i16 or v4i32.
568     MVT Tys[6] = {MVT::v8i8, MVT::v4i8, MVT::v2i8,
569                   MVT::v4i16, MVT::v2i16,
570                   MVT::v2i32};
571     for (unsigned i = 0; i < 6; ++i) {
572       setLoadExtAction(ISD::EXTLOAD, Tys[i], Legal);
573       setLoadExtAction(ISD::ZEXTLOAD, Tys[i], Legal);
574       setLoadExtAction(ISD::SEXTLOAD, Tys[i], Legal);
575     }
576   }
577
578   // ARM and Thumb2 support UMLAL/SMLAL.
579   if (!Subtarget->isThumb1Only())
580     setTargetDAGCombine(ISD::ADDC);
581
582
583   computeRegisterProperties();
584
585   // ARM does not have f32 extending load.
586   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
587
588   // ARM does not have i1 sign extending load.
589   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
590
591   // ARM supports all 4 flavors of integer indexed load / store.
592   if (!Subtarget->isThumb1Only()) {
593     for (unsigned im = (unsigned)ISD::PRE_INC;
594          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
595       setIndexedLoadAction(im,  MVT::i1,  Legal);
596       setIndexedLoadAction(im,  MVT::i8,  Legal);
597       setIndexedLoadAction(im,  MVT::i16, Legal);
598       setIndexedLoadAction(im,  MVT::i32, Legal);
599       setIndexedStoreAction(im, MVT::i1,  Legal);
600       setIndexedStoreAction(im, MVT::i8,  Legal);
601       setIndexedStoreAction(im, MVT::i16, Legal);
602       setIndexedStoreAction(im, MVT::i32, Legal);
603     }
604   }
605
606   setOperationAction(ISD::SADDO, MVT::i32, Custom);
607   setOperationAction(ISD::UADDO, MVT::i32, Custom);
608   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
609   setOperationAction(ISD::USUBO, MVT::i32, Custom);
610
611   // i64 operation support.
612   setOperationAction(ISD::MUL,     MVT::i64, Expand);
613   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
614   if (Subtarget->isThumb1Only()) {
615     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
616     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
617   }
618   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
619       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
620     setOperationAction(ISD::MULHS, MVT::i32, Expand);
621
622   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
623   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
624   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
625   setOperationAction(ISD::SRL,       MVT::i64, Custom);
626   setOperationAction(ISD::SRA,       MVT::i64, Custom);
627
628   if (!Subtarget->isThumb1Only()) {
629     // FIXME: We should do this for Thumb1 as well.
630     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
631     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
632     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
633     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
634   }
635
636   // ARM does not have ROTL.
637   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
638   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
639   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
640   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
641     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
642
643   // These just redirect to CTTZ and CTLZ on ARM.
644   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
645   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
646
647   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
648
649   // Only ARMv6 has BSWAP.
650   if (!Subtarget->hasV6Ops())
651     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
652
653   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
654       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
655     // These are expanded into libcalls if the cpu doesn't have HW divider.
656     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
657     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
658   }
659
660   // FIXME: Also set divmod for SREM on EABI
661   setOperationAction(ISD::SREM,  MVT::i32, Expand);
662   setOperationAction(ISD::UREM,  MVT::i32, Expand);
663   // Register based DivRem for AEABI (RTABI 4.2)
664   if (Subtarget->isTargetAEABI()) {
665     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
666     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
667     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
668     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
669     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
670     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
671     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
672     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
673
674     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
675     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
676     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
677     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
678     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
679     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
680     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
681     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
682
683     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
684     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
685   } else {
686     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
687     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
688   }
689
690   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
691   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
692   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
693   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
694   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
695
696   setOperationAction(ISD::TRAP, MVT::Other, Legal);
697
698   // Use the default implementation.
699   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
700   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
701   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
702   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
703   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
704   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
705
706   if (!Subtarget->isTargetMachO()) {
707     // Non-MachO platforms may return values in these registers via the
708     // personality function.
709     setExceptionPointerRegister(ARM::R0);
710     setExceptionSelectorRegister(ARM::R1);
711   }
712
713   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
714     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
715   else
716     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
717
718   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
719   // the default expansion.
720   if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
721     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
722     // to ldrex/strex loops already.
723     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
724
725     // On v8, we have particularly efficient implementations of atomic fences
726     // if they can be combined with nearby atomic loads and stores.
727     if (!Subtarget->hasV8Ops()) {
728       // Automatically insert fences (dmb ist) around ATOMIC_SWAP etc.
729       setInsertFencesForAtomic(true);
730     }
731   } else {
732     // If there's anything we can use as a barrier, go through custom lowering
733     // for ATOMIC_FENCE.
734     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
735                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
736
737     // Set them all for expansion, which will force libcalls.
738     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
739     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
740     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
741     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
742     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
743     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
744     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
745     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
746     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
747     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
748     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
749     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
750     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
751     // Unordered/Monotonic case.
752     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
753     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
754   }
755
756   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
757
758   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
759   if (!Subtarget->hasV6Ops()) {
760     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
761     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
762   }
763   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
764
765   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
766       !Subtarget->isThumb1Only()) {
767     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
768     // iff target supports vfp2.
769     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
770     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
771   }
772
773   // We want to custom lower some of our intrinsics.
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
775   if (Subtarget->isTargetDarwin()) {
776     setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
777     setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
778     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
779   }
780
781   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
782   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
783   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
784   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
785   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
786   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
787   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
788   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
789   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
790
791   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
792   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
793   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
794   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
795   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
796
797   // We don't support sin/cos/fmod/copysign/pow
798   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
799   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
800   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
801   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
802   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
803   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
804   setOperationAction(ISD::FREM,      MVT::f64, Expand);
805   setOperationAction(ISD::FREM,      MVT::f32, Expand);
806   if (!TM.Options.UseSoftFloat && Subtarget->hasVFP2() &&
807       !Subtarget->isThumb1Only()) {
808     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
809     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
810   }
811   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
812   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
813
814   if (!Subtarget->hasVFP4()) {
815     setOperationAction(ISD::FMA, MVT::f64, Expand);
816     setOperationAction(ISD::FMA, MVT::f32, Expand);
817   }
818
819   // Various VFP goodness
820   if (!TM.Options.UseSoftFloat && !Subtarget->isThumb1Only()) {
821     // int <-> fp are custom expanded into bit_convert + ARMISD ops.
822     if (Subtarget->hasVFP2()) {
823       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
824       setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
825       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
826       setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
827     }
828     // Special handling for half-precision FP.
829     if (!Subtarget->hasFP16()) {
830       setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
831       setOperationAction(ISD::FP32_TO_FP16, MVT::i32, Expand);
832     }
833   }
834
835   // Combine sin / cos into one node or libcall if possible.
836   if (Subtarget->hasSinCos()) {
837     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
838     setLibcallName(RTLIB::SINCOS_F64, "sincos");
839     if (Subtarget->getTargetTriple().getOS() == Triple::IOS) {
840       // For iOS, we don't want to the normal expansion of a libcall to
841       // sincos. We want to issue a libcall to __sincos_stret.
842       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
843       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
844     }
845   }
846
847   // We have target-specific dag combine patterns for the following nodes:
848   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
849   setTargetDAGCombine(ISD::ADD);
850   setTargetDAGCombine(ISD::SUB);
851   setTargetDAGCombine(ISD::MUL);
852   setTargetDAGCombine(ISD::AND);
853   setTargetDAGCombine(ISD::OR);
854   setTargetDAGCombine(ISD::XOR);
855
856   if (Subtarget->hasV6Ops())
857     setTargetDAGCombine(ISD::SRL);
858
859   setStackPointerRegisterToSaveRestore(ARM::SP);
860
861   if (TM.Options.UseSoftFloat || Subtarget->isThumb1Only() ||
862       !Subtarget->hasVFP2())
863     setSchedulingPreference(Sched::RegPressure);
864   else
865     setSchedulingPreference(Sched::Hybrid);
866
867   //// temporary - rewrite interface to use type
868   MaxStoresPerMemset = 8;
869   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
870   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
871   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
872   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
873   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 4 : 2;
874
875   // On ARM arguments smaller than 4 bytes are extended, so all arguments
876   // are at least 4 bytes aligned.
877   setMinStackArgumentAlignment(4);
878
879   // Prefer likely predicted branches to selects on out-of-order cores.
880   PredictableSelectIsExpensive = Subtarget->isLikeA9();
881
882   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
883 }
884
885 // FIXME: It might make sense to define the representative register class as the
886 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
887 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
888 // SPR's representative would be DPR_VFP2. This should work well if register
889 // pressure tracking were modified such that a register use would increment the
890 // pressure of the register class's representative and all of it's super
891 // classes' representatives transitively. We have not implemented this because
892 // of the difficulty prior to coalescing of modeling operand register classes
893 // due to the common occurrence of cross class copies and subregister insertions
894 // and extractions.
895 std::pair<const TargetRegisterClass*, uint8_t>
896 ARMTargetLowering::findRepresentativeClass(MVT VT) const{
897   const TargetRegisterClass *RRC = nullptr;
898   uint8_t Cost = 1;
899   switch (VT.SimpleTy) {
900   default:
901     return TargetLowering::findRepresentativeClass(VT);
902   // Use DPR as representative register class for all floating point
903   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
904   // the cost is 1 for both f32 and f64.
905   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
906   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
907     RRC = &ARM::DPRRegClass;
908     // When NEON is used for SP, only half of the register file is available
909     // because operations that define both SP and DP results will be constrained
910     // to the VFP2 class (D0-D15). We currently model this constraint prior to
911     // coalescing by double-counting the SP regs. See the FIXME above.
912     if (Subtarget->useNEONForSinglePrecisionFP())
913       Cost = 2;
914     break;
915   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
916   case MVT::v4f32: case MVT::v2f64:
917     RRC = &ARM::DPRRegClass;
918     Cost = 2;
919     break;
920   case MVT::v4i64:
921     RRC = &ARM::DPRRegClass;
922     Cost = 4;
923     break;
924   case MVT::v8i64:
925     RRC = &ARM::DPRRegClass;
926     Cost = 8;
927     break;
928   }
929   return std::make_pair(RRC, Cost);
930 }
931
932 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
933   switch (Opcode) {
934   default: return nullptr;
935   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
936   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
937   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
938   case ARMISD::CALL:          return "ARMISD::CALL";
939   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
940   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
941   case ARMISD::tCALL:         return "ARMISD::tCALL";
942   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
943   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
944   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
945   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
946   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
947   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
948   case ARMISD::CMP:           return "ARMISD::CMP";
949   case ARMISD::CMN:           return "ARMISD::CMN";
950   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
951   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
952   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
953   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
954   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
955
956   case ARMISD::CMOV:          return "ARMISD::CMOV";
957
958   case ARMISD::RBIT:          return "ARMISD::RBIT";
959
960   case ARMISD::FTOSI:         return "ARMISD::FTOSI";
961   case ARMISD::FTOUI:         return "ARMISD::FTOUI";
962   case ARMISD::SITOF:         return "ARMISD::SITOF";
963   case ARMISD::UITOF:         return "ARMISD::UITOF";
964
965   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
966   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
967   case ARMISD::RRX:           return "ARMISD::RRX";
968
969   case ARMISD::ADDC:          return "ARMISD::ADDC";
970   case ARMISD::ADDE:          return "ARMISD::ADDE";
971   case ARMISD::SUBC:          return "ARMISD::SUBC";
972   case ARMISD::SUBE:          return "ARMISD::SUBE";
973
974   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
975   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
976
977   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
978   case ARMISD::EH_SJLJ_LONGJMP:return "ARMISD::EH_SJLJ_LONGJMP";
979
980   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
981
982   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
983
984   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
985
986   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
987
988   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
989
990   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
991
992   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
993   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
994   case ARMISD::VCGE:          return "ARMISD::VCGE";
995   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
996   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
997   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
998   case ARMISD::VCGT:          return "ARMISD::VCGT";
999   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1000   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1001   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1002   case ARMISD::VTST:          return "ARMISD::VTST";
1003
1004   case ARMISD::VSHL:          return "ARMISD::VSHL";
1005   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1006   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1007   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1008   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1009   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1010   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1011   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1012   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1013   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1014   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1015   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1016   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1017   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1018   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1019   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1020   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1021   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1022   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1023   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1024   case ARMISD::VDUP:          return "ARMISD::VDUP";
1025   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1026   case ARMISD::VEXT:          return "ARMISD::VEXT";
1027   case ARMISD::VREV64:        return "ARMISD::VREV64";
1028   case ARMISD::VREV32:        return "ARMISD::VREV32";
1029   case ARMISD::VREV16:        return "ARMISD::VREV16";
1030   case ARMISD::VZIP:          return "ARMISD::VZIP";
1031   case ARMISD::VUZP:          return "ARMISD::VUZP";
1032   case ARMISD::VTRN:          return "ARMISD::VTRN";
1033   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1034   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1035   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1036   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1037   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1038   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1039   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1040   case ARMISD::FMAX:          return "ARMISD::FMAX";
1041   case ARMISD::FMIN:          return "ARMISD::FMIN";
1042   case ARMISD::VMAXNM:        return "ARMISD::VMAX";
1043   case ARMISD::VMINNM:        return "ARMISD::VMIN";
1044   case ARMISD::BFI:           return "ARMISD::BFI";
1045   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1046   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1047   case ARMISD::VBSL:          return "ARMISD::VBSL";
1048   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1049   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1050   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1051   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1052   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1053   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1054   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1055   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1056   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1057   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1058   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1059   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1060   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1061   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1062   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1063   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1064   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1065   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1066   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1067   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1068   }
1069 }
1070
1071 EVT ARMTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1072   if (!VT.isVector()) return getPointerTy();
1073   return VT.changeVectorElementTypeToInteger();
1074 }
1075
1076 /// getRegClassFor - Return the register class that should be used for the
1077 /// specified value type.
1078 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1079   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1080   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1081   // load / store 4 to 8 consecutive D registers.
1082   if (Subtarget->hasNEON()) {
1083     if (VT == MVT::v4i64)
1084       return &ARM::QQPRRegClass;
1085     if (VT == MVT::v8i64)
1086       return &ARM::QQQQPRRegClass;
1087   }
1088   return TargetLowering::getRegClassFor(VT);
1089 }
1090
1091 // Create a fast isel object.
1092 FastISel *
1093 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1094                                   const TargetLibraryInfo *libInfo) const {
1095   return ARM::createFastISel(funcInfo, libInfo);
1096 }
1097
1098 /// getMaximalGlobalOffset - Returns the maximal possible offset which can
1099 /// be used for loads / stores from the global.
1100 unsigned ARMTargetLowering::getMaximalGlobalOffset() const {
1101   return (Subtarget->isThumb1Only() ? 127 : 4095);
1102 }
1103
1104 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1105   unsigned NumVals = N->getNumValues();
1106   if (!NumVals)
1107     return Sched::RegPressure;
1108
1109   for (unsigned i = 0; i != NumVals; ++i) {
1110     EVT VT = N->getValueType(i);
1111     if (VT == MVT::Glue || VT == MVT::Other)
1112       continue;
1113     if (VT.isFloatingPoint() || VT.isVector())
1114       return Sched::ILP;
1115   }
1116
1117   if (!N->isMachineOpcode())
1118     return Sched::RegPressure;
1119
1120   // Load are scheduled for latency even if there instruction itinerary
1121   // is not available.
1122   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1123   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1124
1125   if (MCID.getNumDefs() == 0)
1126     return Sched::RegPressure;
1127   if (!Itins->isEmpty() &&
1128       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1129     return Sched::ILP;
1130
1131   return Sched::RegPressure;
1132 }
1133
1134 //===----------------------------------------------------------------------===//
1135 // Lowering Code
1136 //===----------------------------------------------------------------------===//
1137
1138 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1139 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1140   switch (CC) {
1141   default: llvm_unreachable("Unknown condition code!");
1142   case ISD::SETNE:  return ARMCC::NE;
1143   case ISD::SETEQ:  return ARMCC::EQ;
1144   case ISD::SETGT:  return ARMCC::GT;
1145   case ISD::SETGE:  return ARMCC::GE;
1146   case ISD::SETLT:  return ARMCC::LT;
1147   case ISD::SETLE:  return ARMCC::LE;
1148   case ISD::SETUGT: return ARMCC::HI;
1149   case ISD::SETUGE: return ARMCC::HS;
1150   case ISD::SETULT: return ARMCC::LO;
1151   case ISD::SETULE: return ARMCC::LS;
1152   }
1153 }
1154
1155 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1156 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1157                         ARMCC::CondCodes &CondCode2) {
1158   CondCode2 = ARMCC::AL;
1159   switch (CC) {
1160   default: llvm_unreachable("Unknown FP condition!");
1161   case ISD::SETEQ:
1162   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1163   case ISD::SETGT:
1164   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1165   case ISD::SETGE:
1166   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1167   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1168   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1169   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1170   case ISD::SETO:   CondCode = ARMCC::VC; break;
1171   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1172   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1173   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1174   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1175   case ISD::SETLT:
1176   case ISD::SETULT: CondCode = ARMCC::LT; break;
1177   case ISD::SETLE:
1178   case ISD::SETULE: CondCode = ARMCC::LE; break;
1179   case ISD::SETNE:
1180   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1181   }
1182 }
1183
1184 //===----------------------------------------------------------------------===//
1185 //                      Calling Convention Implementation
1186 //===----------------------------------------------------------------------===//
1187
1188 #include "ARMGenCallingConv.inc"
1189
1190 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1191 /// account presence of floating point hardware and calling convention
1192 /// limitations, such as support for variadic functions.
1193 CallingConv::ID
1194 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1195                                            bool isVarArg) const {
1196   switch (CC) {
1197   default:
1198     llvm_unreachable("Unsupported calling convention");
1199   case CallingConv::ARM_AAPCS:
1200   case CallingConv::ARM_APCS:
1201   case CallingConv::GHC:
1202     return CC;
1203   case CallingConv::ARM_AAPCS_VFP:
1204     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1205   case CallingConv::C:
1206     if (!Subtarget->isAAPCS_ABI())
1207       return CallingConv::ARM_APCS;
1208     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1209              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1210              !isVarArg)
1211       return CallingConv::ARM_AAPCS_VFP;
1212     else
1213       return CallingConv::ARM_AAPCS;
1214   case CallingConv::Fast:
1215     if (!Subtarget->isAAPCS_ABI()) {
1216       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1217         return CallingConv::Fast;
1218       return CallingConv::ARM_APCS;
1219     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1220       return CallingConv::ARM_AAPCS_VFP;
1221     else
1222       return CallingConv::ARM_AAPCS;
1223   }
1224 }
1225
1226 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1227 /// CallingConvention.
1228 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1229                                                  bool Return,
1230                                                  bool isVarArg) const {
1231   switch (getEffectiveCallingConv(CC, isVarArg)) {
1232   default:
1233     llvm_unreachable("Unsupported calling convention");
1234   case CallingConv::ARM_APCS:
1235     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1236   case CallingConv::ARM_AAPCS:
1237     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1238   case CallingConv::ARM_AAPCS_VFP:
1239     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1240   case CallingConv::Fast:
1241     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1242   case CallingConv::GHC:
1243     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1244   }
1245 }
1246
1247 /// LowerCallResult - Lower the result values of a call into the
1248 /// appropriate copies out of appropriate physical registers.
1249 SDValue
1250 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1251                                    CallingConv::ID CallConv, bool isVarArg,
1252                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1253                                    SDLoc dl, SelectionDAG &DAG,
1254                                    SmallVectorImpl<SDValue> &InVals,
1255                                    bool isThisReturn, SDValue ThisVal) const {
1256
1257   // Assign locations to each value returned by this call.
1258   SmallVector<CCValAssign, 16> RVLocs;
1259   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1260                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
1261   CCInfo.AnalyzeCallResult(Ins,
1262                            CCAssignFnForNode(CallConv, /* Return*/ true,
1263                                              isVarArg));
1264
1265   // Copy all of the result registers out of their specified physreg.
1266   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1267     CCValAssign VA = RVLocs[i];
1268
1269     // Pass 'this' value directly from the argument to return value, to avoid
1270     // reg unit interference
1271     if (i == 0 && isThisReturn) {
1272       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1273              "unexpected return calling convention register assignment");
1274       InVals.push_back(ThisVal);
1275       continue;
1276     }
1277
1278     SDValue Val;
1279     if (VA.needsCustom()) {
1280       // Handle f64 or half of a v2f64.
1281       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1282                                       InFlag);
1283       Chain = Lo.getValue(1);
1284       InFlag = Lo.getValue(2);
1285       VA = RVLocs[++i]; // skip ahead to next loc
1286       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1287                                       InFlag);
1288       Chain = Hi.getValue(1);
1289       InFlag = Hi.getValue(2);
1290       if (!Subtarget->isLittle())
1291         std::swap (Lo, Hi);
1292       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1293
1294       if (VA.getLocVT() == MVT::v2f64) {
1295         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1296         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1297                           DAG.getConstant(0, MVT::i32));
1298
1299         VA = RVLocs[++i]; // skip ahead to next loc
1300         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1301         Chain = Lo.getValue(1);
1302         InFlag = Lo.getValue(2);
1303         VA = RVLocs[++i]; // skip ahead to next loc
1304         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1305         Chain = Hi.getValue(1);
1306         InFlag = Hi.getValue(2);
1307         if (!Subtarget->isLittle())
1308           std::swap (Lo, Hi);
1309         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1310         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1311                           DAG.getConstant(1, MVT::i32));
1312       }
1313     } else {
1314       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1315                                InFlag);
1316       Chain = Val.getValue(1);
1317       InFlag = Val.getValue(2);
1318     }
1319
1320     switch (VA.getLocInfo()) {
1321     default: llvm_unreachable("Unknown loc info!");
1322     case CCValAssign::Full: break;
1323     case CCValAssign::BCvt:
1324       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1325       break;
1326     }
1327
1328     InVals.push_back(Val);
1329   }
1330
1331   return Chain;
1332 }
1333
1334 /// LowerMemOpCallTo - Store the argument to the stack.
1335 SDValue
1336 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1337                                     SDValue StackPtr, SDValue Arg,
1338                                     SDLoc dl, SelectionDAG &DAG,
1339                                     const CCValAssign &VA,
1340                                     ISD::ArgFlagsTy Flags) const {
1341   unsigned LocMemOffset = VA.getLocMemOffset();
1342   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1343   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1344   return DAG.getStore(Chain, dl, Arg, PtrOff,
1345                       MachinePointerInfo::getStack(LocMemOffset),
1346                       false, false, 0);
1347 }
1348
1349 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1350                                          SDValue Chain, SDValue &Arg,
1351                                          RegsToPassVector &RegsToPass,
1352                                          CCValAssign &VA, CCValAssign &NextVA,
1353                                          SDValue &StackPtr,
1354                                          SmallVectorImpl<SDValue> &MemOpChains,
1355                                          ISD::ArgFlagsTy Flags) const {
1356
1357   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1358                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1359   unsigned id = Subtarget->isLittle() ? 0 : 1;
1360   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1361
1362   if (NextVA.isRegLoc())
1363     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1364   else {
1365     assert(NextVA.isMemLoc());
1366     if (!StackPtr.getNode())
1367       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1368
1369     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1370                                            dl, DAG, NextVA,
1371                                            Flags));
1372   }
1373 }
1374
1375 /// LowerCall - Lowering a call into a callseq_start <-
1376 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1377 /// nodes.
1378 SDValue
1379 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1380                              SmallVectorImpl<SDValue> &InVals) const {
1381   SelectionDAG &DAG                     = CLI.DAG;
1382   SDLoc &dl                          = CLI.DL;
1383   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1384   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1385   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1386   SDValue Chain                         = CLI.Chain;
1387   SDValue Callee                        = CLI.Callee;
1388   bool &isTailCall                      = CLI.IsTailCall;
1389   CallingConv::ID CallConv              = CLI.CallConv;
1390   bool doesNotRet                       = CLI.DoesNotReturn;
1391   bool isVarArg                         = CLI.IsVarArg;
1392
1393   MachineFunction &MF = DAG.getMachineFunction();
1394   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1395   bool isThisReturn   = false;
1396   bool isSibCall      = false;
1397
1398   // Disable tail calls if they're not supported.
1399   if (!Subtarget->supportsTailCall() || MF.getTarget().Options.DisableTailCalls)
1400     isTailCall = false;
1401
1402   if (isTailCall) {
1403     // Check if it's really possible to do a tail call.
1404     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1405                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1406                                                    Outs, OutVals, Ins, DAG);
1407     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1408       report_fatal_error("failed to perform tail call elimination on a call "
1409                          "site marked musttail");
1410     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1411     // detected sibcalls.
1412     if (isTailCall) {
1413       ++NumTailCalls;
1414       isSibCall = true;
1415     }
1416   }
1417
1418   // Analyze operands of the call, assigning locations to each operand.
1419   SmallVector<CCValAssign, 16> ArgLocs;
1420   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1421                  getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1422   CCInfo.AnalyzeCallOperands(Outs,
1423                              CCAssignFnForNode(CallConv, /* Return*/ false,
1424                                                isVarArg));
1425
1426   // Get a count of how many bytes are to be pushed on the stack.
1427   unsigned NumBytes = CCInfo.getNextStackOffset();
1428
1429   // For tail calls, memory operands are available in our caller's stack.
1430   if (isSibCall)
1431     NumBytes = 0;
1432
1433   // Adjust the stack pointer for the new arguments...
1434   // These operations are automatically eliminated by the prolog/epilog pass
1435   if (!isSibCall)
1436     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
1437                                  dl);
1438
1439   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy());
1440
1441   RegsToPassVector RegsToPass;
1442   SmallVector<SDValue, 8> MemOpChains;
1443
1444   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1445   // of tail call optimization, arguments are handled later.
1446   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1447        i != e;
1448        ++i, ++realArgIdx) {
1449     CCValAssign &VA = ArgLocs[i];
1450     SDValue Arg = OutVals[realArgIdx];
1451     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1452     bool isByVal = Flags.isByVal();
1453
1454     // Promote the value if needed.
1455     switch (VA.getLocInfo()) {
1456     default: llvm_unreachable("Unknown loc info!");
1457     case CCValAssign::Full: break;
1458     case CCValAssign::SExt:
1459       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1460       break;
1461     case CCValAssign::ZExt:
1462       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1463       break;
1464     case CCValAssign::AExt:
1465       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1466       break;
1467     case CCValAssign::BCvt:
1468       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1469       break;
1470     }
1471
1472     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1473     if (VA.needsCustom()) {
1474       if (VA.getLocVT() == MVT::v2f64) {
1475         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1476                                   DAG.getConstant(0, MVT::i32));
1477         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1478                                   DAG.getConstant(1, MVT::i32));
1479
1480         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1481                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1482
1483         VA = ArgLocs[++i]; // skip ahead to next loc
1484         if (VA.isRegLoc()) {
1485           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1486                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1487         } else {
1488           assert(VA.isMemLoc());
1489
1490           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1491                                                  dl, DAG, VA, Flags));
1492         }
1493       } else {
1494         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1495                          StackPtr, MemOpChains, Flags);
1496       }
1497     } else if (VA.isRegLoc()) {
1498       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1499         assert(VA.getLocVT() == MVT::i32 &&
1500                "unexpected calling convention register assignment");
1501         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1502                "unexpected use of 'returned'");
1503         isThisReturn = true;
1504       }
1505       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1506     } else if (isByVal) {
1507       assert(VA.isMemLoc());
1508       unsigned offset = 0;
1509
1510       // True if this byval aggregate will be split between registers
1511       // and memory.
1512       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1513       unsigned CurByValIdx = CCInfo.getInRegsParamsProceed();
1514
1515       if (CurByValIdx < ByValArgsCount) {
1516
1517         unsigned RegBegin, RegEnd;
1518         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1519
1520         EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1521         unsigned int i, j;
1522         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1523           SDValue Const = DAG.getConstant(4*i, MVT::i32);
1524           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1525           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1526                                      MachinePointerInfo(),
1527                                      false, false, false,
1528                                      DAG.InferPtrAlignment(AddArg));
1529           MemOpChains.push_back(Load.getValue(1));
1530           RegsToPass.push_back(std::make_pair(j, Load));
1531         }
1532
1533         // If parameter size outsides register area, "offset" value
1534         // helps us to calculate stack slot for remained part properly.
1535         offset = RegEnd - RegBegin;
1536
1537         CCInfo.nextInRegsParam();
1538       }
1539
1540       if (Flags.getByValSize() > 4*offset) {
1541         unsigned LocMemOffset = VA.getLocMemOffset();
1542         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset);
1543         SDValue Dst = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
1544                                   StkPtrOff);
1545         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset);
1546         SDValue Src = DAG.getNode(ISD::ADD, dl, getPointerTy(), Arg, SrcOffset);
1547         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset,
1548                                            MVT::i32);
1549         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), MVT::i32);
1550
1551         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1552         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1553         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1554                                           Ops));
1555       }
1556     } else if (!isSibCall) {
1557       assert(VA.isMemLoc());
1558
1559       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1560                                              dl, DAG, VA, Flags));
1561     }
1562   }
1563
1564   if (!MemOpChains.empty())
1565     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1566
1567   // Build a sequence of copy-to-reg nodes chained together with token chain
1568   // and flag operands which copy the outgoing args into the appropriate regs.
1569   SDValue InFlag;
1570   // Tail call byval lowering might overwrite argument registers so in case of
1571   // tail call optimization the copies to registers are lowered later.
1572   if (!isTailCall)
1573     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1574       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1575                                RegsToPass[i].second, InFlag);
1576       InFlag = Chain.getValue(1);
1577     }
1578
1579   // For tail calls lower the arguments to the 'real' stack slot.
1580   if (isTailCall) {
1581     // Force all the incoming stack arguments to be loaded from the stack
1582     // before any new outgoing arguments are stored to the stack, because the
1583     // outgoing stack slots may alias the incoming argument stack slots, and
1584     // the alias isn't otherwise explicit. This is slightly more conservative
1585     // than necessary, because it means that each store effectively depends
1586     // on every argument instead of just those arguments it would clobber.
1587
1588     // Do not flag preceding copytoreg stuff together with the following stuff.
1589     InFlag = SDValue();
1590     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1591       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1592                                RegsToPass[i].second, InFlag);
1593       InFlag = Chain.getValue(1);
1594     }
1595     InFlag = SDValue();
1596   }
1597
1598   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1599   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1600   // node so that legalize doesn't hack it.
1601   bool isDirect = false;
1602   bool isARMFunc = false;
1603   bool isLocalARMFunc = false;
1604   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1605
1606   if (EnableARMLongCalls) {
1607     assert((Subtarget->isTargetWindows() ||
1608             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1609            "long-calls with non-static relocation model!");
1610     // Handle a global address or an external symbol. If it's not one of
1611     // those, the target's already in a register, so we don't need to do
1612     // anything extra.
1613     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1614       const GlobalValue *GV = G->getGlobal();
1615       // Create a constant pool entry for the callee address
1616       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1617       ARMConstantPoolValue *CPV =
1618         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1619
1620       // Get the address of the callee into a register
1621       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1622       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1623       Callee = DAG.getLoad(getPointerTy(), dl,
1624                            DAG.getEntryNode(), CPAddr,
1625                            MachinePointerInfo::getConstantPool(),
1626                            false, false, false, 0);
1627     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1628       const char *Sym = S->getSymbol();
1629
1630       // Create a constant pool entry for the callee address
1631       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1632       ARMConstantPoolValue *CPV =
1633         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1634                                       ARMPCLabelIndex, 0);
1635       // Get the address of the callee into a register
1636       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1637       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1638       Callee = DAG.getLoad(getPointerTy(), dl,
1639                            DAG.getEntryNode(), CPAddr,
1640                            MachinePointerInfo::getConstantPool(),
1641                            false, false, false, 0);
1642     }
1643   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1644     const GlobalValue *GV = G->getGlobal();
1645     isDirect = true;
1646     bool isExt = GV->isDeclaration() || GV->isWeakForLinker();
1647     bool isStub = (isExt && Subtarget->isTargetMachO()) &&
1648                    getTargetMachine().getRelocationModel() != Reloc::Static;
1649     isARMFunc = !Subtarget->isThumb() || isStub;
1650     // ARM call to a local ARM function is predicable.
1651     isLocalARMFunc = !Subtarget->isThumb() && (!isExt || !ARMInterworking);
1652     // tBX takes a register source operand.
1653     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1654       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1655       Callee = DAG.getNode(ARMISD::WrapperPIC, dl, getPointerTy(),
1656                            DAG.getTargetGlobalAddress(GV, dl, getPointerTy()));
1657     } else {
1658       // On ELF targets for PIC code, direct calls should go through the PLT
1659       unsigned OpFlags = 0;
1660       if (Subtarget->isTargetELF() &&
1661           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1662         OpFlags = ARMII::MO_PLT;
1663       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
1664     }
1665   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1666     isDirect = true;
1667     bool isStub = Subtarget->isTargetMachO() &&
1668                   getTargetMachine().getRelocationModel() != Reloc::Static;
1669     isARMFunc = !Subtarget->isThumb() || isStub;
1670     // tBX takes a register source operand.
1671     const char *Sym = S->getSymbol();
1672     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1673       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1674       ARMConstantPoolValue *CPV =
1675         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1676                                       ARMPCLabelIndex, 4);
1677       SDValue CPAddr = DAG.getTargetConstantPool(CPV, getPointerTy(), 4);
1678       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1679       Callee = DAG.getLoad(getPointerTy(), dl,
1680                            DAG.getEntryNode(), CPAddr,
1681                            MachinePointerInfo::getConstantPool(),
1682                            false, false, false, 0);
1683       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
1684       Callee = DAG.getNode(ARMISD::PIC_ADD, dl,
1685                            getPointerTy(), Callee, PICLabel);
1686     } else {
1687       unsigned OpFlags = 0;
1688       // On ELF targets for PIC code, direct calls should go through the PLT
1689       if (Subtarget->isTargetELF() &&
1690                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1691         OpFlags = ARMII::MO_PLT;
1692       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlags);
1693     }
1694   }
1695
1696   // FIXME: handle tail calls differently.
1697   unsigned CallOpc;
1698   bool HasMinSizeAttr = Subtarget->isMinSize();
1699   if (Subtarget->isThumb()) {
1700     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1701       CallOpc = ARMISD::CALL_NOLINK;
1702     else
1703       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1704   } else {
1705     if (!isDirect && !Subtarget->hasV5TOps())
1706       CallOpc = ARMISD::CALL_NOLINK;
1707     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1708                // Emit regular call when code size is the priority
1709                !HasMinSizeAttr)
1710       // "mov lr, pc; b _foo" to avoid confusing the RSP
1711       CallOpc = ARMISD::CALL_NOLINK;
1712     else
1713       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1714   }
1715
1716   std::vector<SDValue> Ops;
1717   Ops.push_back(Chain);
1718   Ops.push_back(Callee);
1719
1720   // Add argument registers to the end of the list so that they are known live
1721   // into the call.
1722   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1723     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1724                                   RegsToPass[i].second.getValueType()));
1725
1726   // Add a register mask operand representing the call-preserved registers.
1727   if (!isTailCall) {
1728     const uint32_t *Mask;
1729     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1730     const ARMBaseRegisterInfo *ARI = static_cast<const ARMBaseRegisterInfo*>(TRI);
1731     if (isThisReturn) {
1732       // For 'this' returns, use the R0-preserving mask if applicable
1733       Mask = ARI->getThisReturnPreservedMask(CallConv);
1734       if (!Mask) {
1735         // Set isThisReturn to false if the calling convention is not one that
1736         // allows 'returned' to be modeled in this way, so LowerCallResult does
1737         // not try to pass 'this' straight through
1738         isThisReturn = false;
1739         Mask = ARI->getCallPreservedMask(CallConv);
1740       }
1741     } else
1742       Mask = ARI->getCallPreservedMask(CallConv);
1743
1744     assert(Mask && "Missing call preserved mask for calling convention");
1745     Ops.push_back(DAG.getRegisterMask(Mask));
1746   }
1747
1748   if (InFlag.getNode())
1749     Ops.push_back(InFlag);
1750
1751   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1752   if (isTailCall)
1753     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1754
1755   // Returns a chain and a flag for retval copy to use.
1756   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1757   InFlag = Chain.getValue(1);
1758
1759   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1760                              DAG.getIntPtrConstant(0, true), InFlag, dl);
1761   if (!Ins.empty())
1762     InFlag = Chain.getValue(1);
1763
1764   // Handle result values, copying them out of physregs into vregs that we
1765   // return.
1766   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1767                          InVals, isThisReturn,
1768                          isThisReturn ? OutVals[0] : SDValue());
1769 }
1770
1771 /// HandleByVal - Every parameter *after* a byval parameter is passed
1772 /// on the stack.  Remember the next parameter register to allocate,
1773 /// and then confiscate the rest of the parameter registers to insure
1774 /// this.
1775 void
1776 ARMTargetLowering::HandleByVal(
1777     CCState *State, unsigned &size, unsigned Align) const {
1778   unsigned reg = State->AllocateReg(GPRArgRegs, 4);
1779   assert((State->getCallOrPrologue() == Prologue ||
1780           State->getCallOrPrologue() == Call) &&
1781          "unhandled ParmContext");
1782
1783   if ((ARM::R0 <= reg) && (reg <= ARM::R3)) {
1784     if (Subtarget->isAAPCS_ABI() && Align > 4) {
1785       unsigned AlignInRegs = Align / 4;
1786       unsigned Waste = (ARM::R4 - reg) % AlignInRegs;
1787       for (unsigned i = 0; i < Waste; ++i)
1788         reg = State->AllocateReg(GPRArgRegs, 4);
1789     }
1790     if (reg != 0) {
1791       unsigned excess = 4 * (ARM::R4 - reg);
1792
1793       // Special case when NSAA != SP and parameter size greater than size of
1794       // all remained GPR regs. In that case we can't split parameter, we must
1795       // send it to stack. We also must set NCRN to R4, so waste all
1796       // remained registers.
1797       const unsigned NSAAOffset = State->getNextStackOffset();
1798       if (Subtarget->isAAPCS_ABI() && NSAAOffset != 0 && size > excess) {
1799         while (State->AllocateReg(GPRArgRegs, 4))
1800           ;
1801         return;
1802       }
1803
1804       // First register for byval parameter is the first register that wasn't
1805       // allocated before this method call, so it would be "reg".
1806       // If parameter is small enough to be saved in range [reg, r4), then
1807       // the end (first after last) register would be reg + param-size-in-regs,
1808       // else parameter would be splitted between registers and stack,
1809       // end register would be r4 in this case.
1810       unsigned ByValRegBegin = reg;
1811       unsigned ByValRegEnd = (size < excess) ? reg + size/4 : (unsigned)ARM::R4;
1812       State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1813       // Note, first register is allocated in the beginning of function already,
1814       // allocate remained amount of registers we need.
1815       for (unsigned i = reg+1; i != ByValRegEnd; ++i)
1816         State->AllocateReg(GPRArgRegs, 4);
1817       // A byval parameter that is split between registers and memory needs its
1818       // size truncated here.
1819       // In the case where the entire structure fits in registers, we set the
1820       // size in memory to zero.
1821       if (size < excess)
1822         size = 0;
1823       else
1824         size -= excess;
1825     }
1826   }
1827 }
1828
1829 /// MatchingStackOffset - Return true if the given stack call argument is
1830 /// already available in the same position (relatively) of the caller's
1831 /// incoming argument stack.
1832 static
1833 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1834                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1835                          const TargetInstrInfo *TII) {
1836   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1837   int FI = INT_MAX;
1838   if (Arg.getOpcode() == ISD::CopyFromReg) {
1839     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1840     if (!TargetRegisterInfo::isVirtualRegister(VR))
1841       return false;
1842     MachineInstr *Def = MRI->getVRegDef(VR);
1843     if (!Def)
1844       return false;
1845     if (!Flags.isByVal()) {
1846       if (!TII->isLoadFromStackSlot(Def, FI))
1847         return false;
1848     } else {
1849       return false;
1850     }
1851   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1852     if (Flags.isByVal())
1853       // ByVal argument is passed in as a pointer but it's now being
1854       // dereferenced. e.g.
1855       // define @foo(%struct.X* %A) {
1856       //   tail call @bar(%struct.X* byval %A)
1857       // }
1858       return false;
1859     SDValue Ptr = Ld->getBasePtr();
1860     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
1861     if (!FINode)
1862       return false;
1863     FI = FINode->getIndex();
1864   } else
1865     return false;
1866
1867   assert(FI != INT_MAX);
1868   if (!MFI->isFixedObjectIndex(FI))
1869     return false;
1870   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
1871 }
1872
1873 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
1874 /// for tail call optimization. Targets which want to do tail call
1875 /// optimization should implement this function.
1876 bool
1877 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
1878                                                      CallingConv::ID CalleeCC,
1879                                                      bool isVarArg,
1880                                                      bool isCalleeStructRet,
1881                                                      bool isCallerStructRet,
1882                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
1883                                     const SmallVectorImpl<SDValue> &OutVals,
1884                                     const SmallVectorImpl<ISD::InputArg> &Ins,
1885                                                      SelectionDAG& DAG) const {
1886   const Function *CallerF = DAG.getMachineFunction().getFunction();
1887   CallingConv::ID CallerCC = CallerF->getCallingConv();
1888   bool CCMatch = CallerCC == CalleeCC;
1889
1890   // Look for obvious safe cases to perform tail call optimization that do not
1891   // require ABI changes. This is what gcc calls sibcall.
1892
1893   // Do not sibcall optimize vararg calls unless the call site is not passing
1894   // any arguments.
1895   if (isVarArg && !Outs.empty())
1896     return false;
1897
1898   // Exception-handling functions need a special set of instructions to indicate
1899   // a return to the hardware. Tail-calling another function would probably
1900   // break this.
1901   if (CallerF->hasFnAttribute("interrupt"))
1902     return false;
1903
1904   // Also avoid sibcall optimization if either caller or callee uses struct
1905   // return semantics.
1906   if (isCalleeStructRet || isCallerStructRet)
1907     return false;
1908
1909   // FIXME: Completely disable sibcall for Thumb1 since Thumb1RegisterInfo::
1910   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
1911   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
1912   // support in the assembler and linker to be used. This would need to be
1913   // fixed to fully support tail calls in Thumb1.
1914   //
1915   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
1916   // LR.  This means if we need to reload LR, it takes an extra instructions,
1917   // which outweighs the value of the tail call; but here we don't know yet
1918   // whether LR is going to be used.  Probably the right approach is to
1919   // generate the tail call here and turn it back into CALL/RET in
1920   // emitEpilogue if LR is used.
1921
1922   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
1923   // but we need to make sure there are enough registers; the only valid
1924   // registers are the 4 used for parameters.  We don't currently do this
1925   // case.
1926   if (Subtarget->isThumb1Only())
1927     return false;
1928
1929   // If the calling conventions do not match, then we'd better make sure the
1930   // results are returned in the same way as what the caller expects.
1931   if (!CCMatch) {
1932     SmallVector<CCValAssign, 16> RVLocs1;
1933     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
1934                        getTargetMachine(), RVLocs1, *DAG.getContext(), Call);
1935     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
1936
1937     SmallVector<CCValAssign, 16> RVLocs2;
1938     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
1939                        getTargetMachine(), RVLocs2, *DAG.getContext(), Call);
1940     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
1941
1942     if (RVLocs1.size() != RVLocs2.size())
1943       return false;
1944     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
1945       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
1946         return false;
1947       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
1948         return false;
1949       if (RVLocs1[i].isRegLoc()) {
1950         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
1951           return false;
1952       } else {
1953         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
1954           return false;
1955       }
1956     }
1957   }
1958
1959   // If Caller's vararg or byval argument has been split between registers and
1960   // stack, do not perform tail call, since part of the argument is in caller's
1961   // local frame.
1962   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
1963                                       getInfo<ARMFunctionInfo>();
1964   if (AFI_Caller->getArgRegsSaveSize())
1965     return false;
1966
1967   // If the callee takes no arguments then go on to check the results of the
1968   // call.
1969   if (!Outs.empty()) {
1970     // Check if stack adjustment is needed. For now, do not do this if any
1971     // argument is passed on the stack.
1972     SmallVector<CCValAssign, 16> ArgLocs;
1973     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1974                       getTargetMachine(), ArgLocs, *DAG.getContext(), Call);
1975     CCInfo.AnalyzeCallOperands(Outs,
1976                                CCAssignFnForNode(CalleeCC, false, isVarArg));
1977     if (CCInfo.getNextStackOffset()) {
1978       MachineFunction &MF = DAG.getMachineFunction();
1979
1980       // Check if the arguments are already laid out in the right way as
1981       // the caller's fixed stack objects.
1982       MachineFrameInfo *MFI = MF.getFrameInfo();
1983       const MachineRegisterInfo *MRI = &MF.getRegInfo();
1984       const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1985       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1986            i != e;
1987            ++i, ++realArgIdx) {
1988         CCValAssign &VA = ArgLocs[i];
1989         EVT RegVT = VA.getLocVT();
1990         SDValue Arg = OutVals[realArgIdx];
1991         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1992         if (VA.getLocInfo() == CCValAssign::Indirect)
1993           return false;
1994         if (VA.needsCustom()) {
1995           // f64 and vector types are split into multiple registers or
1996           // register/stack-slot combinations.  The types will not match
1997           // the registers; give up on memory f64 refs until we figure
1998           // out what to do about this.
1999           if (!VA.isRegLoc())
2000             return false;
2001           if (!ArgLocs[++i].isRegLoc())
2002             return false;
2003           if (RegVT == MVT::v2f64) {
2004             if (!ArgLocs[++i].isRegLoc())
2005               return false;
2006             if (!ArgLocs[++i].isRegLoc())
2007               return false;
2008           }
2009         } else if (!VA.isRegLoc()) {
2010           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2011                                    MFI, MRI, TII))
2012             return false;
2013         }
2014       }
2015     }
2016   }
2017
2018   return true;
2019 }
2020
2021 bool
2022 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2023                                   MachineFunction &MF, bool isVarArg,
2024                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2025                                   LLVMContext &Context) const {
2026   SmallVector<CCValAssign, 16> RVLocs;
2027   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2028   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2029                                                     isVarArg));
2030 }
2031
2032 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2033                                     SDLoc DL, SelectionDAG &DAG) {
2034   const MachineFunction &MF = DAG.getMachineFunction();
2035   const Function *F = MF.getFunction();
2036
2037   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2038
2039   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2040   // version of the "preferred return address". These offsets affect the return
2041   // instruction if this is a return from PL1 without hypervisor extensions.
2042   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2043   //    SWI:     0      "subs pc, lr, #0"
2044   //    ABORT:   +4     "subs pc, lr, #4"
2045   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2046   // UNDEF varies depending on where the exception came from ARM or Thumb
2047   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2048
2049   int64_t LROffset;
2050   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2051       IntKind == "ABORT")
2052     LROffset = 4;
2053   else if (IntKind == "SWI" || IntKind == "UNDEF")
2054     LROffset = 0;
2055   else
2056     report_fatal_error("Unsupported interrupt attribute. If present, value "
2057                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2058
2059   RetOps.insert(RetOps.begin() + 1, DAG.getConstant(LROffset, MVT::i32, false));
2060
2061   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2062 }
2063
2064 SDValue
2065 ARMTargetLowering::LowerReturn(SDValue Chain,
2066                                CallingConv::ID CallConv, bool isVarArg,
2067                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2068                                const SmallVectorImpl<SDValue> &OutVals,
2069                                SDLoc dl, SelectionDAG &DAG) const {
2070
2071   // CCValAssign - represent the assignment of the return value to a location.
2072   SmallVector<CCValAssign, 16> RVLocs;
2073
2074   // CCState - Info about the registers and stack slots.
2075   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2076                     getTargetMachine(), RVLocs, *DAG.getContext(), Call);
2077
2078   // Analyze outgoing return values.
2079   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2080                                                isVarArg));
2081
2082   SDValue Flag;
2083   SmallVector<SDValue, 4> RetOps;
2084   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2085   bool isLittleEndian = Subtarget->isLittle();
2086
2087   // Copy the result values into the output registers.
2088   for (unsigned i = 0, realRVLocIdx = 0;
2089        i != RVLocs.size();
2090        ++i, ++realRVLocIdx) {
2091     CCValAssign &VA = RVLocs[i];
2092     assert(VA.isRegLoc() && "Can only return in registers!");
2093
2094     SDValue Arg = OutVals[realRVLocIdx];
2095
2096     switch (VA.getLocInfo()) {
2097     default: llvm_unreachable("Unknown loc info!");
2098     case CCValAssign::Full: break;
2099     case CCValAssign::BCvt:
2100       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2101       break;
2102     }
2103
2104     if (VA.needsCustom()) {
2105       if (VA.getLocVT() == MVT::v2f64) {
2106         // Extract the first half and return it in two registers.
2107         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2108                                    DAG.getConstant(0, MVT::i32));
2109         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2110                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2111
2112         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2113                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2114                                  Flag);
2115         Flag = Chain.getValue(1);
2116         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2117         VA = RVLocs[++i]; // skip ahead to next loc
2118         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2119                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2120                                  Flag);
2121         Flag = Chain.getValue(1);
2122         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2123         VA = RVLocs[++i]; // skip ahead to next loc
2124
2125         // Extract the 2nd half and fall through to handle it as an f64 value.
2126         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2127                           DAG.getConstant(1, MVT::i32));
2128       }
2129       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2130       // available.
2131       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2132                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2133       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2134                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2135                                Flag);
2136       Flag = Chain.getValue(1);
2137       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2138       VA = RVLocs[++i]; // skip ahead to next loc
2139       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2140                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2141                                Flag);
2142     } else
2143       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2144
2145     // Guarantee that all emitted copies are
2146     // stuck together, avoiding something bad.
2147     Flag = Chain.getValue(1);
2148     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2149   }
2150
2151   // Update chain and glue.
2152   RetOps[0] = Chain;
2153   if (Flag.getNode())
2154     RetOps.push_back(Flag);
2155
2156   // CPUs which aren't M-class use a special sequence to return from
2157   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2158   // though we use "subs pc, lr, #N").
2159   //
2160   // M-class CPUs actually use a normal return sequence with a special
2161   // (hardware-provided) value in LR, so the normal code path works.
2162   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2163       !Subtarget->isMClass()) {
2164     if (Subtarget->isThumb1Only())
2165       report_fatal_error("interrupt attribute is not supported in Thumb1");
2166     return LowerInterruptReturn(RetOps, dl, DAG);
2167   }
2168
2169   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2170 }
2171
2172 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2173   if (N->getNumValues() != 1)
2174     return false;
2175   if (!N->hasNUsesOfValue(1, 0))
2176     return false;
2177
2178   SDValue TCChain = Chain;
2179   SDNode *Copy = *N->use_begin();
2180   if (Copy->getOpcode() == ISD::CopyToReg) {
2181     // If the copy has a glue operand, we conservatively assume it isn't safe to
2182     // perform a tail call.
2183     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2184       return false;
2185     TCChain = Copy->getOperand(0);
2186   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2187     SDNode *VMov = Copy;
2188     // f64 returned in a pair of GPRs.
2189     SmallPtrSet<SDNode*, 2> Copies;
2190     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2191          UI != UE; ++UI) {
2192       if (UI->getOpcode() != ISD::CopyToReg)
2193         return false;
2194       Copies.insert(*UI);
2195     }
2196     if (Copies.size() > 2)
2197       return false;
2198
2199     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2200          UI != UE; ++UI) {
2201       SDValue UseChain = UI->getOperand(0);
2202       if (Copies.count(UseChain.getNode()))
2203         // Second CopyToReg
2204         Copy = *UI;
2205       else
2206         // First CopyToReg
2207         TCChain = UseChain;
2208     }
2209   } else if (Copy->getOpcode() == ISD::BITCAST) {
2210     // f32 returned in a single GPR.
2211     if (!Copy->hasOneUse())
2212       return false;
2213     Copy = *Copy->use_begin();
2214     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2215       return false;
2216     TCChain = Copy->getOperand(0);
2217   } else {
2218     return false;
2219   }
2220
2221   bool HasRet = false;
2222   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2223        UI != UE; ++UI) {
2224     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2225         UI->getOpcode() != ARMISD::INTRET_FLAG)
2226       return false;
2227     HasRet = true;
2228   }
2229
2230   if (!HasRet)
2231     return false;
2232
2233   Chain = TCChain;
2234   return true;
2235 }
2236
2237 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2238   if (!Subtarget->supportsTailCall())
2239     return false;
2240
2241   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2242     return false;
2243
2244   return !Subtarget->isThumb1Only();
2245 }
2246
2247 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2248 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2249 // one of the above mentioned nodes. It has to be wrapped because otherwise
2250 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2251 // be used to form addressing mode. These wrapped nodes will be selected
2252 // into MOVi.
2253 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2254   EVT PtrVT = Op.getValueType();
2255   // FIXME there is no actual debug info here
2256   SDLoc dl(Op);
2257   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2258   SDValue Res;
2259   if (CP->isMachineConstantPoolEntry())
2260     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2261                                     CP->getAlignment());
2262   else
2263     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2264                                     CP->getAlignment());
2265   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2266 }
2267
2268 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2269   return MachineJumpTableInfo::EK_Inline;
2270 }
2271
2272 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2273                                              SelectionDAG &DAG) const {
2274   MachineFunction &MF = DAG.getMachineFunction();
2275   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2276   unsigned ARMPCLabelIndex = 0;
2277   SDLoc DL(Op);
2278   EVT PtrVT = getPointerTy();
2279   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2280   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2281   SDValue CPAddr;
2282   if (RelocM == Reloc::Static) {
2283     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2284   } else {
2285     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2286     ARMPCLabelIndex = AFI->createPICLabelUId();
2287     ARMConstantPoolValue *CPV =
2288       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2289                                       ARMCP::CPBlockAddress, PCAdj);
2290     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2291   }
2292   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2293   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2294                                MachinePointerInfo::getConstantPool(),
2295                                false, false, false, 0);
2296   if (RelocM == Reloc::Static)
2297     return Result;
2298   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2299   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2300 }
2301
2302 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2303 SDValue
2304 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2305                                                  SelectionDAG &DAG) const {
2306   SDLoc dl(GA);
2307   EVT PtrVT = getPointerTy();
2308   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2309   MachineFunction &MF = DAG.getMachineFunction();
2310   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2311   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2312   ARMConstantPoolValue *CPV =
2313     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2314                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2315   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2316   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2317   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2318                          MachinePointerInfo::getConstantPool(),
2319                          false, false, false, 0);
2320   SDValue Chain = Argument.getValue(1);
2321
2322   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2323   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2324
2325   // call __tls_get_addr.
2326   ArgListTy Args;
2327   ArgListEntry Entry;
2328   Entry.Node = Argument;
2329   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2330   Args.push_back(Entry);
2331
2332   // FIXME: is there useful debug info available here?
2333   TargetLowering::CallLoweringInfo CLI(DAG);
2334   CLI.setDebugLoc(dl).setChain(Chain)
2335     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2336                DAG.getExternalSymbol("__tls_get_addr", PtrVT), &Args, 0);
2337
2338   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2339   return CallResult.first;
2340 }
2341
2342 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2343 // "local exec" model.
2344 SDValue
2345 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2346                                         SelectionDAG &DAG,
2347                                         TLSModel::Model model) const {
2348   const GlobalValue *GV = GA->getGlobal();
2349   SDLoc dl(GA);
2350   SDValue Offset;
2351   SDValue Chain = DAG.getEntryNode();
2352   EVT PtrVT = getPointerTy();
2353   // Get the Thread Pointer
2354   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2355
2356   if (model == TLSModel::InitialExec) {
2357     MachineFunction &MF = DAG.getMachineFunction();
2358     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2359     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2360     // Initial exec model.
2361     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2362     ARMConstantPoolValue *CPV =
2363       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2364                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2365                                       true);
2366     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2367     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2368     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2369                          MachinePointerInfo::getConstantPool(),
2370                          false, false, false, 0);
2371     Chain = Offset.getValue(1);
2372
2373     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2374     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2375
2376     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2377                          MachinePointerInfo::getConstantPool(),
2378                          false, false, false, 0);
2379   } else {
2380     // local exec model
2381     assert(model == TLSModel::LocalExec);
2382     ARMConstantPoolValue *CPV =
2383       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2384     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2385     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2386     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2387                          MachinePointerInfo::getConstantPool(),
2388                          false, false, false, 0);
2389   }
2390
2391   // The address of the thread local variable is the add of the thread
2392   // pointer with the offset of the variable.
2393   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2394 }
2395
2396 SDValue
2397 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2398   // TODO: implement the "local dynamic" model
2399   assert(Subtarget->isTargetELF() &&
2400          "TLS not implemented for non-ELF targets");
2401   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2402
2403   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2404
2405   switch (model) {
2406     case TLSModel::GeneralDynamic:
2407     case TLSModel::LocalDynamic:
2408       return LowerToTLSGeneralDynamicModel(GA, DAG);
2409     case TLSModel::InitialExec:
2410     case TLSModel::LocalExec:
2411       return LowerToTLSExecModels(GA, DAG, model);
2412   }
2413   llvm_unreachable("bogus TLS model");
2414 }
2415
2416 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2417                                                  SelectionDAG &DAG) const {
2418   EVT PtrVT = getPointerTy();
2419   SDLoc dl(Op);
2420   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2421   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2422     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2423     ARMConstantPoolValue *CPV =
2424       ARMConstantPoolConstant::Create(GV,
2425                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2426     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2427     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2428     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2429                                  CPAddr,
2430                                  MachinePointerInfo::getConstantPool(),
2431                                  false, false, false, 0);
2432     SDValue Chain = Result.getValue(1);
2433     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2434     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2435     if (!UseGOTOFF)
2436       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2437                            MachinePointerInfo::getGOT(),
2438                            false, false, false, 0);
2439     return Result;
2440   }
2441
2442   // If we have T2 ops, we can materialize the address directly via movt/movw
2443   // pair. This is always cheaper.
2444   if (Subtarget->useMovt()) {
2445     ++NumMovwMovt;
2446     // FIXME: Once remat is capable of dealing with instructions with register
2447     // operands, expand this into two nodes.
2448     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2449                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2450   } else {
2451     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2452     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2453     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2454                        MachinePointerInfo::getConstantPool(),
2455                        false, false, false, 0);
2456   }
2457 }
2458
2459 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2460                                                     SelectionDAG &DAG) const {
2461   EVT PtrVT = getPointerTy();
2462   SDLoc dl(Op);
2463   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2464   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2465
2466   if (Subtarget->useMovt())
2467     ++NumMovwMovt;
2468
2469   // FIXME: Once remat is capable of dealing with instructions with register
2470   // operands, expand this into multiple nodes
2471   unsigned Wrapper =
2472       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2473
2474   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2475   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2476
2477   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2478     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2479                          MachinePointerInfo::getGOT(), false, false, false, 0);
2480   return Result;
2481 }
2482
2483 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2484                                                      SelectionDAG &DAG) const {
2485   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2486   assert(Subtarget->useMovt() && "Windows on ARM expects to use movw/movt");
2487
2488   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2489   EVT PtrVT = getPointerTy();
2490   SDLoc DL(Op);
2491
2492   ++NumMovwMovt;
2493
2494   // FIXME: Once remat is capable of dealing with instructions with register
2495   // operands, expand this into two nodes.
2496   return DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2497                      DAG.getTargetGlobalAddress(GV, DL, PtrVT));
2498 }
2499
2500 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2501                                                     SelectionDAG &DAG) const {
2502   assert(Subtarget->isTargetELF() &&
2503          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2504   MachineFunction &MF = DAG.getMachineFunction();
2505   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2506   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2507   EVT PtrVT = getPointerTy();
2508   SDLoc dl(Op);
2509   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2510   ARMConstantPoolValue *CPV =
2511     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2512                                   ARMPCLabelIndex, PCAdj);
2513   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2514   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2515   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2516                                MachinePointerInfo::getConstantPool(),
2517                                false, false, false, 0);
2518   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2519   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2520 }
2521
2522 SDValue
2523 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2524   SDLoc dl(Op);
2525   SDValue Val = DAG.getConstant(0, MVT::i32);
2526   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2527                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2528                      Op.getOperand(1), Val);
2529 }
2530
2531 SDValue
2532 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2533   SDLoc dl(Op);
2534   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2535                      Op.getOperand(1), DAG.getConstant(0, MVT::i32));
2536 }
2537
2538 SDValue
2539 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2540                                           const ARMSubtarget *Subtarget) const {
2541   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2542   SDLoc dl(Op);
2543   switch (IntNo) {
2544   default: return SDValue();    // Don't custom lower most intrinsics.
2545   case Intrinsic::arm_rbit: {
2546     assert(Op.getOperand(0).getValueType() == MVT::i32 &&
2547            "RBIT intrinsic must have i32 type!");
2548     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(0));
2549   }
2550   case Intrinsic::arm_thread_pointer: {
2551     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2552     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2553   }
2554   case Intrinsic::eh_sjlj_lsda: {
2555     MachineFunction &MF = DAG.getMachineFunction();
2556     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2557     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2558     EVT PtrVT = getPointerTy();
2559     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2560     SDValue CPAddr;
2561     unsigned PCAdj = (RelocM != Reloc::PIC_)
2562       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2563     ARMConstantPoolValue *CPV =
2564       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2565                                       ARMCP::CPLSDA, PCAdj);
2566     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2567     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2568     SDValue Result =
2569       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2570                   MachinePointerInfo::getConstantPool(),
2571                   false, false, false, 0);
2572
2573     if (RelocM == Reloc::PIC_) {
2574       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, MVT::i32);
2575       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2576     }
2577     return Result;
2578   }
2579   case Intrinsic::arm_neon_vmulls:
2580   case Intrinsic::arm_neon_vmullu: {
2581     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2582       ? ARMISD::VMULLs : ARMISD::VMULLu;
2583     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2584                        Op.getOperand(1), Op.getOperand(2));
2585   }
2586   }
2587 }
2588
2589 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2590                                  const ARMSubtarget *Subtarget) {
2591   // FIXME: handle "fence singlethread" more efficiently.
2592   SDLoc dl(Op);
2593   if (!Subtarget->hasDataBarrier()) {
2594     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2595     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2596     // here.
2597     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2598            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2599     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2600                        DAG.getConstant(0, MVT::i32));
2601   }
2602
2603   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2604   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2605   unsigned Domain = ARM_MB::ISH;
2606   if (Subtarget->isMClass()) {
2607     // Only a full system barrier exists in the M-class architectures.
2608     Domain = ARM_MB::SY;
2609   } else if (Subtarget->isSwift() && Ord == Release) {
2610     // Swift happens to implement ISHST barriers in a way that's compatible with
2611     // Release semantics but weaker than ISH so we'd be fools not to use
2612     // it. Beware: other processors probably don't!
2613     Domain = ARM_MB::ISHST;
2614   }
2615
2616   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2617                      DAG.getConstant(Intrinsic::arm_dmb, MVT::i32),
2618                      DAG.getConstant(Domain, MVT::i32));
2619 }
2620
2621 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2622                              const ARMSubtarget *Subtarget) {
2623   // ARM pre v5TE and Thumb1 does not have preload instructions.
2624   if (!(Subtarget->isThumb2() ||
2625         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2626     // Just preserve the chain.
2627     return Op.getOperand(0);
2628
2629   SDLoc dl(Op);
2630   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2631   if (!isRead &&
2632       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2633     // ARMv7 with MP extension has PLDW.
2634     return Op.getOperand(0);
2635
2636   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2637   if (Subtarget->isThumb()) {
2638     // Invert the bits.
2639     isRead = ~isRead & 1;
2640     isData = ~isData & 1;
2641   }
2642
2643   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2644                      Op.getOperand(1), DAG.getConstant(isRead, MVT::i32),
2645                      DAG.getConstant(isData, MVT::i32));
2646 }
2647
2648 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2649   MachineFunction &MF = DAG.getMachineFunction();
2650   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2651
2652   // vastart just stores the address of the VarArgsFrameIndex slot into the
2653   // memory location argument.
2654   SDLoc dl(Op);
2655   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2656   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2657   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2658   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2659                       MachinePointerInfo(SV), false, false, 0);
2660 }
2661
2662 SDValue
2663 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2664                                         SDValue &Root, SelectionDAG &DAG,
2665                                         SDLoc dl) const {
2666   MachineFunction &MF = DAG.getMachineFunction();
2667   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2668
2669   const TargetRegisterClass *RC;
2670   if (AFI->isThumb1OnlyFunction())
2671     RC = &ARM::tGPRRegClass;
2672   else
2673     RC = &ARM::GPRRegClass;
2674
2675   // Transform the arguments stored in physical registers into virtual ones.
2676   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2677   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2678
2679   SDValue ArgValue2;
2680   if (NextVA.isMemLoc()) {
2681     MachineFrameInfo *MFI = MF.getFrameInfo();
2682     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2683
2684     // Create load node to retrieve arguments from the stack.
2685     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2686     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2687                             MachinePointerInfo::getFixedStack(FI),
2688                             false, false, false, 0);
2689   } else {
2690     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2691     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2692   }
2693   if (!Subtarget->isLittle())
2694     std::swap (ArgValue, ArgValue2);
2695   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2696 }
2697
2698 void
2699 ARMTargetLowering::computeRegArea(CCState &CCInfo, MachineFunction &MF,
2700                                   unsigned InRegsParamRecordIdx,
2701                                   unsigned ArgSize,
2702                                   unsigned &ArgRegsSize,
2703                                   unsigned &ArgRegsSaveSize)
2704   const {
2705   unsigned NumGPRs;
2706   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2707     unsigned RBegin, REnd;
2708     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2709     NumGPRs = REnd - RBegin;
2710   } else {
2711     unsigned int firstUnalloced;
2712     firstUnalloced = CCInfo.getFirstUnallocated(GPRArgRegs,
2713                                                 sizeof(GPRArgRegs) /
2714                                                 sizeof(GPRArgRegs[0]));
2715     NumGPRs = (firstUnalloced <= 3) ? (4 - firstUnalloced) : 0;
2716   }
2717
2718   unsigned Align = MF.getTarget().getFrameLowering()->getStackAlignment();
2719   ArgRegsSize = NumGPRs * 4;
2720
2721   // If parameter is split between stack and GPRs...
2722   if (NumGPRs && Align > 4 &&
2723       (ArgRegsSize < ArgSize ||
2724         InRegsParamRecordIdx >= CCInfo.getInRegsParamsCount())) {
2725     // Add padding for part of param recovered from GPRs.  For example,
2726     // if Align == 8, its last byte must be at address K*8 - 1.
2727     // We need to do it, since remained (stack) part of parameter has
2728     // stack alignment, and we need to "attach" "GPRs head" without gaps
2729     // to it:
2730     // Stack:
2731     // |---- 8 bytes block ----| |---- 8 bytes block ----| |---- 8 bytes...
2732     // [ [padding] [GPRs head] ] [        Tail passed via stack       ....
2733     //
2734     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2735     unsigned Padding =
2736         OffsetToAlignment(ArgRegsSize + AFI->getArgRegsSaveSize(), Align);
2737     ArgRegsSaveSize = ArgRegsSize + Padding;
2738   } else
2739     // We don't need to extend regs save size for byval parameters if they
2740     // are passed via GPRs only.
2741     ArgRegsSaveSize = ArgRegsSize;
2742 }
2743
2744 // The remaining GPRs hold either the beginning of variable-argument
2745 // data, or the beginning of an aggregate passed by value (usually
2746 // byval).  Either way, we allocate stack slots adjacent to the data
2747 // provided by our caller, and store the unallocated registers there.
2748 // If this is a variadic function, the va_list pointer will begin with
2749 // these values; otherwise, this reassembles a (byval) structure that
2750 // was split between registers and memory.
2751 // Return: The frame index registers were stored into.
2752 int
2753 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2754                                   SDLoc dl, SDValue &Chain,
2755                                   const Value *OrigArg,
2756                                   unsigned InRegsParamRecordIdx,
2757                                   unsigned OffsetFromOrigArg,
2758                                   unsigned ArgOffset,
2759                                   unsigned ArgSize,
2760                                   bool ForceMutable,
2761                                   unsigned ByValStoreOffset,
2762                                   unsigned TotalArgRegsSaveSize) const {
2763
2764   // Currently, two use-cases possible:
2765   // Case #1. Non-var-args function, and we meet first byval parameter.
2766   //          Setup first unallocated register as first byval register;
2767   //          eat all remained registers
2768   //          (these two actions are performed by HandleByVal method).
2769   //          Then, here, we initialize stack frame with
2770   //          "store-reg" instructions.
2771   // Case #2. Var-args function, that doesn't contain byval parameters.
2772   //          The same: eat all remained unallocated registers,
2773   //          initialize stack frame.
2774
2775   MachineFunction &MF = DAG.getMachineFunction();
2776   MachineFrameInfo *MFI = MF.getFrameInfo();
2777   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2778   unsigned firstRegToSaveIndex, lastRegToSaveIndex;
2779   unsigned RBegin, REnd;
2780   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2781     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2782     firstRegToSaveIndex = RBegin - ARM::R0;
2783     lastRegToSaveIndex = REnd - ARM::R0;
2784   } else {
2785     firstRegToSaveIndex = CCInfo.getFirstUnallocated
2786       (GPRArgRegs, array_lengthof(GPRArgRegs));
2787     lastRegToSaveIndex = 4;
2788   }
2789
2790   unsigned ArgRegsSize, ArgRegsSaveSize;
2791   computeRegArea(CCInfo, MF, InRegsParamRecordIdx, ArgSize,
2792                  ArgRegsSize, ArgRegsSaveSize);
2793
2794   // Store any by-val regs to their spots on the stack so that they may be
2795   // loaded by deferencing the result of formal parameter pointer or va_next.
2796   // Note: once stack area for byval/varargs registers
2797   // was initialized, it can't be initialized again.
2798   if (ArgRegsSaveSize) {
2799     unsigned Padding = ArgRegsSaveSize - ArgRegsSize;
2800
2801     if (Padding) {
2802       assert(AFI->getStoredByValParamsPadding() == 0 &&
2803              "The only parameter may be padded.");
2804       AFI->setStoredByValParamsPadding(Padding);
2805     }
2806
2807     int FrameIndex = MFI->CreateFixedObject(ArgRegsSaveSize,
2808                                             Padding +
2809                                               ByValStoreOffset -
2810                                               (int64_t)TotalArgRegsSaveSize,
2811                                             false);
2812     SDValue FIN = DAG.getFrameIndex(FrameIndex, getPointerTy());
2813     if (Padding) {
2814        MFI->CreateFixedObject(Padding,
2815                               ArgOffset + ByValStoreOffset -
2816                                 (int64_t)ArgRegsSaveSize,
2817                               false);
2818     }
2819
2820     SmallVector<SDValue, 4> MemOps;
2821     for (unsigned i = 0; firstRegToSaveIndex < lastRegToSaveIndex;
2822          ++firstRegToSaveIndex, ++i) {
2823       const TargetRegisterClass *RC;
2824       if (AFI->isThumb1OnlyFunction())
2825         RC = &ARM::tGPRRegClass;
2826       else
2827         RC = &ARM::GPRRegClass;
2828
2829       unsigned VReg = MF.addLiveIn(GPRArgRegs[firstRegToSaveIndex], RC);
2830       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2831       SDValue Store =
2832         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2833                      MachinePointerInfo(OrigArg, OffsetFromOrigArg + 4*i),
2834                      false, false, 0);
2835       MemOps.push_back(Store);
2836       FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
2837                         DAG.getConstant(4, getPointerTy()));
2838     }
2839
2840     AFI->setArgRegsSaveSize(ArgRegsSaveSize + AFI->getArgRegsSaveSize());
2841
2842     if (!MemOps.empty())
2843       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2844     return FrameIndex;
2845   } else {
2846     if (ArgSize == 0) {
2847       // We cannot allocate a zero-byte object for the first variadic argument,
2848       // so just make up a size.
2849       ArgSize = 4;
2850     }
2851     // This will point to the next argument passed via stack.
2852     return MFI->CreateFixedObject(
2853       ArgSize, ArgOffset, !ForceMutable);
2854   }
2855 }
2856
2857 // Setup stack frame, the va_list pointer will start from.
2858 void
2859 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2860                                         SDLoc dl, SDValue &Chain,
2861                                         unsigned ArgOffset,
2862                                         unsigned TotalArgRegsSaveSize,
2863                                         bool ForceMutable) const {
2864   MachineFunction &MF = DAG.getMachineFunction();
2865   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2866
2867   // Try to store any remaining integer argument regs
2868   // to their spots on the stack so that they may be loaded by deferencing
2869   // the result of va_next.
2870   // If there is no regs to be stored, just point address after last
2871   // argument passed via stack.
2872   int FrameIndex =
2873     StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2874                    CCInfo.getInRegsParamsCount(), 0, ArgOffset, 0, ForceMutable,
2875                    0, TotalArgRegsSaveSize);
2876
2877   AFI->setVarArgsFrameIndex(FrameIndex);
2878 }
2879
2880 SDValue
2881 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
2882                                         CallingConv::ID CallConv, bool isVarArg,
2883                                         const SmallVectorImpl<ISD::InputArg>
2884                                           &Ins,
2885                                         SDLoc dl, SelectionDAG &DAG,
2886                                         SmallVectorImpl<SDValue> &InVals)
2887                                           const {
2888   MachineFunction &MF = DAG.getMachineFunction();
2889   MachineFrameInfo *MFI = MF.getFrameInfo();
2890
2891   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2892
2893   // Assign locations to all of the incoming arguments.
2894   SmallVector<CCValAssign, 16> ArgLocs;
2895   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2896                     getTargetMachine(), ArgLocs, *DAG.getContext(), Prologue);
2897   CCInfo.AnalyzeFormalArguments(Ins,
2898                                 CCAssignFnForNode(CallConv, /* Return*/ false,
2899                                                   isVarArg));
2900
2901   SmallVector<SDValue, 16> ArgValues;
2902   int lastInsIndex = -1;
2903   SDValue ArgValue;
2904   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2905   unsigned CurArgIdx = 0;
2906
2907   // Initially ArgRegsSaveSize is zero.
2908   // Then we increase this value each time we meet byval parameter.
2909   // We also increase this value in case of varargs function.
2910   AFI->setArgRegsSaveSize(0);
2911
2912   unsigned ByValStoreOffset = 0;
2913   unsigned TotalArgRegsSaveSize = 0;
2914   unsigned ArgRegsSaveSizeMaxAlign = 4;
2915
2916   // Calculate the amount of stack space that we need to allocate to store
2917   // byval and variadic arguments that are passed in registers.
2918   // We need to know this before we allocate the first byval or variadic
2919   // argument, as they will be allocated a stack slot below the CFA (Canonical
2920   // Frame Address, the stack pointer at entry to the function).
2921   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2922     CCValAssign &VA = ArgLocs[i];
2923     if (VA.isMemLoc()) {
2924       int index = VA.getValNo();
2925       if (index != lastInsIndex) {
2926         ISD::ArgFlagsTy Flags = Ins[index].Flags;
2927         if (Flags.isByVal()) {
2928           unsigned ExtraArgRegsSize;
2929           unsigned ExtraArgRegsSaveSize;
2930           computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsProceed(),
2931                          Flags.getByValSize(),
2932                          ExtraArgRegsSize, ExtraArgRegsSaveSize);
2933
2934           TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2935           if (Flags.getByValAlign() > ArgRegsSaveSizeMaxAlign)
2936               ArgRegsSaveSizeMaxAlign = Flags.getByValAlign();
2937           CCInfo.nextInRegsParam();
2938         }
2939         lastInsIndex = index;
2940       }
2941     }
2942   }
2943   CCInfo.rewindByValRegsInfo();
2944   lastInsIndex = -1;
2945   if (isVarArg) {
2946     unsigned ExtraArgRegsSize;
2947     unsigned ExtraArgRegsSaveSize;
2948     computeRegArea(CCInfo, MF, CCInfo.getInRegsParamsCount(), 0,
2949                    ExtraArgRegsSize, ExtraArgRegsSaveSize);
2950     TotalArgRegsSaveSize += ExtraArgRegsSaveSize;
2951   }
2952   // If the arg regs save area contains N-byte aligned values, the
2953   // bottom of it must be at least N-byte aligned.
2954   TotalArgRegsSaveSize = RoundUpToAlignment(TotalArgRegsSaveSize, ArgRegsSaveSizeMaxAlign);
2955   TotalArgRegsSaveSize = std::min(TotalArgRegsSaveSize, 16U);
2956
2957   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2958     CCValAssign &VA = ArgLocs[i];
2959     std::advance(CurOrigArg, Ins[VA.getValNo()].OrigArgIndex - CurArgIdx);
2960     CurArgIdx = Ins[VA.getValNo()].OrigArgIndex;
2961     // Arguments stored in registers.
2962     if (VA.isRegLoc()) {
2963       EVT RegVT = VA.getLocVT();
2964
2965       if (VA.needsCustom()) {
2966         // f64 and vector types are split up into multiple registers or
2967         // combinations of registers and stack slots.
2968         if (VA.getLocVT() == MVT::v2f64) {
2969           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
2970                                                    Chain, DAG, dl);
2971           VA = ArgLocs[++i]; // skip ahead to next loc
2972           SDValue ArgValue2;
2973           if (VA.isMemLoc()) {
2974             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
2975             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2976             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
2977                                     MachinePointerInfo::getFixedStack(FI),
2978                                     false, false, false, 0);
2979           } else {
2980             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
2981                                              Chain, DAG, dl);
2982           }
2983           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2984           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2985                                  ArgValue, ArgValue1, DAG.getIntPtrConstant(0));
2986           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
2987                                  ArgValue, ArgValue2, DAG.getIntPtrConstant(1));
2988         } else
2989           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
2990
2991       } else {
2992         const TargetRegisterClass *RC;
2993
2994         if (RegVT == MVT::f32)
2995           RC = &ARM::SPRRegClass;
2996         else if (RegVT == MVT::f64)
2997           RC = &ARM::DPRRegClass;
2998         else if (RegVT == MVT::v2f64)
2999           RC = &ARM::QPRRegClass;
3000         else if (RegVT == MVT::i32)
3001           RC = AFI->isThumb1OnlyFunction() ?
3002             (const TargetRegisterClass*)&ARM::tGPRRegClass :
3003             (const TargetRegisterClass*)&ARM::GPRRegClass;
3004         else
3005           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3006
3007         // Transform the arguments in physical registers into virtual ones.
3008         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3009         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3010       }
3011
3012       // If this is an 8 or 16-bit value, it is really passed promoted
3013       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3014       // truncate to the right size.
3015       switch (VA.getLocInfo()) {
3016       default: llvm_unreachable("Unknown loc info!");
3017       case CCValAssign::Full: break;
3018       case CCValAssign::BCvt:
3019         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3020         break;
3021       case CCValAssign::SExt:
3022         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3023                                DAG.getValueType(VA.getValVT()));
3024         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3025         break;
3026       case CCValAssign::ZExt:
3027         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3028                                DAG.getValueType(VA.getValVT()));
3029         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3030         break;
3031       }
3032
3033       InVals.push_back(ArgValue);
3034
3035     } else { // VA.isRegLoc()
3036
3037       // sanity check
3038       assert(VA.isMemLoc());
3039       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3040
3041       int index = ArgLocs[i].getValNo();
3042
3043       // Some Ins[] entries become multiple ArgLoc[] entries.
3044       // Process them only once.
3045       if (index != lastInsIndex)
3046         {
3047           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3048           // FIXME: For now, all byval parameter objects are marked mutable.
3049           // This can be changed with more analysis.
3050           // In case of tail call optimization mark all arguments mutable.
3051           // Since they could be overwritten by lowering of arguments in case of
3052           // a tail call.
3053           if (Flags.isByVal()) {
3054             unsigned CurByValIndex = CCInfo.getInRegsParamsProceed();
3055
3056             ByValStoreOffset = RoundUpToAlignment(ByValStoreOffset, Flags.getByValAlign());
3057             int FrameIndex = StoreByValRegs(
3058                 CCInfo, DAG, dl, Chain, CurOrigArg,
3059                 CurByValIndex,
3060                 Ins[VA.getValNo()].PartOffset,
3061                 VA.getLocMemOffset(),
3062                 Flags.getByValSize(),
3063                 true /*force mutable frames*/,
3064                 ByValStoreOffset,
3065                 TotalArgRegsSaveSize);
3066             ByValStoreOffset += Flags.getByValSize();
3067             ByValStoreOffset = std::min(ByValStoreOffset, 16U);
3068             InVals.push_back(DAG.getFrameIndex(FrameIndex, getPointerTy()));
3069             CCInfo.nextInRegsParam();
3070           } else {
3071             unsigned FIOffset = VA.getLocMemOffset();
3072             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3073                                             FIOffset, true);
3074
3075             // Create load nodes to retrieve arguments from the stack.
3076             SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3077             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3078                                          MachinePointerInfo::getFixedStack(FI),
3079                                          false, false, false, 0));
3080           }
3081           lastInsIndex = index;
3082         }
3083     }
3084   }
3085
3086   // varargs
3087   if (isVarArg)
3088     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3089                          CCInfo.getNextStackOffset(),
3090                          TotalArgRegsSaveSize);
3091
3092   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3093
3094   return Chain;
3095 }
3096
3097 /// isFloatingPointZero - Return true if this is +0.0.
3098 static bool isFloatingPointZero(SDValue Op) {
3099   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3100     return CFP->getValueAPF().isPosZero();
3101   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3102     // Maybe this has already been legalized into the constant pool?
3103     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3104       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3105       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3106         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3107           return CFP->getValueAPF().isPosZero();
3108     }
3109   }
3110   return false;
3111 }
3112
3113 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3114 /// the given operands.
3115 SDValue
3116 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3117                              SDValue &ARMcc, SelectionDAG &DAG,
3118                              SDLoc dl) const {
3119   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3120     unsigned C = RHSC->getZExtValue();
3121     if (!isLegalICmpImmediate(C)) {
3122       // Constant does not fit, try adjusting it by one?
3123       switch (CC) {
3124       default: break;
3125       case ISD::SETLT:
3126       case ISD::SETGE:
3127         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3128           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3129           RHS = DAG.getConstant(C-1, MVT::i32);
3130         }
3131         break;
3132       case ISD::SETULT:
3133       case ISD::SETUGE:
3134         if (C != 0 && isLegalICmpImmediate(C-1)) {
3135           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3136           RHS = DAG.getConstant(C-1, MVT::i32);
3137         }
3138         break;
3139       case ISD::SETLE:
3140       case ISD::SETGT:
3141         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3142           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3143           RHS = DAG.getConstant(C+1, MVT::i32);
3144         }
3145         break;
3146       case ISD::SETULE:
3147       case ISD::SETUGT:
3148         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3149           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3150           RHS = DAG.getConstant(C+1, MVT::i32);
3151         }
3152         break;
3153       }
3154     }
3155   }
3156
3157   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3158   ARMISD::NodeType CompareType;
3159   switch (CondCode) {
3160   default:
3161     CompareType = ARMISD::CMP;
3162     break;
3163   case ARMCC::EQ:
3164   case ARMCC::NE:
3165     // Uses only Z Flag
3166     CompareType = ARMISD::CMPZ;
3167     break;
3168   }
3169   ARMcc = DAG.getConstant(CondCode, MVT::i32);
3170   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3171 }
3172
3173 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3174 SDValue
3175 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3176                              SDLoc dl) const {
3177   SDValue Cmp;
3178   if (!isFloatingPointZero(RHS))
3179     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3180   else
3181     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3182   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3183 }
3184
3185 /// duplicateCmp - Glue values can have only one use, so this function
3186 /// duplicates a comparison node.
3187 SDValue
3188 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3189   unsigned Opc = Cmp.getOpcode();
3190   SDLoc DL(Cmp);
3191   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3192     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3193
3194   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3195   Cmp = Cmp.getOperand(0);
3196   Opc = Cmp.getOpcode();
3197   if (Opc == ARMISD::CMPFP)
3198     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3199   else {
3200     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3201     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3202   }
3203   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3204 }
3205
3206 std::pair<SDValue, SDValue>
3207 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3208                                  SDValue &ARMcc) const {
3209   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3210
3211   SDValue Value, OverflowCmp;
3212   SDValue LHS = Op.getOperand(0);
3213   SDValue RHS = Op.getOperand(1);
3214
3215
3216   // FIXME: We are currently always generating CMPs because we don't support
3217   // generating CMN through the backend. This is not as good as the natural
3218   // CMP case because it causes a register dependency and cannot be folded
3219   // later.
3220
3221   switch (Op.getOpcode()) {
3222   default:
3223     llvm_unreachable("Unknown overflow instruction!");
3224   case ISD::SADDO:
3225     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3226     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3227     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3228     break;
3229   case ISD::UADDO:
3230     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3231     Value = DAG.getNode(ISD::ADD, SDLoc(Op), Op.getValueType(), LHS, RHS);
3232     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, Value, LHS);
3233     break;
3234   case ISD::SSUBO:
3235     ARMcc = DAG.getConstant(ARMCC::VC, MVT::i32);
3236     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3237     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3238     break;
3239   case ISD::USUBO:
3240     ARMcc = DAG.getConstant(ARMCC::HS, MVT::i32);
3241     Value = DAG.getNode(ISD::SUB, SDLoc(Op), Op.getValueType(), LHS, RHS);
3242     OverflowCmp = DAG.getNode(ARMISD::CMP, SDLoc(Op), MVT::Glue, LHS, RHS);
3243     break;
3244   } // switch (...)
3245
3246   return std::make_pair(Value, OverflowCmp);
3247 }
3248
3249
3250 SDValue
3251 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3252   // Let legalize expand this if it isn't a legal type yet.
3253   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3254     return SDValue();
3255
3256   SDValue Value, OverflowCmp;
3257   SDValue ARMcc;
3258   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3259   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3260   // We use 0 and 1 as false and true values.
3261   SDValue TVal = DAG.getConstant(1, MVT::i32);
3262   SDValue FVal = DAG.getConstant(0, MVT::i32);
3263   EVT VT = Op.getValueType();
3264
3265   SDValue Overflow = DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, TVal, FVal,
3266                                  ARMcc, CCR, OverflowCmp);
3267
3268   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3269   return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
3270 }
3271
3272
3273 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3274   SDValue Cond = Op.getOperand(0);
3275   SDValue SelectTrue = Op.getOperand(1);
3276   SDValue SelectFalse = Op.getOperand(2);
3277   SDLoc dl(Op);
3278   unsigned Opc = Cond.getOpcode();
3279
3280   if (Cond.getResNo() == 1 &&
3281       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3282        Opc == ISD::USUBO)) {
3283     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3284       return SDValue();
3285
3286     SDValue Value, OverflowCmp;
3287     SDValue ARMcc;
3288     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3289     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3290     EVT VT = Op.getValueType();
3291
3292     return DAG.getNode(ARMISD::CMOV, SDLoc(Op), VT, SelectTrue, SelectFalse,
3293                        ARMcc, CCR, OverflowCmp);
3294
3295   }
3296
3297   // Convert:
3298   //
3299   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3300   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3301   //
3302   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3303     const ConstantSDNode *CMOVTrue =
3304       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3305     const ConstantSDNode *CMOVFalse =
3306       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3307
3308     if (CMOVTrue && CMOVFalse) {
3309       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3310       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3311
3312       SDValue True;
3313       SDValue False;
3314       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3315         True = SelectTrue;
3316         False = SelectFalse;
3317       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3318         True = SelectFalse;
3319         False = SelectTrue;
3320       }
3321
3322       if (True.getNode() && False.getNode()) {
3323         EVT VT = Op.getValueType();
3324         SDValue ARMcc = Cond.getOperand(2);
3325         SDValue CCR = Cond.getOperand(3);
3326         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3327         assert(True.getValueType() == VT);
3328         return DAG.getNode(ARMISD::CMOV, dl, VT, True, False, ARMcc, CCR, Cmp);
3329       }
3330     }
3331   }
3332
3333   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3334   // undefined bits before doing a full-word comparison with zero.
3335   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3336                      DAG.getConstant(1, Cond.getValueType()));
3337
3338   return DAG.getSelectCC(dl, Cond,
3339                          DAG.getConstant(0, Cond.getValueType()),
3340                          SelectTrue, SelectFalse, ISD::SETNE);
3341 }
3342
3343 static ISD::CondCode getInverseCCForVSEL(ISD::CondCode CC) {
3344   if (CC == ISD::SETNE)
3345     return ISD::SETEQ;
3346   return ISD::getSetCCInverse(CC, true);
3347 }
3348
3349 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3350                                  bool &swpCmpOps, bool &swpVselOps) {
3351   // Start by selecting the GE condition code for opcodes that return true for
3352   // 'equality'
3353   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3354       CC == ISD::SETULE)
3355     CondCode = ARMCC::GE;
3356
3357   // and GT for opcodes that return false for 'equality'.
3358   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3359            CC == ISD::SETULT)
3360     CondCode = ARMCC::GT;
3361
3362   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3363   // to swap the compare operands.
3364   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3365       CC == ISD::SETULT)
3366     swpCmpOps = true;
3367
3368   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3369   // If we have an unordered opcode, we need to swap the operands to the VSEL
3370   // instruction (effectively negating the condition).
3371   //
3372   // This also has the effect of swapping which one of 'less' or 'greater'
3373   // returns true, so we also swap the compare operands. It also switches
3374   // whether we return true for 'equality', so we compensate by picking the
3375   // opposite condition code to our original choice.
3376   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3377       CC == ISD::SETUGT) {
3378     swpCmpOps = !swpCmpOps;
3379     swpVselOps = !swpVselOps;
3380     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3381   }
3382
3383   // 'ordered' is 'anything but unordered', so use the VS condition code and
3384   // swap the VSEL operands.
3385   if (CC == ISD::SETO) {
3386     CondCode = ARMCC::VS;
3387     swpVselOps = true;
3388   }
3389
3390   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3391   // code and swap the VSEL operands.
3392   if (CC == ISD::SETUNE) {
3393     CondCode = ARMCC::EQ;
3394     swpVselOps = true;
3395   }
3396 }
3397
3398 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3399   EVT VT = Op.getValueType();
3400   SDValue LHS = Op.getOperand(0);
3401   SDValue RHS = Op.getOperand(1);
3402   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3403   SDValue TrueVal = Op.getOperand(2);
3404   SDValue FalseVal = Op.getOperand(3);
3405   SDLoc dl(Op);
3406
3407   if (LHS.getValueType() == MVT::i32) {
3408     // Try to generate VSEL on ARMv8.
3409     // The VSEL instruction can't use all the usual ARM condition
3410     // codes: it only has two bits to select the condition code, so it's
3411     // constrained to use only GE, GT, VS and EQ.
3412     //
3413     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3414     // swap the operands of the previous compare instruction (effectively
3415     // inverting the compare condition, swapping 'less' and 'greater') and
3416     // sometimes need to swap the operands to the VSEL (which inverts the
3417     // condition in the sense of firing whenever the previous condition didn't)
3418     if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3419                                       TrueVal.getValueType() == MVT::f64)) {
3420       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3421       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3422           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3423         CC = getInverseCCForVSEL(CC);
3424         std::swap(TrueVal, FalseVal);
3425       }
3426     }
3427
3428     SDValue ARMcc;
3429     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3430     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3431     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3432                        Cmp);
3433   }
3434
3435   ARMCC::CondCodes CondCode, CondCode2;
3436   FPCCToARMCC(CC, CondCode, CondCode2);
3437
3438   // Try to generate VSEL on ARMv8.
3439   if (getSubtarget()->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3440                                     TrueVal.getValueType() == MVT::f64)) {
3441     // We can select VMAXNM/VMINNM from a compare followed by a select with the
3442     // same operands, as follows:
3443     //   c = fcmp [ogt, olt, ugt, ult] a, b
3444     //   select c, a, b
3445     // We only do this in unsafe-fp-math, because signed zeros and NaNs are
3446     // handled differently than the original code sequence.
3447     if (getTargetMachine().Options.UnsafeFPMath && LHS == TrueVal &&
3448         RHS == FalseVal) {
3449       if (CC == ISD::SETOGT || CC == ISD::SETUGT)
3450         return DAG.getNode(ARMISD::VMAXNM, dl, VT, TrueVal, FalseVal);
3451       if (CC == ISD::SETOLT || CC == ISD::SETULT)
3452         return DAG.getNode(ARMISD::VMINNM, dl, VT, TrueVal, FalseVal);
3453     }
3454
3455     bool swpCmpOps = false;
3456     bool swpVselOps = false;
3457     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3458
3459     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3460         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3461       if (swpCmpOps)
3462         std::swap(LHS, RHS);
3463       if (swpVselOps)
3464         std::swap(TrueVal, FalseVal);
3465     }
3466   }
3467
3468   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3469   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3470   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3471   SDValue Result = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
3472                                ARMcc, CCR, Cmp);
3473   if (CondCode2 != ARMCC::AL) {
3474     SDValue ARMcc2 = DAG.getConstant(CondCode2, MVT::i32);
3475     // FIXME: Needs another CMP because flag can have but one use.
3476     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3477     Result = DAG.getNode(ARMISD::CMOV, dl, VT,
3478                          Result, TrueVal, ARMcc2, CCR, Cmp2);
3479   }
3480   return Result;
3481 }
3482
3483 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3484 /// to morph to an integer compare sequence.
3485 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3486                            const ARMSubtarget *Subtarget) {
3487   SDNode *N = Op.getNode();
3488   if (!N->hasOneUse())
3489     // Otherwise it requires moving the value from fp to integer registers.
3490     return false;
3491   if (!N->getNumValues())
3492     return false;
3493   EVT VT = Op.getValueType();
3494   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3495     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3496     // vmrs are very slow, e.g. cortex-a8.
3497     return false;
3498
3499   if (isFloatingPointZero(Op)) {
3500     SeenZero = true;
3501     return true;
3502   }
3503   return ISD::isNormalLoad(N);
3504 }
3505
3506 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3507   if (isFloatingPointZero(Op))
3508     return DAG.getConstant(0, MVT::i32);
3509
3510   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3511     return DAG.getLoad(MVT::i32, SDLoc(Op),
3512                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3513                        Ld->isVolatile(), Ld->isNonTemporal(),
3514                        Ld->isInvariant(), Ld->getAlignment());
3515
3516   llvm_unreachable("Unknown VFP cmp argument!");
3517 }
3518
3519 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3520                            SDValue &RetVal1, SDValue &RetVal2) {
3521   if (isFloatingPointZero(Op)) {
3522     RetVal1 = DAG.getConstant(0, MVT::i32);
3523     RetVal2 = DAG.getConstant(0, MVT::i32);
3524     return;
3525   }
3526
3527   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3528     SDValue Ptr = Ld->getBasePtr();
3529     RetVal1 = DAG.getLoad(MVT::i32, SDLoc(Op),
3530                           Ld->getChain(), Ptr,
3531                           Ld->getPointerInfo(),
3532                           Ld->isVolatile(), Ld->isNonTemporal(),
3533                           Ld->isInvariant(), Ld->getAlignment());
3534
3535     EVT PtrType = Ptr.getValueType();
3536     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3537     SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(Op),
3538                                  PtrType, Ptr, DAG.getConstant(4, PtrType));
3539     RetVal2 = DAG.getLoad(MVT::i32, SDLoc(Op),
3540                           Ld->getChain(), NewPtr,
3541                           Ld->getPointerInfo().getWithOffset(4),
3542                           Ld->isVolatile(), Ld->isNonTemporal(),
3543                           Ld->isInvariant(), NewAlign);
3544     return;
3545   }
3546
3547   llvm_unreachable("Unknown VFP cmp argument!");
3548 }
3549
3550 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3551 /// f32 and even f64 comparisons to integer ones.
3552 SDValue
3553 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3554   SDValue Chain = Op.getOperand(0);
3555   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3556   SDValue LHS = Op.getOperand(2);
3557   SDValue RHS = Op.getOperand(3);
3558   SDValue Dest = Op.getOperand(4);
3559   SDLoc dl(Op);
3560
3561   bool LHSSeenZero = false;
3562   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3563   bool RHSSeenZero = false;
3564   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3565   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3566     // If unsafe fp math optimization is enabled and there are no other uses of
3567     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3568     // to an integer comparison.
3569     if (CC == ISD::SETOEQ)
3570       CC = ISD::SETEQ;
3571     else if (CC == ISD::SETUNE)
3572       CC = ISD::SETNE;
3573
3574     SDValue Mask = DAG.getConstant(0x7fffffff, MVT::i32);
3575     SDValue ARMcc;
3576     if (LHS.getValueType() == MVT::f32) {
3577       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3578                         bitcastf32Toi32(LHS, DAG), Mask);
3579       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3580                         bitcastf32Toi32(RHS, DAG), Mask);
3581       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3582       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3583       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3584                          Chain, Dest, ARMcc, CCR, Cmp);
3585     }
3586
3587     SDValue LHS1, LHS2;
3588     SDValue RHS1, RHS2;
3589     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3590     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3591     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3592     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3593     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3594     ARMcc = DAG.getConstant(CondCode, MVT::i32);
3595     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3596     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3597     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3598   }
3599
3600   return SDValue();
3601 }
3602
3603 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3604   SDValue Chain = Op.getOperand(0);
3605   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3606   SDValue LHS = Op.getOperand(2);
3607   SDValue RHS = Op.getOperand(3);
3608   SDValue Dest = Op.getOperand(4);
3609   SDLoc dl(Op);
3610
3611   if (LHS.getValueType() == MVT::i32) {
3612     SDValue ARMcc;
3613     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3614     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3615     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3616                        Chain, Dest, ARMcc, CCR, Cmp);
3617   }
3618
3619   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3620
3621   if (getTargetMachine().Options.UnsafeFPMath &&
3622       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3623        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3624     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3625     if (Result.getNode())
3626       return Result;
3627   }
3628
3629   ARMCC::CondCodes CondCode, CondCode2;
3630   FPCCToARMCC(CC, CondCode, CondCode2);
3631
3632   SDValue ARMcc = DAG.getConstant(CondCode, MVT::i32);
3633   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3634   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3635   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3636   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3637   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3638   if (CondCode2 != ARMCC::AL) {
3639     ARMcc = DAG.getConstant(CondCode2, MVT::i32);
3640     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3641     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3642   }
3643   return Res;
3644 }
3645
3646 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3647   SDValue Chain = Op.getOperand(0);
3648   SDValue Table = Op.getOperand(1);
3649   SDValue Index = Op.getOperand(2);
3650   SDLoc dl(Op);
3651
3652   EVT PTy = getPointerTy();
3653   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3654   ARMFunctionInfo *AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3655   SDValue UId = DAG.getConstant(AFI->createJumpTableUId(), PTy);
3656   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3657   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI, UId);
3658   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, PTy));
3659   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3660   if (Subtarget->isThumb2()) {
3661     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3662     // which does another jump to the destination. This also makes it easier
3663     // to translate it to TBB / TBH later.
3664     // FIXME: This might not work if the function is extremely large.
3665     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3666                        Addr, Op.getOperand(2), JTI, UId);
3667   }
3668   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3669     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3670                        MachinePointerInfo::getJumpTable(),
3671                        false, false, false, 0);
3672     Chain = Addr.getValue(1);
3673     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3674     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3675   } else {
3676     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3677                        MachinePointerInfo::getJumpTable(),
3678                        false, false, false, 0);
3679     Chain = Addr.getValue(1);
3680     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI, UId);
3681   }
3682 }
3683
3684 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3685   EVT VT = Op.getValueType();
3686   SDLoc dl(Op);
3687
3688   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3689     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3690       return Op;
3691     return DAG.UnrollVectorOp(Op.getNode());
3692   }
3693
3694   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3695          "Invalid type for custom lowering!");
3696   if (VT != MVT::v4i16)
3697     return DAG.UnrollVectorOp(Op.getNode());
3698
3699   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3700   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3701 }
3702
3703 static SDValue LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3704   EVT VT = Op.getValueType();
3705   if (VT.isVector())
3706     return LowerVectorFP_TO_INT(Op, DAG);
3707
3708   SDLoc dl(Op);
3709   unsigned Opc;
3710
3711   switch (Op.getOpcode()) {
3712   default: llvm_unreachable("Invalid opcode!");
3713   case ISD::FP_TO_SINT:
3714     Opc = ARMISD::FTOSI;
3715     break;
3716   case ISD::FP_TO_UINT:
3717     Opc = ARMISD::FTOUI;
3718     break;
3719   }
3720   Op = DAG.getNode(Opc, dl, MVT::f32, Op.getOperand(0));
3721   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3722 }
3723
3724 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3725   EVT VT = Op.getValueType();
3726   SDLoc dl(Op);
3727
3728   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3729     if (VT.getVectorElementType() == MVT::f32)
3730       return Op;
3731     return DAG.UnrollVectorOp(Op.getNode());
3732   }
3733
3734   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3735          "Invalid type for custom lowering!");
3736   if (VT != MVT::v4f32)
3737     return DAG.UnrollVectorOp(Op.getNode());
3738
3739   unsigned CastOpc;
3740   unsigned Opc;
3741   switch (Op.getOpcode()) {
3742   default: llvm_unreachable("Invalid opcode!");
3743   case ISD::SINT_TO_FP:
3744     CastOpc = ISD::SIGN_EXTEND;
3745     Opc = ISD::SINT_TO_FP;
3746     break;
3747   case ISD::UINT_TO_FP:
3748     CastOpc = ISD::ZERO_EXTEND;
3749     Opc = ISD::UINT_TO_FP;
3750     break;
3751   }
3752
3753   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
3754   return DAG.getNode(Opc, dl, VT, Op);
3755 }
3756
3757 static SDValue LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3758   EVT VT = Op.getValueType();
3759   if (VT.isVector())
3760     return LowerVectorINT_TO_FP(Op, DAG);
3761
3762   SDLoc dl(Op);
3763   unsigned Opc;
3764
3765   switch (Op.getOpcode()) {
3766   default: llvm_unreachable("Invalid opcode!");
3767   case ISD::SINT_TO_FP:
3768     Opc = ARMISD::SITOF;
3769     break;
3770   case ISD::UINT_TO_FP:
3771     Opc = ARMISD::UITOF;
3772     break;
3773   }
3774
3775   Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
3776   return DAG.getNode(Opc, dl, VT, Op);
3777 }
3778
3779 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
3780   // Implement fcopysign with a fabs and a conditional fneg.
3781   SDValue Tmp0 = Op.getOperand(0);
3782   SDValue Tmp1 = Op.getOperand(1);
3783   SDLoc dl(Op);
3784   EVT VT = Op.getValueType();
3785   EVT SrcVT = Tmp1.getValueType();
3786   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
3787     Tmp0.getOpcode() == ARMISD::VMOVDRR;
3788   bool UseNEON = !InGPR && Subtarget->hasNEON();
3789
3790   if (UseNEON) {
3791     // Use VBSL to copy the sign bit.
3792     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
3793     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
3794                                DAG.getTargetConstant(EncodedVal, MVT::i32));
3795     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
3796     if (VT == MVT::f64)
3797       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3798                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
3799                          DAG.getConstant(32, MVT::i32));
3800     else /*if (VT == MVT::f32)*/
3801       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
3802     if (SrcVT == MVT::f32) {
3803       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
3804       if (VT == MVT::f64)
3805         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
3806                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
3807                            DAG.getConstant(32, MVT::i32));
3808     } else if (VT == MVT::f32)
3809       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
3810                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
3811                          DAG.getConstant(32, MVT::i32));
3812     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
3813     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
3814
3815     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
3816                                             MVT::i32);
3817     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
3818     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
3819                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
3820
3821     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
3822                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
3823                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
3824     if (VT == MVT::f32) {
3825       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
3826       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
3827                         DAG.getConstant(0, MVT::i32));
3828     } else {
3829       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
3830     }
3831
3832     return Res;
3833   }
3834
3835   // Bitcast operand 1 to i32.
3836   if (SrcVT == MVT::f64)
3837     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3838                        Tmp1).getValue(1);
3839   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
3840
3841   // Or in the signbit with integer operations.
3842   SDValue Mask1 = DAG.getConstant(0x80000000, MVT::i32);
3843   SDValue Mask2 = DAG.getConstant(0x7fffffff, MVT::i32);
3844   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
3845   if (VT == MVT::f32) {
3846     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
3847                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
3848     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3849                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
3850   }
3851
3852   // f64: Or the high part with signbit and then combine two parts.
3853   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
3854                      Tmp0);
3855   SDValue Lo = Tmp0.getValue(0);
3856   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
3857   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
3858   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
3859 }
3860
3861 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
3862   MachineFunction &MF = DAG.getMachineFunction();
3863   MachineFrameInfo *MFI = MF.getFrameInfo();
3864   MFI->setReturnAddressIsTaken(true);
3865
3866   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
3867     return SDValue();
3868
3869   EVT VT = Op.getValueType();
3870   SDLoc dl(Op);
3871   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3872   if (Depth) {
3873     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3874     SDValue Offset = DAG.getConstant(4, MVT::i32);
3875     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
3876                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
3877                        MachinePointerInfo(), false, false, false, 0);
3878   }
3879
3880   // Return LR, which contains the return address. Mark it an implicit live-in.
3881   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3882   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
3883 }
3884
3885 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
3886   const ARMBaseRegisterInfo &ARI =
3887     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
3888   MachineFunction &MF = DAG.getMachineFunction();
3889   MachineFrameInfo *MFI = MF.getFrameInfo();
3890   MFI->setFrameAddressIsTaken(true);
3891
3892   EVT VT = Op.getValueType();
3893   SDLoc dl(Op);  // FIXME probably not meaningful
3894   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3895   unsigned FrameReg = ARI.getFrameRegister(MF);
3896   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
3897   while (Depth--)
3898     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
3899                             MachinePointerInfo(),
3900                             false, false, false, 0);
3901   return FrameAddr;
3902 }
3903
3904 // FIXME? Maybe this could be a TableGen attribute on some registers and
3905 // this table could be generated automatically from RegInfo.
3906 unsigned ARMTargetLowering::getRegisterByName(const char* RegName,
3907                                               EVT VT) const {
3908   unsigned Reg = StringSwitch<unsigned>(RegName)
3909                        .Case("sp", ARM::SP)
3910                        .Default(0);
3911   if (Reg)
3912     return Reg;
3913   report_fatal_error("Invalid register name global variable");
3914 }
3915
3916 /// ExpandBITCAST - If the target supports VFP, this function is called to
3917 /// expand a bit convert where either the source or destination type is i64 to
3918 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
3919 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
3920 /// vectors), since the legalizer won't know what to do with that.
3921 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
3922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3923   SDLoc dl(N);
3924   SDValue Op = N->getOperand(0);
3925
3926   // This function is only supposed to be called for i64 types, either as the
3927   // source or destination of the bit convert.
3928   EVT SrcVT = Op.getValueType();
3929   EVT DstVT = N->getValueType(0);
3930   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
3931          "ExpandBITCAST called for non-i64 type");
3932
3933   // Turn i64->f64 into VMOVDRR.
3934   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
3935     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3936                              DAG.getConstant(0, MVT::i32));
3937     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
3938                              DAG.getConstant(1, MVT::i32));
3939     return DAG.getNode(ISD::BITCAST, dl, DstVT,
3940                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
3941   }
3942
3943   // Turn f64->i64 into VMOVRRD.
3944   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
3945     SDValue Cvt;
3946     if (TLI.isBigEndian() && SrcVT.isVector() &&
3947         SrcVT.getVectorNumElements() > 1)
3948       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3949                         DAG.getVTList(MVT::i32, MVT::i32),
3950                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
3951     else
3952       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
3953                         DAG.getVTList(MVT::i32, MVT::i32), Op);
3954     // Merge the pieces into a single i64 value.
3955     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
3956   }
3957
3958   return SDValue();
3959 }
3960
3961 /// getZeroVector - Returns a vector of specified type with all zero elements.
3962 /// Zero vectors are used to represent vector negation and in those cases
3963 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
3964 /// not support i64 elements, so sometimes the zero vectors will need to be
3965 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
3966 /// zero vector.
3967 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
3968   assert(VT.isVector() && "Expected a vector type");
3969   // The canonical modified immediate encoding of a zero vector is....0!
3970   SDValue EncodedVal = DAG.getTargetConstant(0, MVT::i32);
3971   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
3972   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
3973   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
3974 }
3975
3976 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3977 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
3978 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
3979                                                 SelectionDAG &DAG) const {
3980   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3981   EVT VT = Op.getValueType();
3982   unsigned VTBits = VT.getSizeInBits();
3983   SDLoc dl(Op);
3984   SDValue ShOpLo = Op.getOperand(0);
3985   SDValue ShOpHi = Op.getOperand(1);
3986   SDValue ShAmt  = Op.getOperand(2);
3987   SDValue ARMcc;
3988   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3989
3990   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3991
3992   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
3993                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
3994   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3995   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
3996                                    DAG.getConstant(VTBits, MVT::i32));
3997   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3998   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3999   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4000
4001   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4002   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4003                           ARMcc, DAG, dl);
4004   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4005   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4006                            CCR, Cmp);
4007
4008   SDValue Ops[2] = { Lo, Hi };
4009   return DAG.getMergeValues(Ops, dl);
4010 }
4011
4012 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4013 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4014 SDValue ARMTargetLowering::LowerShiftLeftParts(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
4025   assert(Op.getOpcode() == ISD::SHL_PARTS);
4026   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4027                                  DAG.getConstant(VTBits, MVT::i32), ShAmt);
4028   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4029   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4030                                    DAG.getConstant(VTBits, MVT::i32));
4031   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4032   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4033
4034   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4035   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4036   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, MVT::i32), ISD::SETGE,
4037                           ARMcc, DAG, dl);
4038   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4039   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4040                            CCR, Cmp);
4041
4042   SDValue Ops[2] = { Lo, Hi };
4043   return DAG.getMergeValues(Ops, dl);
4044 }
4045
4046 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4047                                             SelectionDAG &DAG) const {
4048   // The rounding mode is in bits 23:22 of the FPSCR.
4049   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4050   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4051   // so that the shift + and get folded into a bitfield extract.
4052   SDLoc dl(Op);
4053   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4054                               DAG.getConstant(Intrinsic::arm_get_fpscr,
4055                                               MVT::i32));
4056   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4057                                   DAG.getConstant(1U << 22, MVT::i32));
4058   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4059                               DAG.getConstant(22, MVT::i32));
4060   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4061                      DAG.getConstant(3, MVT::i32));
4062 }
4063
4064 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4065                          const ARMSubtarget *ST) {
4066   EVT VT = N->getValueType(0);
4067   SDLoc dl(N);
4068
4069   if (!ST->hasV6T2Ops())
4070     return SDValue();
4071
4072   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4073   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4074 }
4075
4076 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4077 /// for each 16-bit element from operand, repeated.  The basic idea is to
4078 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4079 ///
4080 /// Trace for v4i16:
4081 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4082 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4083 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4084 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4085 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4086 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4087 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4088 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4089 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4090   EVT VT = N->getValueType(0);
4091   SDLoc DL(N);
4092
4093   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4094   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4095   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4096   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4097   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4098   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4099 }
4100
4101 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4102 /// bit-count for each 16-bit element from the operand.  We need slightly
4103 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4104 /// 64/128-bit registers.
4105 ///
4106 /// Trace for v4i16:
4107 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4108 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4109 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4110 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4111 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4112   EVT VT = N->getValueType(0);
4113   SDLoc DL(N);
4114
4115   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4116   if (VT.is64BitVector()) {
4117     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4118     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4119                        DAG.getIntPtrConstant(0));
4120   } else {
4121     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4122                                     BitCounts, DAG.getIntPtrConstant(0));
4123     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4124   }
4125 }
4126
4127 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4128 /// bit-count for each 32-bit element from the operand.  The idea here is
4129 /// to split the vector into 16-bit elements, leverage the 16-bit count
4130 /// routine, and then combine the results.
4131 ///
4132 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4133 /// input    = [v0    v1    ] (vi: 32-bit elements)
4134 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4135 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4136 /// vrev: N0 = [k1 k0 k3 k2 ]
4137 ///            [k0 k1 k2 k3 ]
4138 ///       N1 =+[k1 k0 k3 k2 ]
4139 ///            [k0 k2 k1 k3 ]
4140 ///       N2 =+[k1 k3 k0 k2 ]
4141 ///            [k0    k2    k1    k3    ]
4142 /// Extended =+[k1    k3    k0    k2    ]
4143 ///            [k0    k2    ]
4144 /// Extracted=+[k1    k3    ]
4145 ///
4146 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4147   EVT VT = N->getValueType(0);
4148   SDLoc DL(N);
4149
4150   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4151
4152   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4153   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4154   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4155   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4156   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4157
4158   if (VT.is64BitVector()) {
4159     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4160     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4161                        DAG.getIntPtrConstant(0));
4162   } else {
4163     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4164                                     DAG.getIntPtrConstant(0));
4165     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4166   }
4167 }
4168
4169 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4170                           const ARMSubtarget *ST) {
4171   EVT VT = N->getValueType(0);
4172
4173   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4174   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4175           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4176          "Unexpected type for custom ctpop lowering");
4177
4178   if (VT.getVectorElementType() == MVT::i32)
4179     return lowerCTPOP32BitElements(N, DAG);
4180   else
4181     return lowerCTPOP16BitElements(N, DAG);
4182 }
4183
4184 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4185                           const ARMSubtarget *ST) {
4186   EVT VT = N->getValueType(0);
4187   SDLoc dl(N);
4188
4189   if (!VT.isVector())
4190     return SDValue();
4191
4192   // Lower vector shifts on NEON to use VSHL.
4193   assert(ST->hasNEON() && "unexpected vector shift");
4194
4195   // Left shifts translate directly to the vshiftu intrinsic.
4196   if (N->getOpcode() == ISD::SHL)
4197     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4198                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, MVT::i32),
4199                        N->getOperand(0), N->getOperand(1));
4200
4201   assert((N->getOpcode() == ISD::SRA ||
4202           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4203
4204   // NEON uses the same intrinsics for both left and right shifts.  For
4205   // right shifts, the shift amounts are negative, so negate the vector of
4206   // shift amounts.
4207   EVT ShiftVT = N->getOperand(1).getValueType();
4208   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4209                                      getZeroVector(ShiftVT, DAG, dl),
4210                                      N->getOperand(1));
4211   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4212                              Intrinsic::arm_neon_vshifts :
4213                              Intrinsic::arm_neon_vshiftu);
4214   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4215                      DAG.getConstant(vshiftInt, MVT::i32),
4216                      N->getOperand(0), NegatedCount);
4217 }
4218
4219 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4220                                 const ARMSubtarget *ST) {
4221   EVT VT = N->getValueType(0);
4222   SDLoc dl(N);
4223
4224   // We can get here for a node like i32 = ISD::SHL i32, i64
4225   if (VT != MVT::i64)
4226     return SDValue();
4227
4228   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4229          "Unknown shift to lower!");
4230
4231   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4232   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4233       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4234     return SDValue();
4235
4236   // If we are in thumb mode, we don't have RRX.
4237   if (ST->isThumb1Only()) return SDValue();
4238
4239   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4240   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4241                            DAG.getConstant(0, MVT::i32));
4242   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4243                            DAG.getConstant(1, MVT::i32));
4244
4245   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4246   // captures the result into a carry flag.
4247   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4248   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4249
4250   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4251   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4252
4253   // Merge the pieces into a single i64 value.
4254  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4255 }
4256
4257 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4258   SDValue TmpOp0, TmpOp1;
4259   bool Invert = false;
4260   bool Swap = false;
4261   unsigned Opc = 0;
4262
4263   SDValue Op0 = Op.getOperand(0);
4264   SDValue Op1 = Op.getOperand(1);
4265   SDValue CC = Op.getOperand(2);
4266   EVT VT = Op.getValueType();
4267   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4268   SDLoc dl(Op);
4269
4270   if (Op.getOperand(1).getValueType().isFloatingPoint()) {
4271     switch (SetCCOpcode) {
4272     default: llvm_unreachable("Illegal FP comparison");
4273     case ISD::SETUNE:
4274     case ISD::SETNE:  Invert = true; // Fallthrough
4275     case ISD::SETOEQ:
4276     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4277     case ISD::SETOLT:
4278     case ISD::SETLT: Swap = true; // Fallthrough
4279     case ISD::SETOGT:
4280     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4281     case ISD::SETOLE:
4282     case ISD::SETLE:  Swap = true; // Fallthrough
4283     case ISD::SETOGE:
4284     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4285     case ISD::SETUGE: Swap = true; // Fallthrough
4286     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4287     case ISD::SETUGT: Swap = true; // Fallthrough
4288     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4289     case ISD::SETUEQ: Invert = true; // Fallthrough
4290     case ISD::SETONE:
4291       // Expand this to (OLT | OGT).
4292       TmpOp0 = Op0;
4293       TmpOp1 = Op1;
4294       Opc = ISD::OR;
4295       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4296       Op1 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp0, TmpOp1);
4297       break;
4298     case ISD::SETUO: Invert = true; // Fallthrough
4299     case ISD::SETO:
4300       // Expand this to (OLT | OGE).
4301       TmpOp0 = Op0;
4302       TmpOp1 = Op1;
4303       Opc = ISD::OR;
4304       Op0 = DAG.getNode(ARMISD::VCGT, dl, VT, TmpOp1, TmpOp0);
4305       Op1 = DAG.getNode(ARMISD::VCGE, dl, VT, TmpOp0, TmpOp1);
4306       break;
4307     }
4308   } else {
4309     // Integer comparisons.
4310     switch (SetCCOpcode) {
4311     default: llvm_unreachable("Illegal integer comparison");
4312     case ISD::SETNE:  Invert = true;
4313     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4314     case ISD::SETLT:  Swap = true;
4315     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4316     case ISD::SETLE:  Swap = true;
4317     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4318     case ISD::SETULT: Swap = true;
4319     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4320     case ISD::SETULE: Swap = true;
4321     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4322     }
4323
4324     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4325     if (Opc == ARMISD::VCEQ) {
4326
4327       SDValue AndOp;
4328       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4329         AndOp = Op0;
4330       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4331         AndOp = Op1;
4332
4333       // Ignore bitconvert.
4334       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4335         AndOp = AndOp.getOperand(0);
4336
4337       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4338         Opc = ARMISD::VTST;
4339         Op0 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(0));
4340         Op1 = DAG.getNode(ISD::BITCAST, dl, VT, AndOp.getOperand(1));
4341         Invert = !Invert;
4342       }
4343     }
4344   }
4345
4346   if (Swap)
4347     std::swap(Op0, Op1);
4348
4349   // If one of the operands is a constant vector zero, attempt to fold the
4350   // comparison to a specialized compare-against-zero form.
4351   SDValue SingleOp;
4352   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4353     SingleOp = Op0;
4354   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4355     if (Opc == ARMISD::VCGE)
4356       Opc = ARMISD::VCLEZ;
4357     else if (Opc == ARMISD::VCGT)
4358       Opc = ARMISD::VCLTZ;
4359     SingleOp = Op1;
4360   }
4361
4362   SDValue Result;
4363   if (SingleOp.getNode()) {
4364     switch (Opc) {
4365     case ARMISD::VCEQ:
4366       Result = DAG.getNode(ARMISD::VCEQZ, dl, VT, SingleOp); break;
4367     case ARMISD::VCGE:
4368       Result = DAG.getNode(ARMISD::VCGEZ, dl, VT, SingleOp); break;
4369     case ARMISD::VCLEZ:
4370       Result = DAG.getNode(ARMISD::VCLEZ, dl, VT, SingleOp); break;
4371     case ARMISD::VCGT:
4372       Result = DAG.getNode(ARMISD::VCGTZ, dl, VT, SingleOp); break;
4373     case ARMISD::VCLTZ:
4374       Result = DAG.getNode(ARMISD::VCLTZ, dl, VT, SingleOp); break;
4375     default:
4376       Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4377     }
4378   } else {
4379      Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
4380   }
4381
4382   if (Invert)
4383     Result = DAG.getNOT(dl, Result, VT);
4384
4385   return Result;
4386 }
4387
4388 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4389 /// valid vector constant for a NEON instruction with a "modified immediate"
4390 /// operand (e.g., VMOV).  If so, return the encoded value.
4391 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4392                                  unsigned SplatBitSize, SelectionDAG &DAG,
4393                                  EVT &VT, bool is128Bits, NEONModImmType type) {
4394   unsigned OpCmode, Imm;
4395
4396   // SplatBitSize is set to the smallest size that splats the vector, so a
4397   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4398   // immediate instructions others than VMOV do not support the 8-bit encoding
4399   // of a zero vector, and the default encoding of zero is supposed to be the
4400   // 32-bit version.
4401   if (SplatBits == 0)
4402     SplatBitSize = 32;
4403
4404   switch (SplatBitSize) {
4405   case 8:
4406     if (type != VMOVModImm)
4407       return SDValue();
4408     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4409     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4410     OpCmode = 0xe;
4411     Imm = SplatBits;
4412     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4413     break;
4414
4415   case 16:
4416     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4417     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4418     if ((SplatBits & ~0xff) == 0) {
4419       // Value = 0x00nn: Op=x, Cmode=100x.
4420       OpCmode = 0x8;
4421       Imm = SplatBits;
4422       break;
4423     }
4424     if ((SplatBits & ~0xff00) == 0) {
4425       // Value = 0xnn00: Op=x, Cmode=101x.
4426       OpCmode = 0xa;
4427       Imm = SplatBits >> 8;
4428       break;
4429     }
4430     return SDValue();
4431
4432   case 32:
4433     // NEON's 32-bit VMOV supports splat values where:
4434     // * only one byte is nonzero, or
4435     // * the least significant byte is 0xff and the second byte is nonzero, or
4436     // * the least significant 2 bytes are 0xff and the third is nonzero.
4437     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4438     if ((SplatBits & ~0xff) == 0) {
4439       // Value = 0x000000nn: Op=x, Cmode=000x.
4440       OpCmode = 0;
4441       Imm = SplatBits;
4442       break;
4443     }
4444     if ((SplatBits & ~0xff00) == 0) {
4445       // Value = 0x0000nn00: Op=x, Cmode=001x.
4446       OpCmode = 0x2;
4447       Imm = SplatBits >> 8;
4448       break;
4449     }
4450     if ((SplatBits & ~0xff0000) == 0) {
4451       // Value = 0x00nn0000: Op=x, Cmode=010x.
4452       OpCmode = 0x4;
4453       Imm = SplatBits >> 16;
4454       break;
4455     }
4456     if ((SplatBits & ~0xff000000) == 0) {
4457       // Value = 0xnn000000: Op=x, Cmode=011x.
4458       OpCmode = 0x6;
4459       Imm = SplatBits >> 24;
4460       break;
4461     }
4462
4463     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4464     if (type == OtherModImm) return SDValue();
4465
4466     if ((SplatBits & ~0xffff) == 0 &&
4467         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4468       // Value = 0x0000nnff: Op=x, Cmode=1100.
4469       OpCmode = 0xc;
4470       Imm = SplatBits >> 8;
4471       break;
4472     }
4473
4474     if ((SplatBits & ~0xffffff) == 0 &&
4475         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4476       // Value = 0x00nnffff: Op=x, Cmode=1101.
4477       OpCmode = 0xd;
4478       Imm = SplatBits >> 16;
4479       break;
4480     }
4481
4482     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4483     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4484     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4485     // and fall through here to test for a valid 64-bit splat.  But, then the
4486     // caller would also need to check and handle the change in size.
4487     return SDValue();
4488
4489   case 64: {
4490     if (type != VMOVModImm)
4491       return SDValue();
4492     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4493     uint64_t BitMask = 0xff;
4494     uint64_t Val = 0;
4495     unsigned ImmMask = 1;
4496     Imm = 0;
4497     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4498       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4499         Val |= BitMask;
4500         Imm |= ImmMask;
4501       } else if ((SplatBits & BitMask) != 0) {
4502         return SDValue();
4503       }
4504       BitMask <<= 8;
4505       ImmMask <<= 1;
4506     }
4507
4508     if (DAG.getTargetLoweringInfo().isBigEndian())
4509       // swap higher and lower 32 bit word
4510       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4511
4512     // Op=1, Cmode=1110.
4513     OpCmode = 0x1e;
4514     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4515     break;
4516   }
4517
4518   default:
4519     llvm_unreachable("unexpected size for isNEONModifiedImm");
4520   }
4521
4522   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4523   return DAG.getTargetConstant(EncodedVal, MVT::i32);
4524 }
4525
4526 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4527                                            const ARMSubtarget *ST) const {
4528   if (!ST->hasVFP3())
4529     return SDValue();
4530
4531   bool IsDouble = Op.getValueType() == MVT::f64;
4532   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4533
4534   // Try splatting with a VMOV.f32...
4535   APFloat FPVal = CFP->getValueAPF();
4536   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4537
4538   if (ImmVal != -1) {
4539     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4540       // We have code in place to select a valid ConstantFP already, no need to
4541       // do any mangling.
4542       return Op;
4543     }
4544
4545     // It's a float and we are trying to use NEON operations where
4546     // possible. Lower it to a splat followed by an extract.
4547     SDLoc DL(Op);
4548     SDValue NewVal = DAG.getTargetConstant(ImmVal, MVT::i32);
4549     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4550                                       NewVal);
4551     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4552                        DAG.getConstant(0, MVT::i32));
4553   }
4554
4555   // The rest of our options are NEON only, make sure that's allowed before
4556   // proceeding..
4557   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4558     return SDValue();
4559
4560   EVT VMovVT;
4561   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4562
4563   // It wouldn't really be worth bothering for doubles except for one very
4564   // important value, which does happen to match: 0.0. So make sure we don't do
4565   // anything stupid.
4566   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4567     return SDValue();
4568
4569   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4570   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4571                                      false, VMOVModImm);
4572   if (NewVal != SDValue()) {
4573     SDLoc DL(Op);
4574     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4575                                       NewVal);
4576     if (IsDouble)
4577       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4578
4579     // It's a float: cast and extract a vector element.
4580     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4581                                        VecConstant);
4582     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4583                        DAG.getConstant(0, MVT::i32));
4584   }
4585
4586   // Finally, try a VMVN.i32
4587   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, VMovVT,
4588                              false, VMVNModImm);
4589   if (NewVal != SDValue()) {
4590     SDLoc DL(Op);
4591     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4592
4593     if (IsDouble)
4594       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4595
4596     // It's a float: cast and extract a vector element.
4597     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4598                                        VecConstant);
4599     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4600                        DAG.getConstant(0, MVT::i32));
4601   }
4602
4603   return SDValue();
4604 }
4605
4606 // check if an VEXT instruction can handle the shuffle mask when the
4607 // vector sources of the shuffle are the same.
4608 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4609   unsigned NumElts = VT.getVectorNumElements();
4610
4611   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4612   if (M[0] < 0)
4613     return false;
4614
4615   Imm = M[0];
4616
4617   // If this is a VEXT shuffle, the immediate value is the index of the first
4618   // element.  The other shuffle indices must be the successive elements after
4619   // the first one.
4620   unsigned ExpectedElt = Imm;
4621   for (unsigned i = 1; i < NumElts; ++i) {
4622     // Increment the expected index.  If it wraps around, just follow it
4623     // back to index zero and keep going.
4624     ++ExpectedElt;
4625     if (ExpectedElt == NumElts)
4626       ExpectedElt = 0;
4627
4628     if (M[i] < 0) continue; // ignore UNDEF indices
4629     if (ExpectedElt != static_cast<unsigned>(M[i]))
4630       return false;
4631   }
4632
4633   return true;
4634 }
4635
4636
4637 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4638                        bool &ReverseVEXT, unsigned &Imm) {
4639   unsigned NumElts = VT.getVectorNumElements();
4640   ReverseVEXT = false;
4641
4642   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4643   if (M[0] < 0)
4644     return false;
4645
4646   Imm = M[0];
4647
4648   // If this is a VEXT shuffle, the immediate value is the index of the first
4649   // element.  The other shuffle indices must be the successive elements after
4650   // the first one.
4651   unsigned ExpectedElt = Imm;
4652   for (unsigned i = 1; i < NumElts; ++i) {
4653     // Increment the expected index.  If it wraps around, it may still be
4654     // a VEXT but the source vectors must be swapped.
4655     ExpectedElt += 1;
4656     if (ExpectedElt == NumElts * 2) {
4657       ExpectedElt = 0;
4658       ReverseVEXT = true;
4659     }
4660
4661     if (M[i] < 0) continue; // ignore UNDEF indices
4662     if (ExpectedElt != static_cast<unsigned>(M[i]))
4663       return false;
4664   }
4665
4666   // Adjust the index value if the source operands will be swapped.
4667   if (ReverseVEXT)
4668     Imm -= NumElts;
4669
4670   return true;
4671 }
4672
4673 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
4674 /// instruction with the specified blocksize.  (The order of the elements
4675 /// within each block of the vector is reversed.)
4676 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4677   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
4678          "Only possible block sizes for VREV are: 16, 32, 64");
4679
4680   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4681   if (EltSz == 64)
4682     return false;
4683
4684   unsigned NumElts = VT.getVectorNumElements();
4685   unsigned BlockElts = M[0] + 1;
4686   // If the first shuffle index is UNDEF, be optimistic.
4687   if (M[0] < 0)
4688     BlockElts = BlockSize / EltSz;
4689
4690   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4691     return false;
4692
4693   for (unsigned i = 0; i < NumElts; ++i) {
4694     if (M[i] < 0) continue; // ignore UNDEF indices
4695     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
4696       return false;
4697   }
4698
4699   return true;
4700 }
4701
4702 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
4703   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
4704   // range, then 0 is placed into the resulting vector. So pretty much any mask
4705   // of 8 elements can work here.
4706   return VT == MVT::v8i8 && M.size() == 8;
4707 }
4708
4709 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4710   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4711   if (EltSz == 64)
4712     return false;
4713
4714   unsigned NumElts = VT.getVectorNumElements();
4715   WhichResult = (M[0] == 0 ? 0 : 1);
4716   for (unsigned i = 0; i < NumElts; i += 2) {
4717     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4718         (M[i+1] >= 0 && (unsigned) M[i+1] != i + NumElts + WhichResult))
4719       return false;
4720   }
4721   return true;
4722 }
4723
4724 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
4725 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4726 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4727 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4728   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4729   if (EltSz == 64)
4730     return false;
4731
4732   unsigned NumElts = VT.getVectorNumElements();
4733   WhichResult = (M[0] == 0 ? 0 : 1);
4734   for (unsigned i = 0; i < NumElts; i += 2) {
4735     if ((M[i] >= 0 && (unsigned) M[i] != i + WhichResult) ||
4736         (M[i+1] >= 0 && (unsigned) M[i+1] != i + WhichResult))
4737       return false;
4738   }
4739   return true;
4740 }
4741
4742 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4743   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4744   if (EltSz == 64)
4745     return false;
4746
4747   unsigned NumElts = VT.getVectorNumElements();
4748   WhichResult = (M[0] == 0 ? 0 : 1);
4749   for (unsigned i = 0; i != NumElts; ++i) {
4750     if (M[i] < 0) continue; // ignore UNDEF indices
4751     if ((unsigned) M[i] != 2 * i + WhichResult)
4752       return false;
4753   }
4754
4755   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4756   if (VT.is64BitVector() && EltSz == 32)
4757     return false;
4758
4759   return true;
4760 }
4761
4762 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
4763 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4764 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4765 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4766   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4767   if (EltSz == 64)
4768     return false;
4769
4770   unsigned Half = VT.getVectorNumElements() / 2;
4771   WhichResult = (M[0] == 0 ? 0 : 1);
4772   for (unsigned j = 0; j != 2; ++j) {
4773     unsigned Idx = WhichResult;
4774     for (unsigned i = 0; i != Half; ++i) {
4775       int MIdx = M[i + j * Half];
4776       if (MIdx >= 0 && (unsigned) MIdx != Idx)
4777         return false;
4778       Idx += 2;
4779     }
4780   }
4781
4782   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4783   if (VT.is64BitVector() && EltSz == 32)
4784     return false;
4785
4786   return true;
4787 }
4788
4789 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4790   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4791   if (EltSz == 64)
4792     return false;
4793
4794   unsigned NumElts = VT.getVectorNumElements();
4795   WhichResult = (M[0] == 0 ? 0 : 1);
4796   unsigned Idx = WhichResult * NumElts / 2;
4797   for (unsigned i = 0; i != NumElts; i += 2) {
4798     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4799         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx + NumElts))
4800       return false;
4801     Idx += 1;
4802   }
4803
4804   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4805   if (VT.is64BitVector() && EltSz == 32)
4806     return false;
4807
4808   return true;
4809 }
4810
4811 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
4812 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4813 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4814 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
4815   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4816   if (EltSz == 64)
4817     return false;
4818
4819   unsigned NumElts = VT.getVectorNumElements();
4820   WhichResult = (M[0] == 0 ? 0 : 1);
4821   unsigned Idx = WhichResult * NumElts / 2;
4822   for (unsigned i = 0; i != NumElts; i += 2) {
4823     if ((M[i] >= 0 && (unsigned) M[i] != Idx) ||
4824         (M[i+1] >= 0 && (unsigned) M[i+1] != Idx))
4825       return false;
4826     Idx += 1;
4827   }
4828
4829   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
4830   if (VT.is64BitVector() && EltSz == 32)
4831     return false;
4832
4833   return true;
4834 }
4835
4836 /// \return true if this is a reverse operation on an vector.
4837 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
4838   unsigned NumElts = VT.getVectorNumElements();
4839   // Make sure the mask has the right size.
4840   if (NumElts != M.size())
4841       return false;
4842
4843   // Look for <15, ..., 3, -1, 1, 0>.
4844   for (unsigned i = 0; i != NumElts; ++i)
4845     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
4846       return false;
4847
4848   return true;
4849 }
4850
4851 // If N is an integer constant that can be moved into a register in one
4852 // instruction, return an SDValue of such a constant (will become a MOV
4853 // instruction).  Otherwise return null.
4854 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
4855                                      const ARMSubtarget *ST, SDLoc dl) {
4856   uint64_t Val;
4857   if (!isa<ConstantSDNode>(N))
4858     return SDValue();
4859   Val = cast<ConstantSDNode>(N)->getZExtValue();
4860
4861   if (ST->isThumb1Only()) {
4862     if (Val <= 255 || ~Val <= 255)
4863       return DAG.getConstant(Val, MVT::i32);
4864   } else {
4865     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
4866       return DAG.getConstant(Val, MVT::i32);
4867   }
4868   return SDValue();
4869 }
4870
4871 // If this is a case we can't handle, return null and let the default
4872 // expansion code take care of it.
4873 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
4874                                              const ARMSubtarget *ST) const {
4875   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4876   SDLoc dl(Op);
4877   EVT VT = Op.getValueType();
4878
4879   APInt SplatBits, SplatUndef;
4880   unsigned SplatBitSize;
4881   bool HasAnyUndefs;
4882   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4883     if (SplatBitSize <= 64) {
4884       // Check if an immediate VMOV works.
4885       EVT VmovVT;
4886       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
4887                                       SplatUndef.getZExtValue(), SplatBitSize,
4888                                       DAG, VmovVT, VT.is128BitVector(),
4889                                       VMOVModImm);
4890       if (Val.getNode()) {
4891         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
4892         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4893       }
4894
4895       // Try an immediate VMVN.
4896       uint64_t NegatedImm = (~SplatBits).getZExtValue();
4897       Val = isNEONModifiedImm(NegatedImm,
4898                                       SplatUndef.getZExtValue(), SplatBitSize,
4899                                       DAG, VmovVT, VT.is128BitVector(),
4900                                       VMVNModImm);
4901       if (Val.getNode()) {
4902         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
4903         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4904       }
4905
4906       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
4907       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
4908         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
4909         if (ImmVal != -1) {
4910           SDValue Val = DAG.getTargetConstant(ImmVal, MVT::i32);
4911           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
4912         }
4913       }
4914     }
4915   }
4916
4917   // Scan through the operands to see if only one value is used.
4918   //
4919   // As an optimisation, even if more than one value is used it may be more
4920   // profitable to splat with one value then change some lanes.
4921   //
4922   // Heuristically we decide to do this if the vector has a "dominant" value,
4923   // defined as splatted to more than half of the lanes.
4924   unsigned NumElts = VT.getVectorNumElements();
4925   bool isOnlyLowElement = true;
4926   bool usesOnlyOneValue = true;
4927   bool hasDominantValue = false;
4928   bool isConstant = true;
4929
4930   // Map of the number of times a particular SDValue appears in the
4931   // element list.
4932   DenseMap<SDValue, unsigned> ValueCounts;
4933   SDValue Value;
4934   for (unsigned i = 0; i < NumElts; ++i) {
4935     SDValue V = Op.getOperand(i);
4936     if (V.getOpcode() == ISD::UNDEF)
4937       continue;
4938     if (i > 0)
4939       isOnlyLowElement = false;
4940     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
4941       isConstant = false;
4942
4943     ValueCounts.insert(std::make_pair(V, 0));
4944     unsigned &Count = ValueCounts[V];
4945
4946     // Is this value dominant? (takes up more than half of the lanes)
4947     if (++Count > (NumElts / 2)) {
4948       hasDominantValue = true;
4949       Value = V;
4950     }
4951   }
4952   if (ValueCounts.size() != 1)
4953     usesOnlyOneValue = false;
4954   if (!Value.getNode() && ValueCounts.size() > 0)
4955     Value = ValueCounts.begin()->first;
4956
4957   if (ValueCounts.size() == 0)
4958     return DAG.getUNDEF(VT);
4959
4960   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
4961   // Keep going if we are hitting this case.
4962   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
4963     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
4964
4965   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4966
4967   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
4968   // i32 and try again.
4969   if (hasDominantValue && EltSize <= 32) {
4970     if (!isConstant) {
4971       SDValue N;
4972
4973       // If we are VDUPing a value that comes directly from a vector, that will
4974       // cause an unnecessary move to and from a GPR, where instead we could
4975       // just use VDUPLANE. We can only do this if the lane being extracted
4976       // is at a constant index, as the VDUP from lane instructions only have
4977       // constant-index forms.
4978       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
4979           isa<ConstantSDNode>(Value->getOperand(1))) {
4980         // We need to create a new undef vector to use for the VDUPLANE if the
4981         // size of the vector from which we get the value is different than the
4982         // size of the vector that we need to create. We will insert the element
4983         // such that the register coalescer will remove unnecessary copies.
4984         if (VT != Value->getOperand(0).getValueType()) {
4985           ConstantSDNode *constIndex;
4986           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
4987           assert(constIndex && "The index is not a constant!");
4988           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
4989                              VT.getVectorNumElements();
4990           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4991                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
4992                         Value, DAG.getConstant(index, MVT::i32)),
4993                            DAG.getConstant(index, MVT::i32));
4994         } else
4995           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
4996                         Value->getOperand(0), Value->getOperand(1));
4997       } else
4998         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
4999
5000       if (!usesOnlyOneValue) {
5001         // The dominant value was splatted as 'N', but we now have to insert
5002         // all differing elements.
5003         for (unsigned I = 0; I < NumElts; ++I) {
5004           if (Op.getOperand(I) == Value)
5005             continue;
5006           SmallVector<SDValue, 3> Ops;
5007           Ops.push_back(N);
5008           Ops.push_back(Op.getOperand(I));
5009           Ops.push_back(DAG.getConstant(I, MVT::i32));
5010           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5011         }
5012       }
5013       return N;
5014     }
5015     if (VT.getVectorElementType().isFloatingPoint()) {
5016       SmallVector<SDValue, 8> Ops;
5017       for (unsigned i = 0; i < NumElts; ++i)
5018         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5019                                   Op.getOperand(i)));
5020       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5021       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5022       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5023       if (Val.getNode())
5024         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5025     }
5026     if (usesOnlyOneValue) {
5027       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5028       if (isConstant && Val.getNode())
5029         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5030     }
5031   }
5032
5033   // If all elements are constants and the case above didn't get hit, fall back
5034   // to the default expansion, which will generate a load from the constant
5035   // pool.
5036   if (isConstant)
5037     return SDValue();
5038
5039   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5040   if (NumElts >= 4) {
5041     SDValue shuffle = ReconstructShuffle(Op, DAG);
5042     if (shuffle != SDValue())
5043       return shuffle;
5044   }
5045
5046   // Vectors with 32- or 64-bit elements can be built by directly assigning
5047   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5048   // will be legalized.
5049   if (EltSize >= 32) {
5050     // Do the expansion with floating-point types, since that is what the VFP
5051     // registers are defined to use, and since i64 is not legal.
5052     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5053     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5054     SmallVector<SDValue, 8> Ops;
5055     for (unsigned i = 0; i < NumElts; ++i)
5056       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5057     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5058     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5059   }
5060
5061   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5062   // know the default expansion would otherwise fall back on something even
5063   // worse. For a vector with one or two non-undef values, that's
5064   // scalar_to_vector for the elements followed by a shuffle (provided the
5065   // shuffle is valid for the target) and materialization element by element
5066   // on the stack followed by a load for everything else.
5067   if (!isConstant && !usesOnlyOneValue) {
5068     SDValue Vec = DAG.getUNDEF(VT);
5069     for (unsigned i = 0 ; i < NumElts; ++i) {
5070       SDValue V = Op.getOperand(i);
5071       if (V.getOpcode() == ISD::UNDEF)
5072         continue;
5073       SDValue LaneIdx = DAG.getConstant(i, MVT::i32);
5074       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5075     }
5076     return Vec;
5077   }
5078
5079   return SDValue();
5080 }
5081
5082 // Gather data to see if the operation can be modelled as a
5083 // shuffle in combination with VEXTs.
5084 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5085                                               SelectionDAG &DAG) const {
5086   SDLoc dl(Op);
5087   EVT VT = Op.getValueType();
5088   unsigned NumElts = VT.getVectorNumElements();
5089
5090   SmallVector<SDValue, 2> SourceVecs;
5091   SmallVector<unsigned, 2> MinElts;
5092   SmallVector<unsigned, 2> MaxElts;
5093
5094   for (unsigned i = 0; i < NumElts; ++i) {
5095     SDValue V = Op.getOperand(i);
5096     if (V.getOpcode() == ISD::UNDEF)
5097       continue;
5098     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5099       // A shuffle can only come from building a vector from various
5100       // elements of other vectors.
5101       return SDValue();
5102     } else if (V.getOperand(0).getValueType().getVectorElementType() !=
5103                VT.getVectorElementType()) {
5104       // This code doesn't know how to handle shuffles where the vector
5105       // element types do not match (this happens because type legalization
5106       // promotes the return type of EXTRACT_VECTOR_ELT).
5107       // FIXME: It might be appropriate to extend this code to handle
5108       // mismatched types.
5109       return SDValue();
5110     }
5111
5112     // Record this extraction against the appropriate vector if possible...
5113     SDValue SourceVec = V.getOperand(0);
5114     // If the element number isn't a constant, we can't effectively
5115     // analyze what's going on.
5116     if (!isa<ConstantSDNode>(V.getOperand(1)))
5117       return SDValue();
5118     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5119     bool FoundSource = false;
5120     for (unsigned j = 0; j < SourceVecs.size(); ++j) {
5121       if (SourceVecs[j] == SourceVec) {
5122         if (MinElts[j] > EltNo)
5123           MinElts[j] = EltNo;
5124         if (MaxElts[j] < EltNo)
5125           MaxElts[j] = EltNo;
5126         FoundSource = true;
5127         break;
5128       }
5129     }
5130
5131     // Or record a new source if not...
5132     if (!FoundSource) {
5133       SourceVecs.push_back(SourceVec);
5134       MinElts.push_back(EltNo);
5135       MaxElts.push_back(EltNo);
5136     }
5137   }
5138
5139   // Currently only do something sane when at most two source vectors
5140   // involved.
5141   if (SourceVecs.size() > 2)
5142     return SDValue();
5143
5144   SDValue ShuffleSrcs[2] = {DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
5145   int VEXTOffsets[2] = {0, 0};
5146
5147   // This loop extracts the usage patterns of the source vectors
5148   // and prepares appropriate SDValues for a shuffle if possible.
5149   for (unsigned i = 0; i < SourceVecs.size(); ++i) {
5150     if (SourceVecs[i].getValueType() == VT) {
5151       // No VEXT necessary
5152       ShuffleSrcs[i] = SourceVecs[i];
5153       VEXTOffsets[i] = 0;
5154       continue;
5155     } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
5156       // It probably isn't worth padding out a smaller vector just to
5157       // break it down again in a shuffle.
5158       return SDValue();
5159     }
5160
5161     // Since only 64-bit and 128-bit vectors are legal on ARM and
5162     // we've eliminated the other cases...
5163     assert(SourceVecs[i].getValueType().getVectorNumElements() == 2*NumElts &&
5164            "unexpected vector sizes in ReconstructShuffle");
5165
5166     if (MaxElts[i] - MinElts[i] >= NumElts) {
5167       // Span too large for a VEXT to cope
5168       return SDValue();
5169     }
5170
5171     if (MinElts[i] >= NumElts) {
5172       // The extraction can just take the second half
5173       VEXTOffsets[i] = NumElts;
5174       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5175                                    SourceVecs[i],
5176                                    DAG.getIntPtrConstant(NumElts));
5177     } else if (MaxElts[i] < NumElts) {
5178       // The extraction can just take the first half
5179       VEXTOffsets[i] = 0;
5180       ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5181                                    SourceVecs[i],
5182                                    DAG.getIntPtrConstant(0));
5183     } else {
5184       // An actual VEXT is needed
5185       VEXTOffsets[i] = MinElts[i];
5186       SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5187                                      SourceVecs[i],
5188                                      DAG.getIntPtrConstant(0));
5189       SDValue VEXTSrc2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
5190                                      SourceVecs[i],
5191                                      DAG.getIntPtrConstant(NumElts));
5192       ShuffleSrcs[i] = DAG.getNode(ARMISD::VEXT, dl, VT, VEXTSrc1, VEXTSrc2,
5193                                    DAG.getConstant(VEXTOffsets[i], MVT::i32));
5194     }
5195   }
5196
5197   SmallVector<int, 8> Mask;
5198
5199   for (unsigned i = 0; i < NumElts; ++i) {
5200     SDValue Entry = Op.getOperand(i);
5201     if (Entry.getOpcode() == ISD::UNDEF) {
5202       Mask.push_back(-1);
5203       continue;
5204     }
5205
5206     SDValue ExtractVec = Entry.getOperand(0);
5207     int ExtractElt = cast<ConstantSDNode>(Op.getOperand(i)
5208                                           .getOperand(1))->getSExtValue();
5209     if (ExtractVec == SourceVecs[0]) {
5210       Mask.push_back(ExtractElt - VEXTOffsets[0]);
5211     } else {
5212       Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
5213     }
5214   }
5215
5216   // Final check before we try to produce nonsense...
5217   if (isShuffleMaskLegal(Mask, VT))
5218     return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
5219                                 &Mask[0]);
5220
5221   return SDValue();
5222 }
5223
5224 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5225 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5226 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5227 /// are assumed to be legal.
5228 bool
5229 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5230                                       EVT VT) const {
5231   if (VT.getVectorNumElements() == 4 &&
5232       (VT.is128BitVector() || VT.is64BitVector())) {
5233     unsigned PFIndexes[4];
5234     for (unsigned i = 0; i != 4; ++i) {
5235       if (M[i] < 0)
5236         PFIndexes[i] = 8;
5237       else
5238         PFIndexes[i] = M[i];
5239     }
5240
5241     // Compute the index in the perfect shuffle table.
5242     unsigned PFTableIndex =
5243       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5244     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5245     unsigned Cost = (PFEntry >> 30);
5246
5247     if (Cost <= 4)
5248       return true;
5249   }
5250
5251   bool ReverseVEXT;
5252   unsigned Imm, WhichResult;
5253
5254   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5255   return (EltSize >= 32 ||
5256           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5257           isVREVMask(M, VT, 64) ||
5258           isVREVMask(M, VT, 32) ||
5259           isVREVMask(M, VT, 16) ||
5260           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5261           isVTBLMask(M, VT) ||
5262           isVTRNMask(M, VT, WhichResult) ||
5263           isVUZPMask(M, VT, WhichResult) ||
5264           isVZIPMask(M, VT, WhichResult) ||
5265           isVTRN_v_undef_Mask(M, VT, WhichResult) ||
5266           isVUZP_v_undef_Mask(M, VT, WhichResult) ||
5267           isVZIP_v_undef_Mask(M, VT, WhichResult) ||
5268           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5269 }
5270
5271 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5272 /// the specified operations to build the shuffle.
5273 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5274                                       SDValue RHS, SelectionDAG &DAG,
5275                                       SDLoc dl) {
5276   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5277   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5278   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5279
5280   enum {
5281     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5282     OP_VREV,
5283     OP_VDUP0,
5284     OP_VDUP1,
5285     OP_VDUP2,
5286     OP_VDUP3,
5287     OP_VEXT1,
5288     OP_VEXT2,
5289     OP_VEXT3,
5290     OP_VUZPL, // VUZP, left result
5291     OP_VUZPR, // VUZP, right result
5292     OP_VZIPL, // VZIP, left result
5293     OP_VZIPR, // VZIP, right result
5294     OP_VTRNL, // VTRN, left result
5295     OP_VTRNR  // VTRN, right result
5296   };
5297
5298   if (OpNum == OP_COPY) {
5299     if (LHSID == (1*9+2)*9+3) return LHS;
5300     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5301     return RHS;
5302   }
5303
5304   SDValue OpLHS, OpRHS;
5305   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5306   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5307   EVT VT = OpLHS.getValueType();
5308
5309   switch (OpNum) {
5310   default: llvm_unreachable("Unknown shuffle opcode!");
5311   case OP_VREV:
5312     // VREV divides the vector in half and swaps within the half.
5313     if (VT.getVectorElementType() == MVT::i32 ||
5314         VT.getVectorElementType() == MVT::f32)
5315       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5316     // vrev <4 x i16> -> VREV32
5317     if (VT.getVectorElementType() == MVT::i16)
5318       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5319     // vrev <4 x i8> -> VREV16
5320     assert(VT.getVectorElementType() == MVT::i8);
5321     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5322   case OP_VDUP0:
5323   case OP_VDUP1:
5324   case OP_VDUP2:
5325   case OP_VDUP3:
5326     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5327                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, MVT::i32));
5328   case OP_VEXT1:
5329   case OP_VEXT2:
5330   case OP_VEXT3:
5331     return DAG.getNode(ARMISD::VEXT, dl, VT,
5332                        OpLHS, OpRHS,
5333                        DAG.getConstant(OpNum-OP_VEXT1+1, MVT::i32));
5334   case OP_VUZPL:
5335   case OP_VUZPR:
5336     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5337                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5338   case OP_VZIPL:
5339   case OP_VZIPR:
5340     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5341                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5342   case OP_VTRNL:
5343   case OP_VTRNR:
5344     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5345                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5346   }
5347 }
5348
5349 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5350                                        ArrayRef<int> ShuffleMask,
5351                                        SelectionDAG &DAG) {
5352   // Check to see if we can use the VTBL instruction.
5353   SDValue V1 = Op.getOperand(0);
5354   SDValue V2 = Op.getOperand(1);
5355   SDLoc DL(Op);
5356
5357   SmallVector<SDValue, 8> VTBLMask;
5358   for (ArrayRef<int>::iterator
5359          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5360     VTBLMask.push_back(DAG.getConstant(*I, MVT::i32));
5361
5362   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5363     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5364                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5365
5366   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5367                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5368 }
5369
5370 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5371                                                       SelectionDAG &DAG) {
5372   SDLoc DL(Op);
5373   SDValue OpLHS = Op.getOperand(0);
5374   EVT VT = OpLHS.getValueType();
5375
5376   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5377          "Expect an v8i16/v16i8 type");
5378   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5379   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5380   // extract the first 8 bytes into the top double word and the last 8 bytes
5381   // into the bottom double word. The v8i16 case is similar.
5382   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5383   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5384                      DAG.getConstant(ExtractNum, MVT::i32));
5385 }
5386
5387 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5388   SDValue V1 = Op.getOperand(0);
5389   SDValue V2 = Op.getOperand(1);
5390   SDLoc dl(Op);
5391   EVT VT = Op.getValueType();
5392   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5393
5394   // Convert shuffles that are directly supported on NEON to target-specific
5395   // DAG nodes, instead of keeping them as shuffles and matching them again
5396   // during code selection.  This is more efficient and avoids the possibility
5397   // of inconsistencies between legalization and selection.
5398   // FIXME: floating-point vectors should be canonicalized to integer vectors
5399   // of the same time so that they get CSEd properly.
5400   ArrayRef<int> ShuffleMask = SVN->getMask();
5401
5402   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5403   if (EltSize <= 32) {
5404     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5405       int Lane = SVN->getSplatIndex();
5406       // If this is undef splat, generate it via "just" vdup, if possible.
5407       if (Lane == -1) Lane = 0;
5408
5409       // Test if V1 is a SCALAR_TO_VECTOR.
5410       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5411         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5412       }
5413       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5414       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5415       // reaches it).
5416       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5417           !isa<ConstantSDNode>(V1.getOperand(0))) {
5418         bool IsScalarToVector = true;
5419         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5420           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5421             IsScalarToVector = false;
5422             break;
5423           }
5424         if (IsScalarToVector)
5425           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5426       }
5427       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5428                          DAG.getConstant(Lane, MVT::i32));
5429     }
5430
5431     bool ReverseVEXT;
5432     unsigned Imm;
5433     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5434       if (ReverseVEXT)
5435         std::swap(V1, V2);
5436       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5437                          DAG.getConstant(Imm, MVT::i32));
5438     }
5439
5440     if (isVREVMask(ShuffleMask, VT, 64))
5441       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5442     if (isVREVMask(ShuffleMask, VT, 32))
5443       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5444     if (isVREVMask(ShuffleMask, VT, 16))
5445       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5446
5447     if (V2->getOpcode() == ISD::UNDEF &&
5448         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5449       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5450                          DAG.getConstant(Imm, MVT::i32));
5451     }
5452
5453     // Check for Neon shuffles that modify both input vectors in place.
5454     // If both results are used, i.e., if there are two shuffles with the same
5455     // source operands and with masks corresponding to both results of one of
5456     // these operations, DAG memoization will ensure that a single node is
5457     // used for both shuffles.
5458     unsigned WhichResult;
5459     if (isVTRNMask(ShuffleMask, VT, WhichResult))
5460       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5461                          V1, V2).getValue(WhichResult);
5462     if (isVUZPMask(ShuffleMask, VT, WhichResult))
5463       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5464                          V1, V2).getValue(WhichResult);
5465     if (isVZIPMask(ShuffleMask, VT, WhichResult))
5466       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5467                          V1, V2).getValue(WhichResult);
5468
5469     if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5470       return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5471                          V1, V1).getValue(WhichResult);
5472     if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5473       return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5474                          V1, V1).getValue(WhichResult);
5475     if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5476       return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5477                          V1, V1).getValue(WhichResult);
5478   }
5479
5480   // If the shuffle is not directly supported and it has 4 elements, use
5481   // the PerfectShuffle-generated table to synthesize it from other shuffles.
5482   unsigned NumElts = VT.getVectorNumElements();
5483   if (NumElts == 4) {
5484     unsigned PFIndexes[4];
5485     for (unsigned i = 0; i != 4; ++i) {
5486       if (ShuffleMask[i] < 0)
5487         PFIndexes[i] = 8;
5488       else
5489         PFIndexes[i] = ShuffleMask[i];
5490     }
5491
5492     // Compute the index in the perfect shuffle table.
5493     unsigned PFTableIndex =
5494       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5495     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5496     unsigned Cost = (PFEntry >> 30);
5497
5498     if (Cost <= 4)
5499       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5500   }
5501
5502   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
5503   if (EltSize >= 32) {
5504     // Do the expansion with floating-point types, since that is what the VFP
5505     // registers are defined to use, and since i64 is not legal.
5506     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5507     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5508     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
5509     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
5510     SmallVector<SDValue, 8> Ops;
5511     for (unsigned i = 0; i < NumElts; ++i) {
5512       if (ShuffleMask[i] < 0)
5513         Ops.push_back(DAG.getUNDEF(EltVT));
5514       else
5515         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
5516                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
5517                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
5518                                                   MVT::i32)));
5519     }
5520     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5521     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5522   }
5523
5524   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
5525     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
5526
5527   if (VT == MVT::v8i8) {
5528     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
5529     if (NewOp.getNode())
5530       return NewOp;
5531   }
5532
5533   return SDValue();
5534 }
5535
5536 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5537   // INSERT_VECTOR_ELT is legal only for immediate indexes.
5538   SDValue Lane = Op.getOperand(2);
5539   if (!isa<ConstantSDNode>(Lane))
5540     return SDValue();
5541
5542   return Op;
5543 }
5544
5545 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
5546   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
5547   SDValue Lane = Op.getOperand(1);
5548   if (!isa<ConstantSDNode>(Lane))
5549     return SDValue();
5550
5551   SDValue Vec = Op.getOperand(0);
5552   if (Op.getValueType() == MVT::i32 &&
5553       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
5554     SDLoc dl(Op);
5555     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
5556   }
5557
5558   return Op;
5559 }
5560
5561 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
5562   // The only time a CONCAT_VECTORS operation can have legal types is when
5563   // two 64-bit vectors are concatenated to a 128-bit vector.
5564   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
5565          "unexpected CONCAT_VECTORS");
5566   SDLoc dl(Op);
5567   SDValue Val = DAG.getUNDEF(MVT::v2f64);
5568   SDValue Op0 = Op.getOperand(0);
5569   SDValue Op1 = Op.getOperand(1);
5570   if (Op0.getOpcode() != ISD::UNDEF)
5571     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5572                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
5573                       DAG.getIntPtrConstant(0));
5574   if (Op1.getOpcode() != ISD::UNDEF)
5575     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
5576                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
5577                       DAG.getIntPtrConstant(1));
5578   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
5579 }
5580
5581 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
5582 /// element has been zero/sign-extended, depending on the isSigned parameter,
5583 /// from an integer type half its size.
5584 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
5585                                    bool isSigned) {
5586   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
5587   EVT VT = N->getValueType(0);
5588   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
5589     SDNode *BVN = N->getOperand(0).getNode();
5590     if (BVN->getValueType(0) != MVT::v4i32 ||
5591         BVN->getOpcode() != ISD::BUILD_VECTOR)
5592       return false;
5593     unsigned LoElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5594     unsigned HiElt = 1 - LoElt;
5595     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
5596     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
5597     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
5598     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
5599     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
5600       return false;
5601     if (isSigned) {
5602       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
5603           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
5604         return true;
5605     } else {
5606       if (Hi0->isNullValue() && Hi1->isNullValue())
5607         return true;
5608     }
5609     return false;
5610   }
5611
5612   if (N->getOpcode() != ISD::BUILD_VECTOR)
5613     return false;
5614
5615   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5616     SDNode *Elt = N->getOperand(i).getNode();
5617     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
5618       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5619       unsigned HalfSize = EltSize / 2;
5620       if (isSigned) {
5621         if (!isIntN(HalfSize, C->getSExtValue()))
5622           return false;
5623       } else {
5624         if (!isUIntN(HalfSize, C->getZExtValue()))
5625           return false;
5626       }
5627       continue;
5628     }
5629     return false;
5630   }
5631
5632   return true;
5633 }
5634
5635 /// isSignExtended - Check if a node is a vector value that is sign-extended
5636 /// or a constant BUILD_VECTOR with sign-extended elements.
5637 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
5638   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
5639     return true;
5640   if (isExtendedBUILD_VECTOR(N, DAG, true))
5641     return true;
5642   return false;
5643 }
5644
5645 /// isZeroExtended - Check if a node is a vector value that is zero-extended
5646 /// or a constant BUILD_VECTOR with zero-extended elements.
5647 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
5648   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
5649     return true;
5650   if (isExtendedBUILD_VECTOR(N, DAG, false))
5651     return true;
5652   return false;
5653 }
5654
5655 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
5656   if (OrigVT.getSizeInBits() >= 64)
5657     return OrigVT;
5658
5659   assert(OrigVT.isSimple() && "Expecting a simple value type");
5660
5661   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
5662   switch (OrigSimpleTy) {
5663   default: llvm_unreachable("Unexpected Vector Type");
5664   case MVT::v2i8:
5665   case MVT::v2i16:
5666      return MVT::v2i32;
5667   case MVT::v4i8:
5668     return  MVT::v4i16;
5669   }
5670 }
5671
5672 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
5673 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
5674 /// We insert the required extension here to get the vector to fill a D register.
5675 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
5676                                             const EVT &OrigTy,
5677                                             const EVT &ExtTy,
5678                                             unsigned ExtOpcode) {
5679   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
5680   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
5681   // 64-bits we need to insert a new extension so that it will be 64-bits.
5682   assert(ExtTy.is128BitVector() && "Unexpected extension size");
5683   if (OrigTy.getSizeInBits() >= 64)
5684     return N;
5685
5686   // Must extend size to at least 64 bits to be used as an operand for VMULL.
5687   EVT NewVT = getExtensionTo64Bits(OrigTy);
5688
5689   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
5690 }
5691
5692 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
5693 /// does not do any sign/zero extension. If the original vector is less
5694 /// than 64 bits, an appropriate extension will be added after the load to
5695 /// reach a total size of 64 bits. We have to add the extension separately
5696 /// because ARM does not have a sign/zero extending load for vectors.
5697 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
5698   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
5699
5700   // The load already has the right type.
5701   if (ExtendedTy == LD->getMemoryVT())
5702     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
5703                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
5704                 LD->isNonTemporal(), LD->isInvariant(),
5705                 LD->getAlignment());
5706
5707   // We need to create a zextload/sextload. We cannot just create a load
5708   // followed by a zext/zext node because LowerMUL is also run during normal
5709   // operation legalization where we can't create illegal types.
5710   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
5711                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
5712                         LD->getMemoryVT(), LD->isVolatile(),
5713                         LD->isNonTemporal(), LD->getAlignment());
5714 }
5715
5716 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
5717 /// extending load, or BUILD_VECTOR with extended elements, return the
5718 /// unextended value. The unextended vector should be 64 bits so that it can
5719 /// be used as an operand to a VMULL instruction. If the original vector size
5720 /// before extension is less than 64 bits we add a an extension to resize
5721 /// the vector to 64 bits.
5722 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
5723   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
5724     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
5725                                         N->getOperand(0)->getValueType(0),
5726                                         N->getValueType(0),
5727                                         N->getOpcode());
5728
5729   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
5730     return SkipLoadExtensionForVMULL(LD, DAG);
5731
5732   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
5733   // have been legalized as a BITCAST from v4i32.
5734   if (N->getOpcode() == ISD::BITCAST) {
5735     SDNode *BVN = N->getOperand(0).getNode();
5736     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
5737            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
5738     unsigned LowElt = DAG.getTargetLoweringInfo().isBigEndian() ? 1 : 0;
5739     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
5740                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
5741   }
5742   // Construct a new BUILD_VECTOR with elements truncated to half the size.
5743   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
5744   EVT VT = N->getValueType(0);
5745   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
5746   unsigned NumElts = VT.getVectorNumElements();
5747   MVT TruncVT = MVT::getIntegerVT(EltSize);
5748   SmallVector<SDValue, 8> Ops;
5749   for (unsigned i = 0; i != NumElts; ++i) {
5750     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
5751     const APInt &CInt = C->getAPIntValue();
5752     // Element types smaller than 32 bits are not legal, so use i32 elements.
5753     // The values are implicitly truncated so sext vs. zext doesn't matter.
5754     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
5755   }
5756   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
5757                      MVT::getVectorVT(TruncVT, NumElts), Ops);
5758 }
5759
5760 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
5761   unsigned Opcode = N->getOpcode();
5762   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5763     SDNode *N0 = N->getOperand(0).getNode();
5764     SDNode *N1 = N->getOperand(1).getNode();
5765     return N0->hasOneUse() && N1->hasOneUse() &&
5766       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
5767   }
5768   return false;
5769 }
5770
5771 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
5772   unsigned Opcode = N->getOpcode();
5773   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
5774     SDNode *N0 = N->getOperand(0).getNode();
5775     SDNode *N1 = N->getOperand(1).getNode();
5776     return N0->hasOneUse() && N1->hasOneUse() &&
5777       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
5778   }
5779   return false;
5780 }
5781
5782 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
5783   // Multiplications are only custom-lowered for 128-bit vectors so that
5784   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
5785   EVT VT = Op.getValueType();
5786   assert(VT.is128BitVector() && VT.isInteger() &&
5787          "unexpected type for custom-lowering ISD::MUL");
5788   SDNode *N0 = Op.getOperand(0).getNode();
5789   SDNode *N1 = Op.getOperand(1).getNode();
5790   unsigned NewOpc = 0;
5791   bool isMLA = false;
5792   bool isN0SExt = isSignExtended(N0, DAG);
5793   bool isN1SExt = isSignExtended(N1, DAG);
5794   if (isN0SExt && isN1SExt)
5795     NewOpc = ARMISD::VMULLs;
5796   else {
5797     bool isN0ZExt = isZeroExtended(N0, DAG);
5798     bool isN1ZExt = isZeroExtended(N1, DAG);
5799     if (isN0ZExt && isN1ZExt)
5800       NewOpc = ARMISD::VMULLu;
5801     else if (isN1SExt || isN1ZExt) {
5802       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
5803       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
5804       if (isN1SExt && isAddSubSExt(N0, DAG)) {
5805         NewOpc = ARMISD::VMULLs;
5806         isMLA = true;
5807       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
5808         NewOpc = ARMISD::VMULLu;
5809         isMLA = true;
5810       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
5811         std::swap(N0, N1);
5812         NewOpc = ARMISD::VMULLu;
5813         isMLA = true;
5814       }
5815     }
5816
5817     if (!NewOpc) {
5818       if (VT == MVT::v2i64)
5819         // Fall through to expand this.  It is not legal.
5820         return SDValue();
5821       else
5822         // Other vector multiplications are legal.
5823         return Op;
5824     }
5825   }
5826
5827   // Legalize to a VMULL instruction.
5828   SDLoc DL(Op);
5829   SDValue Op0;
5830   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
5831   if (!isMLA) {
5832     Op0 = SkipExtensionForVMULL(N0, DAG);
5833     assert(Op0.getValueType().is64BitVector() &&
5834            Op1.getValueType().is64BitVector() &&
5835            "unexpected types for extended operands to VMULL");
5836     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
5837   }
5838
5839   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
5840   // isel lowering to take advantage of no-stall back to back vmul + vmla.
5841   //   vmull q0, d4, d6
5842   //   vmlal q0, d5, d6
5843   // is faster than
5844   //   vaddl q0, d4, d5
5845   //   vmovl q1, d6
5846   //   vmul  q0, q0, q1
5847   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
5848   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
5849   EVT Op1VT = Op1.getValueType();
5850   return DAG.getNode(N0->getOpcode(), DL, VT,
5851                      DAG.getNode(NewOpc, DL, VT,
5852                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
5853                      DAG.getNode(NewOpc, DL, VT,
5854                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
5855 }
5856
5857 static SDValue
5858 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
5859   // Convert to float
5860   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
5861   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
5862   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
5863   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
5864   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
5865   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
5866   // Get reciprocal estimate.
5867   // float4 recip = vrecpeq_f32(yf);
5868   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5869                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), Y);
5870   // Because char has a smaller range than uchar, we can actually get away
5871   // without any newton steps.  This requires that we use a weird bias
5872   // of 0xb000, however (again, this has been exhaustively tested).
5873   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
5874   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
5875   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
5876   Y = DAG.getConstant(0xb000, MVT::i32);
5877   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
5878   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
5879   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
5880   // Convert back to short.
5881   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
5882   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
5883   return X;
5884 }
5885
5886 static SDValue
5887 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
5888   SDValue N2;
5889   // Convert to float.
5890   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
5891   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
5892   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
5893   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
5894   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5895   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
5896
5897   // Use reciprocal estimate and one refinement step.
5898   // float4 recip = vrecpeq_f32(yf);
5899   // recip *= vrecpsq_f32(yf, recip);
5900   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5901                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), N1);
5902   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
5903                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
5904                    N1, N2);
5905   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
5906   // Because short has a smaller range than ushort, we can actually get away
5907   // with only a single newton step.  This requires that we use a weird bias
5908   // of 89, however (again, this has been exhaustively tested).
5909   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
5910   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
5911   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
5912   N1 = DAG.getConstant(0x89, MVT::i32);
5913   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
5914   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
5915   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
5916   // Convert back to integer and return.
5917   // return vmovn_s32(vcvt_s32_f32(result));
5918   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
5919   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
5920   return N0;
5921 }
5922
5923 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
5924   EVT VT = Op.getValueType();
5925   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5926          "unexpected type for custom-lowering ISD::SDIV");
5927
5928   SDLoc dl(Op);
5929   SDValue N0 = Op.getOperand(0);
5930   SDValue N1 = Op.getOperand(1);
5931   SDValue N2, N3;
5932
5933   if (VT == MVT::v8i8) {
5934     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
5935     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
5936
5937     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5938                      DAG.getIntPtrConstant(4));
5939     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5940                      DAG.getIntPtrConstant(4));
5941     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5942                      DAG.getIntPtrConstant(0));
5943     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5944                      DAG.getIntPtrConstant(0));
5945
5946     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
5947     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
5948
5949     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5950     N0 = LowerCONCAT_VECTORS(N0, DAG);
5951
5952     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
5953     return N0;
5954   }
5955   return LowerSDIV_v4i16(N0, N1, dl, DAG);
5956 }
5957
5958 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
5959   EVT VT = Op.getValueType();
5960   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
5961          "unexpected type for custom-lowering ISD::UDIV");
5962
5963   SDLoc dl(Op);
5964   SDValue N0 = Op.getOperand(0);
5965   SDValue N1 = Op.getOperand(1);
5966   SDValue N2, N3;
5967
5968   if (VT == MVT::v8i8) {
5969     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
5970     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
5971
5972     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5973                      DAG.getIntPtrConstant(4));
5974     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5975                      DAG.getIntPtrConstant(4));
5976     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
5977                      DAG.getIntPtrConstant(0));
5978     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
5979                      DAG.getIntPtrConstant(0));
5980
5981     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
5982     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
5983
5984     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
5985     N0 = LowerCONCAT_VECTORS(N0, DAG);
5986
5987     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
5988                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, MVT::i32),
5989                      N0);
5990     return N0;
5991   }
5992
5993   // v4i16 sdiv ... Convert to float.
5994   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
5995   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
5996   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
5997   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
5998   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
5999   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6000
6001   // Use reciprocal estimate and two refinement steps.
6002   // float4 recip = vrecpeq_f32(yf);
6003   // recip *= vrecpsq_f32(yf, recip);
6004   // recip *= vrecpsq_f32(yf, recip);
6005   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6006                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, MVT::i32), BN1);
6007   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6008                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6009                    BN1, N2);
6010   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6011   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6012                    DAG.getConstant(Intrinsic::arm_neon_vrecps, MVT::i32),
6013                    BN1, N2);
6014   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6015   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6016   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6017   // and that it will never cause us to return an answer too large).
6018   // float4 result = as_float4(as_int4(xf*recip) + 2);
6019   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6020   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6021   N1 = DAG.getConstant(2, MVT::i32);
6022   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6023   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6024   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6025   // Convert back to integer and return.
6026   // return vmovn_u32(vcvt_s32_f32(result));
6027   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6028   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6029   return N0;
6030 }
6031
6032 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6033   EVT VT = Op.getNode()->getValueType(0);
6034   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6035
6036   unsigned Opc;
6037   bool ExtraOp = false;
6038   switch (Op.getOpcode()) {
6039   default: llvm_unreachable("Invalid code");
6040   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6041   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6042   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6043   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6044   }
6045
6046   if (!ExtraOp)
6047     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6048                        Op.getOperand(1));
6049   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6050                      Op.getOperand(1), Op.getOperand(2));
6051 }
6052
6053 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6054   assert(Subtarget->isTargetDarwin());
6055
6056   // For iOS, we want to call an alternative entry point: __sincos_stret,
6057   // return values are passed via sret.
6058   SDLoc dl(Op);
6059   SDValue Arg = Op.getOperand(0);
6060   EVT ArgVT = Arg.getValueType();
6061   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6062
6063   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6065
6066   // Pair of floats / doubles used to pass the result.
6067   StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
6068
6069   // Create stack object for sret.
6070   const uint64_t ByteSize = TLI.getDataLayout()->getTypeAllocSize(RetTy);
6071   const unsigned StackAlign = TLI.getDataLayout()->getPrefTypeAlignment(RetTy);
6072   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6073   SDValue SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
6074
6075   ArgListTy Args;
6076   ArgListEntry Entry;
6077
6078   Entry.Node = SRet;
6079   Entry.Ty = RetTy->getPointerTo();
6080   Entry.isSExt = false;
6081   Entry.isZExt = false;
6082   Entry.isSRet = true;
6083   Args.push_back(Entry);
6084
6085   Entry.Node = Arg;
6086   Entry.Ty = ArgTy;
6087   Entry.isSExt = false;
6088   Entry.isZExt = false;
6089   Args.push_back(Entry);
6090
6091   const char *LibcallName  = (ArgVT == MVT::f64)
6092   ? "__sincos_stret" : "__sincosf_stret";
6093   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
6094
6095   TargetLowering::CallLoweringInfo CLI(DAG);
6096   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6097     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6098                &Args, 0)
6099     .setDiscardResult();
6100
6101   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6102
6103   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6104                                 MachinePointerInfo(), false, false, false, 0);
6105
6106   // Address of cos field.
6107   SDValue Add = DAG.getNode(ISD::ADD, dl, getPointerTy(), SRet,
6108                             DAG.getIntPtrConstant(ArgVT.getStoreSize()));
6109   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6110                                 MachinePointerInfo(), false, false, false, 0);
6111
6112   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6113   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6114                      LoadSin.getValue(0), LoadCos.getValue(0));
6115 }
6116
6117 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6118   // Monotonic load/store is legal for all targets
6119   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6120     return Op;
6121
6122   // Acquire/Release load/store is not legal for targets without a
6123   // dmb or equivalent available.
6124   return SDValue();
6125 }
6126
6127 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6128                                     SmallVectorImpl<SDValue> &Results,
6129                                     SelectionDAG &DAG,
6130                                     const ARMSubtarget *Subtarget) {
6131   SDLoc DL(N);
6132   SDValue Cycles32, OutChain;
6133
6134   if (Subtarget->hasPerfMon()) {
6135     // Under Power Management extensions, the cycle-count is:
6136     //    mrc p15, #0, <Rt>, c9, c13, #0
6137     SDValue Ops[] = { N->getOperand(0), // Chain
6138                       DAG.getConstant(Intrinsic::arm_mrc, MVT::i32),
6139                       DAG.getConstant(15, MVT::i32),
6140                       DAG.getConstant(0, MVT::i32),
6141                       DAG.getConstant(9, MVT::i32),
6142                       DAG.getConstant(13, MVT::i32),
6143                       DAG.getConstant(0, MVT::i32)
6144     };
6145
6146     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6147                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6148     OutChain = Cycles32.getValue(1);
6149   } else {
6150     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6151     // there are older ARM CPUs that have implementation-specific ways of
6152     // obtaining this information (FIXME!).
6153     Cycles32 = DAG.getConstant(0, MVT::i32);
6154     OutChain = DAG.getEntryNode();
6155   }
6156
6157
6158   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6159                                  Cycles32, DAG.getConstant(0, MVT::i32));
6160   Results.push_back(Cycles64);
6161   Results.push_back(OutChain);
6162 }
6163
6164 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6165   switch (Op.getOpcode()) {
6166   default: llvm_unreachable("Don't know how to custom lower this!");
6167   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6168   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6169   case ISD::GlobalAddress:
6170     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6171     default: llvm_unreachable("unknown object format");
6172     case Triple::COFF:
6173       return LowerGlobalAddressWindows(Op, DAG);
6174     case Triple::ELF:
6175       return LowerGlobalAddressELF(Op, DAG);
6176     case Triple::MachO:
6177       return LowerGlobalAddressDarwin(Op, DAG);
6178     }
6179   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6180   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6181   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6182   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6183   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6184   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6185   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6186   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6187   case ISD::SINT_TO_FP:
6188   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6189   case ISD::FP_TO_SINT:
6190   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6191   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6192   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6193   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6194   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6195   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6196   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6197   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6198                                                                Subtarget);
6199   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6200   case ISD::SHL:
6201   case ISD::SRL:
6202   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6203   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6204   case ISD::SRL_PARTS:
6205   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6206   case ISD::CTTZ:          return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6207   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6208   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6209   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6210   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6211   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6212   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6213   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6214   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6215   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6216   case ISD::MUL:           return LowerMUL(Op, DAG);
6217   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6218   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6219   case ISD::ADDC:
6220   case ISD::ADDE:
6221   case ISD::SUBC:
6222   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6223   case ISD::SADDO:
6224   case ISD::UADDO:
6225   case ISD::SSUBO:
6226   case ISD::USUBO:
6227     return LowerXALUO(Op, DAG);
6228   case ISD::ATOMIC_LOAD:
6229   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6230   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6231   case ISD::SDIVREM:
6232   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6233   case ISD::DYNAMIC_STACKALLOC:
6234     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6235       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6236     llvm_unreachable("Don't know how to custom lower this!");
6237   }
6238 }
6239
6240 /// ReplaceNodeResults - Replace the results of node with an illegal result
6241 /// type with new values built out of custom code.
6242 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6243                                            SmallVectorImpl<SDValue>&Results,
6244                                            SelectionDAG &DAG) const {
6245   SDValue Res;
6246   switch (N->getOpcode()) {
6247   default:
6248     llvm_unreachable("Don't know how to custom expand this!");
6249   case ISD::BITCAST:
6250     Res = ExpandBITCAST(N, DAG);
6251     break;
6252   case ISD::SRL:
6253   case ISD::SRA:
6254     Res = Expand64BitShift(N, DAG, Subtarget);
6255     break;
6256   case ISD::READCYCLECOUNTER:
6257     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6258     return;
6259   }
6260   if (Res.getNode())
6261     Results.push_back(Res);
6262 }
6263
6264 //===----------------------------------------------------------------------===//
6265 //                           ARM Scheduler Hooks
6266 //===----------------------------------------------------------------------===//
6267
6268 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6269 /// registers the function context.
6270 void ARMTargetLowering::
6271 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6272                        MachineBasicBlock *DispatchBB, int FI) const {
6273   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6274   DebugLoc dl = MI->getDebugLoc();
6275   MachineFunction *MF = MBB->getParent();
6276   MachineRegisterInfo *MRI = &MF->getRegInfo();
6277   MachineConstantPool *MCP = MF->getConstantPool();
6278   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6279   const Function *F = MF->getFunction();
6280
6281   bool isThumb = Subtarget->isThumb();
6282   bool isThumb2 = Subtarget->isThumb2();
6283
6284   unsigned PCLabelId = AFI->createPICLabelUId();
6285   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6286   ARMConstantPoolValue *CPV =
6287     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6288   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6289
6290   const TargetRegisterClass *TRC = isThumb ?
6291     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6292     (const TargetRegisterClass*)&ARM::GPRRegClass;
6293
6294   // Grab constant pool and fixed stack memory operands.
6295   MachineMemOperand *CPMMO =
6296     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6297                              MachineMemOperand::MOLoad, 4, 4);
6298
6299   MachineMemOperand *FIMMOSt =
6300     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6301                              MachineMemOperand::MOStore, 4, 4);
6302
6303   // Load the address of the dispatch MBB into the jump buffer.
6304   if (isThumb2) {
6305     // Incoming value: jbuf
6306     //   ldr.n  r5, LCPI1_1
6307     //   orr    r5, r5, #1
6308     //   add    r5, pc
6309     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6310     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6311     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6312                    .addConstantPoolIndex(CPI)
6313                    .addMemOperand(CPMMO));
6314     // Set the low bit because of thumb mode.
6315     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6316     AddDefaultCC(
6317       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6318                      .addReg(NewVReg1, RegState::Kill)
6319                      .addImm(0x01)));
6320     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6321     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6322       .addReg(NewVReg2, RegState::Kill)
6323       .addImm(PCLabelId);
6324     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6325                    .addReg(NewVReg3, RegState::Kill)
6326                    .addFrameIndex(FI)
6327                    .addImm(36)  // &jbuf[1] :: pc
6328                    .addMemOperand(FIMMOSt));
6329   } else if (isThumb) {
6330     // Incoming value: jbuf
6331     //   ldr.n  r1, LCPI1_4
6332     //   add    r1, pc
6333     //   mov    r2, #1
6334     //   orrs   r1, r2
6335     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6336     //   str    r1, [r2]
6337     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6338     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6339                    .addConstantPoolIndex(CPI)
6340                    .addMemOperand(CPMMO));
6341     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6342     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6343       .addReg(NewVReg1, RegState::Kill)
6344       .addImm(PCLabelId);
6345     // Set the low bit because of thumb mode.
6346     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6347     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6348                    .addReg(ARM::CPSR, RegState::Define)
6349                    .addImm(1));
6350     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6351     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6352                    .addReg(ARM::CPSR, RegState::Define)
6353                    .addReg(NewVReg2, RegState::Kill)
6354                    .addReg(NewVReg3, RegState::Kill));
6355     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6356     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tADDrSPi), NewVReg5)
6357                    .addFrameIndex(FI)
6358                    .addImm(36)); // &jbuf[1] :: pc
6359     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6360                    .addReg(NewVReg4, RegState::Kill)
6361                    .addReg(NewVReg5, RegState::Kill)
6362                    .addImm(0)
6363                    .addMemOperand(FIMMOSt));
6364   } else {
6365     // Incoming value: jbuf
6366     //   ldr  r1, LCPI1_1
6367     //   add  r1, pc, r1
6368     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6369     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6370     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6371                    .addConstantPoolIndex(CPI)
6372                    .addImm(0)
6373                    .addMemOperand(CPMMO));
6374     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6375     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6376                    .addReg(NewVReg1, RegState::Kill)
6377                    .addImm(PCLabelId));
6378     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6379                    .addReg(NewVReg2, RegState::Kill)
6380                    .addFrameIndex(FI)
6381                    .addImm(36)  // &jbuf[1] :: pc
6382                    .addMemOperand(FIMMOSt));
6383   }
6384 }
6385
6386 MachineBasicBlock *ARMTargetLowering::
6387 EmitSjLjDispatchBlock(MachineInstr *MI, MachineBasicBlock *MBB) const {
6388   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6389   DebugLoc dl = MI->getDebugLoc();
6390   MachineFunction *MF = MBB->getParent();
6391   MachineRegisterInfo *MRI = &MF->getRegInfo();
6392   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6393   MachineFrameInfo *MFI = MF->getFrameInfo();
6394   int FI = MFI->getFunctionContextIndex();
6395
6396   const TargetRegisterClass *TRC = Subtarget->isThumb() ?
6397     (const TargetRegisterClass*)&ARM::tGPRRegClass :
6398     (const TargetRegisterClass*)&ARM::GPRnopcRegClass;
6399
6400   // Get a mapping of the call site numbers to all of the landing pads they're
6401   // associated with.
6402   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6403   unsigned MaxCSNum = 0;
6404   MachineModuleInfo &MMI = MF->getMMI();
6405   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6406        ++BB) {
6407     if (!BB->isLandingPad()) continue;
6408
6409     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6410     // pad.
6411     for (MachineBasicBlock::iterator
6412            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6413       if (!II->isEHLabel()) continue;
6414
6415       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6416       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6417
6418       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6419       for (SmallVectorImpl<unsigned>::iterator
6420              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6421            CSI != CSE; ++CSI) {
6422         CallSiteNumToLPad[*CSI].push_back(BB);
6423         MaxCSNum = std::max(MaxCSNum, *CSI);
6424       }
6425       break;
6426     }
6427   }
6428
6429   // Get an ordered list of the machine basic blocks for the jump table.
6430   std::vector<MachineBasicBlock*> LPadList;
6431   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
6432   LPadList.reserve(CallSiteNumToLPad.size());
6433   for (unsigned I = 1; I <= MaxCSNum; ++I) {
6434     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
6435     for (SmallVectorImpl<MachineBasicBlock*>::iterator
6436            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
6437       LPadList.push_back(*II);
6438       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
6439     }
6440   }
6441
6442   assert(!LPadList.empty() &&
6443          "No landing pad destinations for the dispatch jump table!");
6444
6445   // Create the jump table and associated information.
6446   MachineJumpTableInfo *JTI =
6447     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
6448   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
6449   unsigned UId = AFI->createJumpTableUId();
6450   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
6451
6452   // Create the MBBs for the dispatch code.
6453
6454   // Shove the dispatch's address into the return slot in the function context.
6455   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
6456   DispatchBB->setIsLandingPad();
6457
6458   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
6459   unsigned trap_opcode;
6460   if (Subtarget->isThumb())
6461     trap_opcode = ARM::tTRAP;
6462   else
6463     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
6464
6465   BuildMI(TrapBB, dl, TII->get(trap_opcode));
6466   DispatchBB->addSuccessor(TrapBB);
6467
6468   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
6469   DispatchBB->addSuccessor(DispContBB);
6470
6471   // Insert and MBBs.
6472   MF->insert(MF->end(), DispatchBB);
6473   MF->insert(MF->end(), DispContBB);
6474   MF->insert(MF->end(), TrapBB);
6475
6476   // Insert code into the entry block that creates and registers the function
6477   // context.
6478   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
6479
6480   MachineMemOperand *FIMMOLd =
6481     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6482                              MachineMemOperand::MOLoad |
6483                              MachineMemOperand::MOVolatile, 4, 4);
6484
6485   MachineInstrBuilder MIB;
6486   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
6487
6488   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
6489   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
6490
6491   // Add a register mask with no preserved registers.  This results in all
6492   // registers being marked as clobbered.
6493   MIB.addRegMask(RI.getNoPreservedMask());
6494
6495   unsigned NumLPads = LPadList.size();
6496   if (Subtarget->isThumb2()) {
6497     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6498     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
6499                    .addFrameIndex(FI)
6500                    .addImm(4)
6501                    .addMemOperand(FIMMOLd));
6502
6503     if (NumLPads < 256) {
6504       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
6505                      .addReg(NewVReg1)
6506                      .addImm(LPadList.size()));
6507     } else {
6508       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6509       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
6510                      .addImm(NumLPads & 0xFFFF));
6511
6512       unsigned VReg2 = VReg1;
6513       if ((NumLPads & 0xFFFF0000) != 0) {
6514         VReg2 = MRI->createVirtualRegister(TRC);
6515         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
6516                        .addReg(VReg1)
6517                        .addImm(NumLPads >> 16));
6518       }
6519
6520       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
6521                      .addReg(NewVReg1)
6522                      .addReg(VReg2));
6523     }
6524
6525     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
6526       .addMBB(TrapBB)
6527       .addImm(ARMCC::HI)
6528       .addReg(ARM::CPSR);
6529
6530     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6531     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
6532                    .addJumpTableIndex(MJTI)
6533                    .addImm(UId));
6534
6535     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6536     AddDefaultCC(
6537       AddDefaultPred(
6538         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
6539         .addReg(NewVReg3, RegState::Kill)
6540         .addReg(NewVReg1)
6541         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6542
6543     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
6544       .addReg(NewVReg4, RegState::Kill)
6545       .addReg(NewVReg1)
6546       .addJumpTableIndex(MJTI)
6547       .addImm(UId);
6548   } else if (Subtarget->isThumb()) {
6549     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6550     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
6551                    .addFrameIndex(FI)
6552                    .addImm(1)
6553                    .addMemOperand(FIMMOLd));
6554
6555     if (NumLPads < 256) {
6556       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
6557                      .addReg(NewVReg1)
6558                      .addImm(NumLPads));
6559     } else {
6560       MachineConstantPool *ConstantPool = MF->getConstantPool();
6561       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6562       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6563
6564       // MachineConstantPool wants an explicit alignment.
6565       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6566       if (Align == 0)
6567         Align = getDataLayout()->getTypeAllocSize(C->getType());
6568       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6569
6570       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6571       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
6572                      .addReg(VReg1, RegState::Define)
6573                      .addConstantPoolIndex(Idx));
6574       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
6575                      .addReg(NewVReg1)
6576                      .addReg(VReg1));
6577     }
6578
6579     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
6580       .addMBB(TrapBB)
6581       .addImm(ARMCC::HI)
6582       .addReg(ARM::CPSR);
6583
6584     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6585     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
6586                    .addReg(ARM::CPSR, RegState::Define)
6587                    .addReg(NewVReg1)
6588                    .addImm(2));
6589
6590     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6591     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
6592                    .addJumpTableIndex(MJTI)
6593                    .addImm(UId));
6594
6595     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6596     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
6597                    .addReg(ARM::CPSR, RegState::Define)
6598                    .addReg(NewVReg2, RegState::Kill)
6599                    .addReg(NewVReg3));
6600
6601     MachineMemOperand *JTMMOLd =
6602       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6603                                MachineMemOperand::MOLoad, 4, 4);
6604
6605     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6606     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
6607                    .addReg(NewVReg4, RegState::Kill)
6608                    .addImm(0)
6609                    .addMemOperand(JTMMOLd));
6610
6611     unsigned NewVReg6 = NewVReg5;
6612     if (RelocM == Reloc::PIC_) {
6613       NewVReg6 = MRI->createVirtualRegister(TRC);
6614       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
6615                      .addReg(ARM::CPSR, RegState::Define)
6616                      .addReg(NewVReg5, RegState::Kill)
6617                      .addReg(NewVReg3));
6618     }
6619
6620     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
6621       .addReg(NewVReg6, RegState::Kill)
6622       .addJumpTableIndex(MJTI)
6623       .addImm(UId);
6624   } else {
6625     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6626     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
6627                    .addFrameIndex(FI)
6628                    .addImm(4)
6629                    .addMemOperand(FIMMOLd));
6630
6631     if (NumLPads < 256) {
6632       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
6633                      .addReg(NewVReg1)
6634                      .addImm(NumLPads));
6635     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
6636       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6637       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
6638                      .addImm(NumLPads & 0xFFFF));
6639
6640       unsigned VReg2 = VReg1;
6641       if ((NumLPads & 0xFFFF0000) != 0) {
6642         VReg2 = MRI->createVirtualRegister(TRC);
6643         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
6644                        .addReg(VReg1)
6645                        .addImm(NumLPads >> 16));
6646       }
6647
6648       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6649                      .addReg(NewVReg1)
6650                      .addReg(VReg2));
6651     } else {
6652       MachineConstantPool *ConstantPool = MF->getConstantPool();
6653       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
6654       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
6655
6656       // MachineConstantPool wants an explicit alignment.
6657       unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
6658       if (Align == 0)
6659         Align = getDataLayout()->getTypeAllocSize(C->getType());
6660       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
6661
6662       unsigned VReg1 = MRI->createVirtualRegister(TRC);
6663       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
6664                      .addReg(VReg1, RegState::Define)
6665                      .addConstantPoolIndex(Idx)
6666                      .addImm(0));
6667       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
6668                      .addReg(NewVReg1)
6669                      .addReg(VReg1, RegState::Kill));
6670     }
6671
6672     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
6673       .addMBB(TrapBB)
6674       .addImm(ARMCC::HI)
6675       .addReg(ARM::CPSR);
6676
6677     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6678     AddDefaultCC(
6679       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
6680                      .addReg(NewVReg1)
6681                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
6682     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6683     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
6684                    .addJumpTableIndex(MJTI)
6685                    .addImm(UId));
6686
6687     MachineMemOperand *JTMMOLd =
6688       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
6689                                MachineMemOperand::MOLoad, 4, 4);
6690     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6691     AddDefaultPred(
6692       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
6693       .addReg(NewVReg3, RegState::Kill)
6694       .addReg(NewVReg4)
6695       .addImm(0)
6696       .addMemOperand(JTMMOLd));
6697
6698     if (RelocM == Reloc::PIC_) {
6699       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
6700         .addReg(NewVReg5, RegState::Kill)
6701         .addReg(NewVReg4)
6702         .addJumpTableIndex(MJTI)
6703         .addImm(UId);
6704     } else {
6705       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
6706         .addReg(NewVReg5, RegState::Kill)
6707         .addJumpTableIndex(MJTI)
6708         .addImm(UId);
6709     }
6710   }
6711
6712   // Add the jump table entries as successors to the MBB.
6713   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
6714   for (std::vector<MachineBasicBlock*>::iterator
6715          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
6716     MachineBasicBlock *CurMBB = *I;
6717     if (SeenMBBs.insert(CurMBB))
6718       DispContBB->addSuccessor(CurMBB);
6719   }
6720
6721   // N.B. the order the invoke BBs are processed in doesn't matter here.
6722   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
6723   SmallVector<MachineBasicBlock*, 64> MBBLPads;
6724   for (SmallPtrSet<MachineBasicBlock*, 64>::iterator
6725          I = InvokeBBs.begin(), E = InvokeBBs.end(); I != E; ++I) {
6726     MachineBasicBlock *BB = *I;
6727
6728     // Remove the landing pad successor from the invoke block and replace it
6729     // with the new dispatch block.
6730     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
6731                                                   BB->succ_end());
6732     while (!Successors.empty()) {
6733       MachineBasicBlock *SMBB = Successors.pop_back_val();
6734       if (SMBB->isLandingPad()) {
6735         BB->removeSuccessor(SMBB);
6736         MBBLPads.push_back(SMBB);
6737       }
6738     }
6739
6740     BB->addSuccessor(DispatchBB);
6741
6742     // Find the invoke call and mark all of the callee-saved registers as
6743     // 'implicit defined' so that they're spilled. This prevents code from
6744     // moving instructions to before the EH block, where they will never be
6745     // executed.
6746     for (MachineBasicBlock::reverse_iterator
6747            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
6748       if (!II->isCall()) continue;
6749
6750       DenseMap<unsigned, bool> DefRegs;
6751       for (MachineInstr::mop_iterator
6752              OI = II->operands_begin(), OE = II->operands_end();
6753            OI != OE; ++OI) {
6754         if (!OI->isReg()) continue;
6755         DefRegs[OI->getReg()] = true;
6756       }
6757
6758       MachineInstrBuilder MIB(*MF, &*II);
6759
6760       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
6761         unsigned Reg = SavedRegs[i];
6762         if (Subtarget->isThumb2() &&
6763             !ARM::tGPRRegClass.contains(Reg) &&
6764             !ARM::hGPRRegClass.contains(Reg))
6765           continue;
6766         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
6767           continue;
6768         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
6769           continue;
6770         if (!DefRegs[Reg])
6771           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
6772       }
6773
6774       break;
6775     }
6776   }
6777
6778   // Mark all former landing pads as non-landing pads. The dispatch is the only
6779   // landing pad now.
6780   for (SmallVectorImpl<MachineBasicBlock*>::iterator
6781          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
6782     (*I)->setIsLandingPad(false);
6783
6784   // The instruction is gone now.
6785   MI->eraseFromParent();
6786
6787   return MBB;
6788 }
6789
6790 static
6791 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
6792   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
6793        E = MBB->succ_end(); I != E; ++I)
6794     if (*I != Succ)
6795       return *I;
6796   llvm_unreachable("Expecting a BB with two successors!");
6797 }
6798
6799 /// Return the load opcode for a given load size. If load size >= 8,
6800 /// neon opcode will be returned.
6801 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
6802   if (LdSize >= 8)
6803     return LdSize == 16 ? ARM::VLD1q32wb_fixed
6804                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
6805   if (IsThumb1)
6806     return LdSize == 4 ? ARM::tLDRi
6807                        : LdSize == 2 ? ARM::tLDRHi
6808                                      : LdSize == 1 ? ARM::tLDRBi : 0;
6809   if (IsThumb2)
6810     return LdSize == 4 ? ARM::t2LDR_POST
6811                        : LdSize == 2 ? ARM::t2LDRH_POST
6812                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
6813   return LdSize == 4 ? ARM::LDR_POST_IMM
6814                      : LdSize == 2 ? ARM::LDRH_POST
6815                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
6816 }
6817
6818 /// Return the store opcode for a given store size. If store size >= 8,
6819 /// neon opcode will be returned.
6820 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
6821   if (StSize >= 8)
6822     return StSize == 16 ? ARM::VST1q32wb_fixed
6823                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
6824   if (IsThumb1)
6825     return StSize == 4 ? ARM::tSTRi
6826                        : StSize == 2 ? ARM::tSTRHi
6827                                      : StSize == 1 ? ARM::tSTRBi : 0;
6828   if (IsThumb2)
6829     return StSize == 4 ? ARM::t2STR_POST
6830                        : StSize == 2 ? ARM::t2STRH_POST
6831                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
6832   return StSize == 4 ? ARM::STR_POST_IMM
6833                      : StSize == 2 ? ARM::STRH_POST
6834                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
6835 }
6836
6837 /// Emit a post-increment load operation with given size. The instructions
6838 /// will be added to BB at Pos.
6839 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
6840                        const TargetInstrInfo *TII, DebugLoc dl,
6841                        unsigned LdSize, unsigned Data, unsigned AddrIn,
6842                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6843   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
6844   assert(LdOpc != 0 && "Should have a load opcode");
6845   if (LdSize >= 8) {
6846     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6847                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6848                        .addImm(0));
6849   } else if (IsThumb1) {
6850     // load + update AddrIn
6851     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6852                        .addReg(AddrIn).addImm(0));
6853     MachineInstrBuilder MIB =
6854         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6855     MIB = AddDefaultT1CC(MIB);
6856     MIB.addReg(AddrIn).addImm(LdSize);
6857     AddDefaultPred(MIB);
6858   } else if (IsThumb2) {
6859     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6860                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6861                        .addImm(LdSize));
6862   } else { // arm
6863     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
6864                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
6865                        .addReg(0).addImm(LdSize));
6866   }
6867 }
6868
6869 /// Emit a post-increment store operation with given size. The instructions
6870 /// will be added to BB at Pos.
6871 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
6872                        const TargetInstrInfo *TII, DebugLoc dl,
6873                        unsigned StSize, unsigned Data, unsigned AddrIn,
6874                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
6875   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
6876   assert(StOpc != 0 && "Should have a store opcode");
6877   if (StSize >= 8) {
6878     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6879                        .addReg(AddrIn).addImm(0).addReg(Data));
6880   } else if (IsThumb1) {
6881     // store + update AddrIn
6882     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
6883                        .addReg(AddrIn).addImm(0));
6884     MachineInstrBuilder MIB =
6885         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
6886     MIB = AddDefaultT1CC(MIB);
6887     MIB.addReg(AddrIn).addImm(StSize);
6888     AddDefaultPred(MIB);
6889   } else if (IsThumb2) {
6890     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6891                        .addReg(Data).addReg(AddrIn).addImm(StSize));
6892   } else { // arm
6893     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
6894                        .addReg(Data).addReg(AddrIn).addReg(0)
6895                        .addImm(StSize));
6896   }
6897 }
6898
6899 MachineBasicBlock *
6900 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
6901                                    MachineBasicBlock *BB) const {
6902   // This pseudo instruction has 3 operands: dst, src, size
6903   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
6904   // Otherwise, we will generate unrolled scalar copies.
6905   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6906   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6907   MachineFunction::iterator It = BB;
6908   ++It;
6909
6910   unsigned dest = MI->getOperand(0).getReg();
6911   unsigned src = MI->getOperand(1).getReg();
6912   unsigned SizeVal = MI->getOperand(2).getImm();
6913   unsigned Align = MI->getOperand(3).getImm();
6914   DebugLoc dl = MI->getDebugLoc();
6915
6916   MachineFunction *MF = BB->getParent();
6917   MachineRegisterInfo &MRI = MF->getRegInfo();
6918   unsigned UnitSize = 0;
6919   const TargetRegisterClass *TRC = nullptr;
6920   const TargetRegisterClass *VecTRC = nullptr;
6921
6922   bool IsThumb1 = Subtarget->isThumb1Only();
6923   bool IsThumb2 = Subtarget->isThumb2();
6924
6925   if (Align & 1) {
6926     UnitSize = 1;
6927   } else if (Align & 2) {
6928     UnitSize = 2;
6929   } else {
6930     // Check whether we can use NEON instructions.
6931     if (!MF->getFunction()->getAttributes().
6932           hasAttribute(AttributeSet::FunctionIndex,
6933                        Attribute::NoImplicitFloat) &&
6934         Subtarget->hasNEON()) {
6935       if ((Align % 16 == 0) && SizeVal >= 16)
6936         UnitSize = 16;
6937       else if ((Align % 8 == 0) && SizeVal >= 8)
6938         UnitSize = 8;
6939     }
6940     // Can't use NEON instructions.
6941     if (UnitSize == 0)
6942       UnitSize = 4;
6943   }
6944
6945   // Select the correct opcode and register class for unit size load/store
6946   bool IsNeon = UnitSize >= 8;
6947   TRC = (IsThumb1 || IsThumb2) ? (const TargetRegisterClass *)&ARM::tGPRRegClass
6948                                : (const TargetRegisterClass *)&ARM::GPRRegClass;
6949   if (IsNeon)
6950     VecTRC = UnitSize == 16
6951                  ? (const TargetRegisterClass *)&ARM::DPairRegClass
6952                  : UnitSize == 8
6953                        ? (const TargetRegisterClass *)&ARM::DPRRegClass
6954                        : nullptr;
6955
6956   unsigned BytesLeft = SizeVal % UnitSize;
6957   unsigned LoopSize = SizeVal - BytesLeft;
6958
6959   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
6960     // Use LDR and STR to copy.
6961     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
6962     // [destOut] = STR_POST(scratch, destIn, UnitSize)
6963     unsigned srcIn = src;
6964     unsigned destIn = dest;
6965     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
6966       unsigned srcOut = MRI.createVirtualRegister(TRC);
6967       unsigned destOut = MRI.createVirtualRegister(TRC);
6968       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
6969       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
6970                  IsThumb1, IsThumb2);
6971       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
6972                  IsThumb1, IsThumb2);
6973       srcIn = srcOut;
6974       destIn = destOut;
6975     }
6976
6977     // Handle the leftover bytes with LDRB and STRB.
6978     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
6979     // [destOut] = STRB_POST(scratch, destIn, 1)
6980     for (unsigned i = 0; i < BytesLeft; i++) {
6981       unsigned srcOut = MRI.createVirtualRegister(TRC);
6982       unsigned destOut = MRI.createVirtualRegister(TRC);
6983       unsigned scratch = MRI.createVirtualRegister(TRC);
6984       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
6985                  IsThumb1, IsThumb2);
6986       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
6987                  IsThumb1, IsThumb2);
6988       srcIn = srcOut;
6989       destIn = destOut;
6990     }
6991     MI->eraseFromParent();   // The instruction is gone now.
6992     return BB;
6993   }
6994
6995   // Expand the pseudo op to a loop.
6996   // thisMBB:
6997   //   ...
6998   //   movw varEnd, # --> with thumb2
6999   //   movt varEnd, #
7000   //   ldrcp varEnd, idx --> without thumb2
7001   //   fallthrough --> loopMBB
7002   // loopMBB:
7003   //   PHI varPhi, varEnd, varLoop
7004   //   PHI srcPhi, src, srcLoop
7005   //   PHI destPhi, dst, destLoop
7006   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7007   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7008   //   subs varLoop, varPhi, #UnitSize
7009   //   bne loopMBB
7010   //   fallthrough --> exitMBB
7011   // exitMBB:
7012   //   epilogue to handle left-over bytes
7013   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7014   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7015   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7016   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7017   MF->insert(It, loopMBB);
7018   MF->insert(It, exitMBB);
7019
7020   // Transfer the remainder of BB and its successor edges to exitMBB.
7021   exitMBB->splice(exitMBB->begin(), BB,
7022                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7023   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7024
7025   // Load an immediate to varEnd.
7026   unsigned varEnd = MRI.createVirtualRegister(TRC);
7027   if (IsThumb2) {
7028     unsigned Vtmp = varEnd;
7029     if ((LoopSize & 0xFFFF0000) != 0)
7030       Vtmp = MRI.createVirtualRegister(TRC);
7031     AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVi16), Vtmp)
7032                        .addImm(LoopSize & 0xFFFF));
7033
7034     if ((LoopSize & 0xFFFF0000) != 0)
7035       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2MOVTi16), varEnd)
7036                          .addReg(Vtmp).addImm(LoopSize >> 16));
7037   } else {
7038     MachineConstantPool *ConstantPool = MF->getConstantPool();
7039     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7040     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7041
7042     // MachineConstantPool wants an explicit alignment.
7043     unsigned Align = getDataLayout()->getPrefTypeAlignment(Int32Ty);
7044     if (Align == 0)
7045       Align = getDataLayout()->getTypeAllocSize(C->getType());
7046     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7047
7048     if (IsThumb1)
7049       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7050           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7051     else
7052       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7053           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7054   }
7055   BB->addSuccessor(loopMBB);
7056
7057   // Generate the loop body:
7058   //   varPhi = PHI(varLoop, varEnd)
7059   //   srcPhi = PHI(srcLoop, src)
7060   //   destPhi = PHI(destLoop, dst)
7061   MachineBasicBlock *entryBB = BB;
7062   BB = loopMBB;
7063   unsigned varLoop = MRI.createVirtualRegister(TRC);
7064   unsigned varPhi = MRI.createVirtualRegister(TRC);
7065   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7066   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7067   unsigned destLoop = MRI.createVirtualRegister(TRC);
7068   unsigned destPhi = MRI.createVirtualRegister(TRC);
7069
7070   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7071     .addReg(varLoop).addMBB(loopMBB)
7072     .addReg(varEnd).addMBB(entryBB);
7073   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7074     .addReg(srcLoop).addMBB(loopMBB)
7075     .addReg(src).addMBB(entryBB);
7076   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7077     .addReg(destLoop).addMBB(loopMBB)
7078     .addReg(dest).addMBB(entryBB);
7079
7080   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7081   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7082   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7083   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7084              IsThumb1, IsThumb2);
7085   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7086              IsThumb1, IsThumb2);
7087
7088   // Decrement loop variable by UnitSize.
7089   if (IsThumb1) {
7090     MachineInstrBuilder MIB =
7091         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7092     MIB = AddDefaultT1CC(MIB);
7093     MIB.addReg(varPhi).addImm(UnitSize);
7094     AddDefaultPred(MIB);
7095   } else {
7096     MachineInstrBuilder MIB =
7097         BuildMI(*BB, BB->end(), dl,
7098                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7099     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7100     MIB->getOperand(5).setReg(ARM::CPSR);
7101     MIB->getOperand(5).setIsDef(true);
7102   }
7103   BuildMI(*BB, BB->end(), dl,
7104           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7105       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7106
7107   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7108   BB->addSuccessor(loopMBB);
7109   BB->addSuccessor(exitMBB);
7110
7111   // Add epilogue to handle BytesLeft.
7112   BB = exitMBB;
7113   MachineInstr *StartOfExit = exitMBB->begin();
7114
7115   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7116   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7117   unsigned srcIn = srcLoop;
7118   unsigned destIn = destLoop;
7119   for (unsigned i = 0; i < BytesLeft; i++) {
7120     unsigned srcOut = MRI.createVirtualRegister(TRC);
7121     unsigned destOut = MRI.createVirtualRegister(TRC);
7122     unsigned scratch = MRI.createVirtualRegister(TRC);
7123     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7124                IsThumb1, IsThumb2);
7125     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7126                IsThumb1, IsThumb2);
7127     srcIn = srcOut;
7128     destIn = destOut;
7129   }
7130
7131   MI->eraseFromParent();   // The instruction is gone now.
7132   return BB;
7133 }
7134
7135 MachineBasicBlock *
7136 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7137                                        MachineBasicBlock *MBB) const {
7138   const TargetMachine &TM = getTargetMachine();
7139   const TargetInstrInfo &TII = *TM.getInstrInfo();
7140   DebugLoc DL = MI->getDebugLoc();
7141
7142   assert(Subtarget->isTargetWindows() &&
7143          "__chkstk is only supported on Windows");
7144   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7145
7146   // __chkstk takes the number of words to allocate on the stack in R4, and
7147   // returns the stack adjustment in number of bytes in R4.  This will not
7148   // clober any other registers (other than the obvious lr).
7149   //
7150   // Although, technically, IP should be considered a register which may be
7151   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7152   // thumb-2 environment, so there is no interworking required.  As a result, we
7153   // do not expect a veneer to be emitted by the linker, clobbering IP.
7154   //
7155   // Each module receives its own copy of __chkstk, so no import thunk is
7156   // required, again, ensuring that IP is not clobbered.
7157   //
7158   // Finally, although some linkers may theoretically provide a trampoline for
7159   // out of range calls (which is quite common due to a 32M range limitation of
7160   // branches for Thumb), we can generate the long-call version via
7161   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7162   // IP.
7163
7164   switch (TM.getCodeModel()) {
7165   case CodeModel::Small:
7166   case CodeModel::Medium:
7167   case CodeModel::Default:
7168   case CodeModel::Kernel:
7169     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7170       .addImm((unsigned)ARMCC::AL).addReg(0)
7171       .addExternalSymbol("__chkstk")
7172       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7173       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7174       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7175     break;
7176   case CodeModel::Large:
7177   case CodeModel::JITDefault: {
7178     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7179     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7180
7181     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7182       .addExternalSymbol("__chkstk");
7183     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7184       .addImm((unsigned)ARMCC::AL).addReg(0)
7185       .addReg(Reg, RegState::Kill)
7186       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7187       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7188       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7189     break;
7190   }
7191   }
7192
7193   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7194                                       ARM::SP)
7195                               .addReg(ARM::SP, RegState::Define)
7196                               .addReg(ARM::R4, RegState::Kill)));
7197
7198   MI->eraseFromParent();
7199   return MBB;
7200 }
7201
7202 MachineBasicBlock *
7203 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7204                                                MachineBasicBlock *BB) const {
7205   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7206   DebugLoc dl = MI->getDebugLoc();
7207   bool isThumb2 = Subtarget->isThumb2();
7208   switch (MI->getOpcode()) {
7209   default: {
7210     MI->dump();
7211     llvm_unreachable("Unexpected instr type to insert");
7212   }
7213   // The Thumb2 pre-indexed stores have the same MI operands, they just
7214   // define them differently in the .td files from the isel patterns, so
7215   // they need pseudos.
7216   case ARM::t2STR_preidx:
7217     MI->setDesc(TII->get(ARM::t2STR_PRE));
7218     return BB;
7219   case ARM::t2STRB_preidx:
7220     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7221     return BB;
7222   case ARM::t2STRH_preidx:
7223     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7224     return BB;
7225
7226   case ARM::STRi_preidx:
7227   case ARM::STRBi_preidx: {
7228     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7229       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7230     // Decode the offset.
7231     unsigned Offset = MI->getOperand(4).getImm();
7232     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7233     Offset = ARM_AM::getAM2Offset(Offset);
7234     if (isSub)
7235       Offset = -Offset;
7236
7237     MachineMemOperand *MMO = *MI->memoperands_begin();
7238     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7239       .addOperand(MI->getOperand(0))  // Rn_wb
7240       .addOperand(MI->getOperand(1))  // Rt
7241       .addOperand(MI->getOperand(2))  // Rn
7242       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7243       .addOperand(MI->getOperand(5))  // pred
7244       .addOperand(MI->getOperand(6))
7245       .addMemOperand(MMO);
7246     MI->eraseFromParent();
7247     return BB;
7248   }
7249   case ARM::STRr_preidx:
7250   case ARM::STRBr_preidx:
7251   case ARM::STRH_preidx: {
7252     unsigned NewOpc;
7253     switch (MI->getOpcode()) {
7254     default: llvm_unreachable("unexpected opcode!");
7255     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7256     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7257     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7258     }
7259     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7260     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7261       MIB.addOperand(MI->getOperand(i));
7262     MI->eraseFromParent();
7263     return BB;
7264   }
7265
7266   case ARM::tMOVCCr_pseudo: {
7267     // To "insert" a SELECT_CC instruction, we actually have to insert the
7268     // diamond control-flow pattern.  The incoming instruction knows the
7269     // destination vreg to set, the condition code register to branch on, the
7270     // true/false values to select between, and a branch opcode to use.
7271     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7272     MachineFunction::iterator It = BB;
7273     ++It;
7274
7275     //  thisMBB:
7276     //  ...
7277     //   TrueVal = ...
7278     //   cmpTY ccX, r1, r2
7279     //   bCC copy1MBB
7280     //   fallthrough --> copy0MBB
7281     MachineBasicBlock *thisMBB  = BB;
7282     MachineFunction *F = BB->getParent();
7283     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7284     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7285     F->insert(It, copy0MBB);
7286     F->insert(It, sinkMBB);
7287
7288     // Transfer the remainder of BB and its successor edges to sinkMBB.
7289     sinkMBB->splice(sinkMBB->begin(), BB,
7290                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7291     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7292
7293     BB->addSuccessor(copy0MBB);
7294     BB->addSuccessor(sinkMBB);
7295
7296     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7297       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7298
7299     //  copy0MBB:
7300     //   %FalseValue = ...
7301     //   # fallthrough to sinkMBB
7302     BB = copy0MBB;
7303
7304     // Update machine-CFG edges
7305     BB->addSuccessor(sinkMBB);
7306
7307     //  sinkMBB:
7308     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7309     //  ...
7310     BB = sinkMBB;
7311     BuildMI(*BB, BB->begin(), dl,
7312             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7313       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7314       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7315
7316     MI->eraseFromParent();   // The pseudo instruction is gone now.
7317     return BB;
7318   }
7319
7320   case ARM::BCCi64:
7321   case ARM::BCCZi64: {
7322     // If there is an unconditional branch to the other successor, remove it.
7323     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7324
7325     // Compare both parts that make up the double comparison separately for
7326     // equality.
7327     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7328
7329     unsigned LHS1 = MI->getOperand(1).getReg();
7330     unsigned LHS2 = MI->getOperand(2).getReg();
7331     if (RHSisZero) {
7332       AddDefaultPred(BuildMI(BB, dl,
7333                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7334                      .addReg(LHS1).addImm(0));
7335       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7336         .addReg(LHS2).addImm(0)
7337         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7338     } else {
7339       unsigned RHS1 = MI->getOperand(3).getReg();
7340       unsigned RHS2 = MI->getOperand(4).getReg();
7341       AddDefaultPred(BuildMI(BB, dl,
7342                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7343                      .addReg(LHS1).addReg(RHS1));
7344       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7345         .addReg(LHS2).addReg(RHS2)
7346         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7347     }
7348
7349     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7350     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7351     if (MI->getOperand(0).getImm() == ARMCC::NE)
7352       std::swap(destMBB, exitMBB);
7353
7354     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7355       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7356     if (isThumb2)
7357       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7358     else
7359       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7360
7361     MI->eraseFromParent();   // The pseudo instruction is gone now.
7362     return BB;
7363   }
7364
7365   case ARM::Int_eh_sjlj_setjmp:
7366   case ARM::Int_eh_sjlj_setjmp_nofp:
7367   case ARM::tInt_eh_sjlj_setjmp:
7368   case ARM::t2Int_eh_sjlj_setjmp:
7369   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7370     EmitSjLjDispatchBlock(MI, BB);
7371     return BB;
7372
7373   case ARM::ABS:
7374   case ARM::t2ABS: {
7375     // To insert an ABS instruction, we have to insert the
7376     // diamond control-flow pattern.  The incoming instruction knows the
7377     // source vreg to test against 0, the destination vreg to set,
7378     // the condition code register to branch on, the
7379     // true/false values to select between, and a branch opcode to use.
7380     // It transforms
7381     //     V1 = ABS V0
7382     // into
7383     //     V2 = MOVS V0
7384     //     BCC                      (branch to SinkBB if V0 >= 0)
7385     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7386     //     SinkBB: V1 = PHI(V2, V3)
7387     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7388     MachineFunction::iterator BBI = BB;
7389     ++BBI;
7390     MachineFunction *Fn = BB->getParent();
7391     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7392     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7393     Fn->insert(BBI, RSBBB);
7394     Fn->insert(BBI, SinkBB);
7395
7396     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7397     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7398     bool isThumb2 = Subtarget->isThumb2();
7399     MachineRegisterInfo &MRI = Fn->getRegInfo();
7400     // In Thumb mode S must not be specified if source register is the SP or
7401     // PC and if destination register is the SP, so restrict register class
7402     unsigned NewRsbDstReg = MRI.createVirtualRegister(isThumb2 ?
7403       (const TargetRegisterClass*)&ARM::rGPRRegClass :
7404       (const TargetRegisterClass*)&ARM::GPRRegClass);
7405
7406     // Transfer the remainder of BB and its successor edges to sinkMBB.
7407     SinkBB->splice(SinkBB->begin(), BB,
7408                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7409     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7410
7411     BB->addSuccessor(RSBBB);
7412     BB->addSuccessor(SinkBB);
7413
7414     // fall through to SinkMBB
7415     RSBBB->addSuccessor(SinkBB);
7416
7417     // insert a cmp at the end of BB
7418     AddDefaultPred(BuildMI(BB, dl,
7419                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7420                    .addReg(ABSSrcReg).addImm(0));
7421
7422     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7423     BuildMI(BB, dl,
7424       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7425       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7426
7427     // insert rsbri in RSBBB
7428     // Note: BCC and rsbri will be converted into predicated rsbmi
7429     // by if-conversion pass
7430     BuildMI(*RSBBB, RSBBB->begin(), dl,
7431       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7432       .addReg(ABSSrcReg, RegState::Kill)
7433       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7434
7435     // insert PHI in SinkBB,
7436     // reuse ABSDstReg to not change uses of ABS instruction
7437     BuildMI(*SinkBB, SinkBB->begin(), dl,
7438       TII->get(ARM::PHI), ABSDstReg)
7439       .addReg(NewRsbDstReg).addMBB(RSBBB)
7440       .addReg(ABSSrcReg).addMBB(BB);
7441
7442     // remove ABS instruction
7443     MI->eraseFromParent();
7444
7445     // return last added BB
7446     return SinkBB;
7447   }
7448   case ARM::COPY_STRUCT_BYVAL_I32:
7449     ++NumLoopByVals;
7450     return EmitStructByval(MI, BB);
7451   case ARM::WIN__CHKSTK:
7452     return EmitLowered__chkstk(MI, BB);
7453   }
7454 }
7455
7456 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
7457                                                       SDNode *Node) const {
7458   if (!MI->hasPostISelHook()) {
7459     assert(!convertAddSubFlagsOpcode(MI->getOpcode()) &&
7460            "Pseudo flag-setting opcodes must be marked with 'hasPostISelHook'");
7461     return;
7462   }
7463
7464   const MCInstrDesc *MCID = &MI->getDesc();
7465   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
7466   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
7467   // operand is still set to noreg. If needed, set the optional operand's
7468   // register to CPSR, and remove the redundant implicit def.
7469   //
7470   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
7471
7472   // Rename pseudo opcodes.
7473   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
7474   if (NewOpc) {
7475     const ARMBaseInstrInfo *TII =
7476       static_cast<const ARMBaseInstrInfo*>(getTargetMachine().getInstrInfo());
7477     MCID = &TII->get(NewOpc);
7478
7479     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
7480            "converted opcode should be the same except for cc_out");
7481
7482     MI->setDesc(*MCID);
7483
7484     // Add the optional cc_out operand
7485     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
7486   }
7487   unsigned ccOutIdx = MCID->getNumOperands() - 1;
7488
7489   // Any ARM instruction that sets the 's' bit should specify an optional
7490   // "cc_out" operand in the last operand position.
7491   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
7492     assert(!NewOpc && "Optional cc_out operand required");
7493     return;
7494   }
7495   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
7496   // since we already have an optional CPSR def.
7497   bool definesCPSR = false;
7498   bool deadCPSR = false;
7499   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
7500        i != e; ++i) {
7501     const MachineOperand &MO = MI->getOperand(i);
7502     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
7503       definesCPSR = true;
7504       if (MO.isDead())
7505         deadCPSR = true;
7506       MI->RemoveOperand(i);
7507       break;
7508     }
7509   }
7510   if (!definesCPSR) {
7511     assert(!NewOpc && "Optional cc_out operand required");
7512     return;
7513   }
7514   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
7515   if (deadCPSR) {
7516     assert(!MI->getOperand(ccOutIdx).getReg() &&
7517            "expect uninitialized optional cc_out operand");
7518     return;
7519   }
7520
7521   // If this instruction was defined with an optional CPSR def and its dag node
7522   // had a live implicit CPSR def, then activate the optional CPSR def.
7523   MachineOperand &MO = MI->getOperand(ccOutIdx);
7524   MO.setReg(ARM::CPSR);
7525   MO.setIsDef(true);
7526 }
7527
7528 //===----------------------------------------------------------------------===//
7529 //                           ARM Optimization Hooks
7530 //===----------------------------------------------------------------------===//
7531
7532 // Helper function that checks if N is a null or all ones constant.
7533 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
7534   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
7535   if (!C)
7536     return false;
7537   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
7538 }
7539
7540 // Return true if N is conditionally 0 or all ones.
7541 // Detects these expressions where cc is an i1 value:
7542 //
7543 //   (select cc 0, y)   [AllOnes=0]
7544 //   (select cc y, 0)   [AllOnes=0]
7545 //   (zext cc)          [AllOnes=0]
7546 //   (sext cc)          [AllOnes=0/1]
7547 //   (select cc -1, y)  [AllOnes=1]
7548 //   (select cc y, -1)  [AllOnes=1]
7549 //
7550 // Invert is set when N is the null/all ones constant when CC is false.
7551 // OtherOp is set to the alternative value of N.
7552 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
7553                                        SDValue &CC, bool &Invert,
7554                                        SDValue &OtherOp,
7555                                        SelectionDAG &DAG) {
7556   switch (N->getOpcode()) {
7557   default: return false;
7558   case ISD::SELECT: {
7559     CC = N->getOperand(0);
7560     SDValue N1 = N->getOperand(1);
7561     SDValue N2 = N->getOperand(2);
7562     if (isZeroOrAllOnes(N1, AllOnes)) {
7563       Invert = false;
7564       OtherOp = N2;
7565       return true;
7566     }
7567     if (isZeroOrAllOnes(N2, AllOnes)) {
7568       Invert = true;
7569       OtherOp = N1;
7570       return true;
7571     }
7572     return false;
7573   }
7574   case ISD::ZERO_EXTEND:
7575     // (zext cc) can never be the all ones value.
7576     if (AllOnes)
7577       return false;
7578     // Fall through.
7579   case ISD::SIGN_EXTEND: {
7580     EVT VT = N->getValueType(0);
7581     CC = N->getOperand(0);
7582     if (CC.getValueType() != MVT::i1)
7583       return false;
7584     Invert = !AllOnes;
7585     if (AllOnes)
7586       // When looking for an AllOnes constant, N is an sext, and the 'other'
7587       // value is 0.
7588       OtherOp = DAG.getConstant(0, VT);
7589     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7590       // When looking for a 0 constant, N can be zext or sext.
7591       OtherOp = DAG.getConstant(1, VT);
7592     else
7593       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
7594     return true;
7595   }
7596   }
7597 }
7598
7599 // Combine a constant select operand into its use:
7600 //
7601 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
7602 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
7603 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
7604 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
7605 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
7606 //
7607 // The transform is rejected if the select doesn't have a constant operand that
7608 // is null, or all ones when AllOnes is set.
7609 //
7610 // Also recognize sext/zext from i1:
7611 //
7612 //   (add (zext cc), x) -> (select cc (add x, 1), x)
7613 //   (add (sext cc), x) -> (select cc (add x, -1), x)
7614 //
7615 // These transformations eventually create predicated instructions.
7616 //
7617 // @param N       The node to transform.
7618 // @param Slct    The N operand that is a select.
7619 // @param OtherOp The other N operand (x above).
7620 // @param DCI     Context.
7621 // @param AllOnes Require the select constant to be all ones instead of null.
7622 // @returns The new node, or SDValue() on failure.
7623 static
7624 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
7625                             TargetLowering::DAGCombinerInfo &DCI,
7626                             bool AllOnes = false) {
7627   SelectionDAG &DAG = DCI.DAG;
7628   EVT VT = N->getValueType(0);
7629   SDValue NonConstantVal;
7630   SDValue CCOp;
7631   bool SwapSelectOps;
7632   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
7633                                   NonConstantVal, DAG))
7634     return SDValue();
7635
7636   // Slct is now know to be the desired identity constant when CC is true.
7637   SDValue TrueVal = OtherOp;
7638   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
7639                                  OtherOp, NonConstantVal);
7640   // Unless SwapSelectOps says CC should be false.
7641   if (SwapSelectOps)
7642     std::swap(TrueVal, FalseVal);
7643
7644   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
7645                      CCOp, TrueVal, FalseVal);
7646 }
7647
7648 // Attempt combineSelectAndUse on each operand of a commutative operator N.
7649 static
7650 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
7651                                        TargetLowering::DAGCombinerInfo &DCI) {
7652   SDValue N0 = N->getOperand(0);
7653   SDValue N1 = N->getOperand(1);
7654   if (N0.getNode()->hasOneUse()) {
7655     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
7656     if (Result.getNode())
7657       return Result;
7658   }
7659   if (N1.getNode()->hasOneUse()) {
7660     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
7661     if (Result.getNode())
7662       return Result;
7663   }
7664   return SDValue();
7665 }
7666
7667 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
7668 // (only after legalization).
7669 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
7670                                  TargetLowering::DAGCombinerInfo &DCI,
7671                                  const ARMSubtarget *Subtarget) {
7672
7673   // Only perform optimization if after legalize, and if NEON is available. We
7674   // also expected both operands to be BUILD_VECTORs.
7675   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
7676       || N0.getOpcode() != ISD::BUILD_VECTOR
7677       || N1.getOpcode() != ISD::BUILD_VECTOR)
7678     return SDValue();
7679
7680   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
7681   EVT VT = N->getValueType(0);
7682   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
7683     return SDValue();
7684
7685   // Check that the vector operands are of the right form.
7686   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
7687   // operands, where N is the size of the formed vector.
7688   // Each EXTRACT_VECTOR should have the same input vector and odd or even
7689   // index such that we have a pair wise add pattern.
7690
7691   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
7692   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7693     return SDValue();
7694   SDValue Vec = N0->getOperand(0)->getOperand(0);
7695   SDNode *V = Vec.getNode();
7696   unsigned nextIndex = 0;
7697
7698   // For each operands to the ADD which are BUILD_VECTORs,
7699   // check to see if each of their operands are an EXTRACT_VECTOR with
7700   // the same vector and appropriate index.
7701   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
7702     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
7703         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7704
7705       SDValue ExtVec0 = N0->getOperand(i);
7706       SDValue ExtVec1 = N1->getOperand(i);
7707
7708       // First operand is the vector, verify its the same.
7709       if (V != ExtVec0->getOperand(0).getNode() ||
7710           V != ExtVec1->getOperand(0).getNode())
7711         return SDValue();
7712
7713       // Second is the constant, verify its correct.
7714       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
7715       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
7716
7717       // For the constant, we want to see all the even or all the odd.
7718       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
7719           || C1->getZExtValue() != nextIndex+1)
7720         return SDValue();
7721
7722       // Increment index.
7723       nextIndex+=2;
7724     } else
7725       return SDValue();
7726   }
7727
7728   // Create VPADDL node.
7729   SelectionDAG &DAG = DCI.DAG;
7730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7731
7732   // Build operand list.
7733   SmallVector<SDValue, 8> Ops;
7734   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls,
7735                                 TLI.getPointerTy()));
7736
7737   // Input is the vector.
7738   Ops.push_back(Vec);
7739
7740   // Get widened type and narrowed type.
7741   MVT widenType;
7742   unsigned numElem = VT.getVectorNumElements();
7743   
7744   EVT inputLaneType = Vec.getValueType().getVectorElementType();
7745   switch (inputLaneType.getSimpleVT().SimpleTy) {
7746     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
7747     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
7748     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
7749     default:
7750       llvm_unreachable("Invalid vector element type for padd optimization.");
7751   }
7752
7753   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), widenType, Ops);
7754   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
7755   return DAG.getNode(ExtOp, SDLoc(N), VT, tmp);
7756 }
7757
7758 static SDValue findMUL_LOHI(SDValue V) {
7759   if (V->getOpcode() == ISD::UMUL_LOHI ||
7760       V->getOpcode() == ISD::SMUL_LOHI)
7761     return V;
7762   return SDValue();
7763 }
7764
7765 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
7766                                      TargetLowering::DAGCombinerInfo &DCI,
7767                                      const ARMSubtarget *Subtarget) {
7768
7769   if (Subtarget->isThumb1Only()) return SDValue();
7770
7771   // Only perform the checks after legalize when the pattern is available.
7772   if (DCI.isBeforeLegalize()) return SDValue();
7773
7774   // Look for multiply add opportunities.
7775   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
7776   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
7777   // a glue link from the first add to the second add.
7778   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
7779   // a S/UMLAL instruction.
7780   //          loAdd   UMUL_LOHI
7781   //            \    / :lo    \ :hi
7782   //             \  /          \          [no multiline comment]
7783   //              ADDC         |  hiAdd
7784   //                 \ :glue  /  /
7785   //                  \      /  /
7786   //                    ADDE
7787   //
7788   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
7789   SDValue AddcOp0 = AddcNode->getOperand(0);
7790   SDValue AddcOp1 = AddcNode->getOperand(1);
7791
7792   // Check if the two operands are from the same mul_lohi node.
7793   if (AddcOp0.getNode() == AddcOp1.getNode())
7794     return SDValue();
7795
7796   assert(AddcNode->getNumValues() == 2 &&
7797          AddcNode->getValueType(0) == MVT::i32 &&
7798          "Expect ADDC with two result values. First: i32");
7799
7800   // Check that we have a glued ADDC node.
7801   if (AddcNode->getValueType(1) != MVT::Glue)
7802     return SDValue();
7803
7804   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
7805   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
7806       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
7807       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
7808       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
7809     return SDValue();
7810
7811   // Look for the glued ADDE.
7812   SDNode* AddeNode = AddcNode->getGluedUser();
7813   if (!AddeNode)
7814     return SDValue();
7815
7816   // Make sure it is really an ADDE.
7817   if (AddeNode->getOpcode() != ISD::ADDE)
7818     return SDValue();
7819
7820   assert(AddeNode->getNumOperands() == 3 &&
7821          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
7822          "ADDE node has the wrong inputs");
7823
7824   // Check for the triangle shape.
7825   SDValue AddeOp0 = AddeNode->getOperand(0);
7826   SDValue AddeOp1 = AddeNode->getOperand(1);
7827
7828   // Make sure that the ADDE operands are not coming from the same node.
7829   if (AddeOp0.getNode() == AddeOp1.getNode())
7830     return SDValue();
7831
7832   // Find the MUL_LOHI node walking up ADDE's operands.
7833   bool IsLeftOperandMUL = false;
7834   SDValue MULOp = findMUL_LOHI(AddeOp0);
7835   if (MULOp == SDValue())
7836    MULOp = findMUL_LOHI(AddeOp1);
7837   else
7838     IsLeftOperandMUL = true;
7839   if (MULOp == SDValue())
7840      return SDValue();
7841
7842   // Figure out the right opcode.
7843   unsigned Opc = MULOp->getOpcode();
7844   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
7845
7846   // Figure out the high and low input values to the MLAL node.
7847   SDValue* HiMul = &MULOp;
7848   SDValue* HiAdd = nullptr;
7849   SDValue* LoMul = nullptr;
7850   SDValue* LowAdd = nullptr;
7851
7852   if (IsLeftOperandMUL)
7853     HiAdd = &AddeOp1;
7854   else
7855     HiAdd = &AddeOp0;
7856
7857
7858   if (AddcOp0->getOpcode() == Opc) {
7859     LoMul = &AddcOp0;
7860     LowAdd = &AddcOp1;
7861   }
7862   if (AddcOp1->getOpcode() == Opc) {
7863     LoMul = &AddcOp1;
7864     LowAdd = &AddcOp0;
7865   }
7866
7867   if (!LoMul)
7868     return SDValue();
7869
7870   if (LoMul->getNode() != HiMul->getNode())
7871     return SDValue();
7872
7873   // Create the merged node.
7874   SelectionDAG &DAG = DCI.DAG;
7875
7876   // Build operand list.
7877   SmallVector<SDValue, 8> Ops;
7878   Ops.push_back(LoMul->getOperand(0));
7879   Ops.push_back(LoMul->getOperand(1));
7880   Ops.push_back(*LowAdd);
7881   Ops.push_back(*HiAdd);
7882
7883   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
7884                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
7885
7886   // Replace the ADDs' nodes uses by the MLA node's values.
7887   SDValue HiMLALResult(MLALNode.getNode(), 1);
7888   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
7889
7890   SDValue LoMLALResult(MLALNode.getNode(), 0);
7891   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
7892
7893   // Return original node to notify the driver to stop replacing.
7894   SDValue resNode(AddcNode, 0);
7895   return resNode;
7896 }
7897
7898 /// PerformADDCCombine - Target-specific dag combine transform from
7899 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
7900 static SDValue PerformADDCCombine(SDNode *N,
7901                                  TargetLowering::DAGCombinerInfo &DCI,
7902                                  const ARMSubtarget *Subtarget) {
7903
7904   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
7905
7906 }
7907
7908 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
7909 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
7910 /// called with the default operands, and if that fails, with commuted
7911 /// operands.
7912 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
7913                                           TargetLowering::DAGCombinerInfo &DCI,
7914                                           const ARMSubtarget *Subtarget){
7915
7916   // Attempt to create vpaddl for this add.
7917   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
7918   if (Result.getNode())
7919     return Result;
7920
7921   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
7922   if (N0.getNode()->hasOneUse()) {
7923     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
7924     if (Result.getNode()) return Result;
7925   }
7926   return SDValue();
7927 }
7928
7929 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
7930 ///
7931 static SDValue PerformADDCombine(SDNode *N,
7932                                  TargetLowering::DAGCombinerInfo &DCI,
7933                                  const ARMSubtarget *Subtarget) {
7934   SDValue N0 = N->getOperand(0);
7935   SDValue N1 = N->getOperand(1);
7936
7937   // First try with the default operand order.
7938   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
7939   if (Result.getNode())
7940     return Result;
7941
7942   // If that didn't work, try again with the operands commuted.
7943   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
7944 }
7945
7946 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
7947 ///
7948 static SDValue PerformSUBCombine(SDNode *N,
7949                                  TargetLowering::DAGCombinerInfo &DCI) {
7950   SDValue N0 = N->getOperand(0);
7951   SDValue N1 = N->getOperand(1);
7952
7953   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
7954   if (N1.getNode()->hasOneUse()) {
7955     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
7956     if (Result.getNode()) return Result;
7957   }
7958
7959   return SDValue();
7960 }
7961
7962 /// PerformVMULCombine
7963 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
7964 /// special multiplier accumulator forwarding.
7965 ///   vmul d3, d0, d2
7966 ///   vmla d3, d1, d2
7967 /// is faster than
7968 ///   vadd d3, d0, d1
7969 ///   vmul d3, d3, d2
7970 //  However, for (A + B) * (A + B),
7971 //    vadd d2, d0, d1
7972 //    vmul d3, d0, d2
7973 //    vmla d3, d1, d2
7974 //  is slower than
7975 //    vadd d2, d0, d1
7976 //    vmul d3, d2, d2
7977 static SDValue PerformVMULCombine(SDNode *N,
7978                                   TargetLowering::DAGCombinerInfo &DCI,
7979                                   const ARMSubtarget *Subtarget) {
7980   if (!Subtarget->hasVMLxForwarding())
7981     return SDValue();
7982
7983   SelectionDAG &DAG = DCI.DAG;
7984   SDValue N0 = N->getOperand(0);
7985   SDValue N1 = N->getOperand(1);
7986   unsigned Opcode = N0.getOpcode();
7987   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7988       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
7989     Opcode = N1.getOpcode();
7990     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
7991         Opcode != ISD::FADD && Opcode != ISD::FSUB)
7992       return SDValue();
7993     std::swap(N0, N1);
7994   }
7995
7996   if (N0 == N1)
7997     return SDValue();
7998
7999   EVT VT = N->getValueType(0);
8000   SDLoc DL(N);
8001   SDValue N00 = N0->getOperand(0);
8002   SDValue N01 = N0->getOperand(1);
8003   return DAG.getNode(Opcode, DL, VT,
8004                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8005                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8006 }
8007
8008 static SDValue PerformMULCombine(SDNode *N,
8009                                  TargetLowering::DAGCombinerInfo &DCI,
8010                                  const ARMSubtarget *Subtarget) {
8011   SelectionDAG &DAG = DCI.DAG;
8012
8013   if (Subtarget->isThumb1Only())
8014     return SDValue();
8015
8016   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8017     return SDValue();
8018
8019   EVT VT = N->getValueType(0);
8020   if (VT.is64BitVector() || VT.is128BitVector())
8021     return PerformVMULCombine(N, DCI, Subtarget);
8022   if (VT != MVT::i32)
8023     return SDValue();
8024
8025   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8026   if (!C)
8027     return SDValue();
8028
8029   int64_t MulAmt = C->getSExtValue();
8030   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8031
8032   ShiftAmt = ShiftAmt & (32 - 1);
8033   SDValue V = N->getOperand(0);
8034   SDLoc DL(N);
8035
8036   SDValue Res;
8037   MulAmt >>= ShiftAmt;
8038
8039   if (MulAmt >= 0) {
8040     if (isPowerOf2_32(MulAmt - 1)) {
8041       // (mul x, 2^N + 1) => (add (shl x, N), x)
8042       Res = DAG.getNode(ISD::ADD, DL, VT,
8043                         V,
8044                         DAG.getNode(ISD::SHL, DL, VT,
8045                                     V,
8046                                     DAG.getConstant(Log2_32(MulAmt - 1),
8047                                                     MVT::i32)));
8048     } else if (isPowerOf2_32(MulAmt + 1)) {
8049       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8050       Res = DAG.getNode(ISD::SUB, DL, VT,
8051                         DAG.getNode(ISD::SHL, DL, VT,
8052                                     V,
8053                                     DAG.getConstant(Log2_32(MulAmt + 1),
8054                                                     MVT::i32)),
8055                         V);
8056     } else
8057       return SDValue();
8058   } else {
8059     uint64_t MulAmtAbs = -MulAmt;
8060     if (isPowerOf2_32(MulAmtAbs + 1)) {
8061       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8062       Res = DAG.getNode(ISD::SUB, DL, VT,
8063                         V,
8064                         DAG.getNode(ISD::SHL, DL, VT,
8065                                     V,
8066                                     DAG.getConstant(Log2_32(MulAmtAbs + 1),
8067                                                     MVT::i32)));
8068     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8069       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8070       Res = DAG.getNode(ISD::ADD, DL, VT,
8071                         V,
8072                         DAG.getNode(ISD::SHL, DL, VT,
8073                                     V,
8074                                     DAG.getConstant(Log2_32(MulAmtAbs-1),
8075                                                     MVT::i32)));
8076       Res = DAG.getNode(ISD::SUB, DL, VT,
8077                         DAG.getConstant(0, MVT::i32),Res);
8078
8079     } else
8080       return SDValue();
8081   }
8082
8083   if (ShiftAmt != 0)
8084     Res = DAG.getNode(ISD::SHL, DL, VT,
8085                       Res, DAG.getConstant(ShiftAmt, MVT::i32));
8086
8087   // Do not add new nodes to DAG combiner worklist.
8088   DCI.CombineTo(N, Res, false);
8089   return SDValue();
8090 }
8091
8092 static SDValue PerformANDCombine(SDNode *N,
8093                                  TargetLowering::DAGCombinerInfo &DCI,
8094                                  const ARMSubtarget *Subtarget) {
8095
8096   // Attempt to use immediate-form VBIC
8097   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8098   SDLoc dl(N);
8099   EVT VT = N->getValueType(0);
8100   SelectionDAG &DAG = DCI.DAG;
8101
8102   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8103     return SDValue();
8104
8105   APInt SplatBits, SplatUndef;
8106   unsigned SplatBitSize;
8107   bool HasAnyUndefs;
8108   if (BVN &&
8109       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8110     if (SplatBitSize <= 64) {
8111       EVT VbicVT;
8112       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8113                                       SplatUndef.getZExtValue(), SplatBitSize,
8114                                       DAG, VbicVT, VT.is128BitVector(),
8115                                       OtherModImm);
8116       if (Val.getNode()) {
8117         SDValue Input =
8118           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8119         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8120         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8121       }
8122     }
8123   }
8124
8125   if (!Subtarget->isThumb1Only()) {
8126     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8127     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8128     if (Result.getNode())
8129       return Result;
8130   }
8131
8132   return SDValue();
8133 }
8134
8135 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8136 static SDValue PerformORCombine(SDNode *N,
8137                                 TargetLowering::DAGCombinerInfo &DCI,
8138                                 const ARMSubtarget *Subtarget) {
8139   // Attempt to use immediate-form VORR
8140   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8141   SDLoc dl(N);
8142   EVT VT = N->getValueType(0);
8143   SelectionDAG &DAG = DCI.DAG;
8144
8145   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8146     return SDValue();
8147
8148   APInt SplatBits, SplatUndef;
8149   unsigned SplatBitSize;
8150   bool HasAnyUndefs;
8151   if (BVN && Subtarget->hasNEON() &&
8152       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8153     if (SplatBitSize <= 64) {
8154       EVT VorrVT;
8155       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8156                                       SplatUndef.getZExtValue(), SplatBitSize,
8157                                       DAG, VorrVT, VT.is128BitVector(),
8158                                       OtherModImm);
8159       if (Val.getNode()) {
8160         SDValue Input =
8161           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8162         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8163         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8164       }
8165     }
8166   }
8167
8168   if (!Subtarget->isThumb1Only()) {
8169     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8170     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8171     if (Result.getNode())
8172       return Result;
8173   }
8174
8175   // The code below optimizes (or (and X, Y), Z).
8176   // The AND operand needs to have a single user to make these optimizations
8177   // profitable.
8178   SDValue N0 = N->getOperand(0);
8179   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8180     return SDValue();
8181   SDValue N1 = N->getOperand(1);
8182
8183   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8184   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8185       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8186     APInt SplatUndef;
8187     unsigned SplatBitSize;
8188     bool HasAnyUndefs;
8189
8190     APInt SplatBits0, SplatBits1;
8191     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8192     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8193     // Ensure that the second operand of both ands are constants
8194     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8195                                       HasAnyUndefs) && !HasAnyUndefs) {
8196         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8197                                           HasAnyUndefs) && !HasAnyUndefs) {
8198             // Ensure that the bit width of the constants are the same and that
8199             // the splat arguments are logical inverses as per the pattern we
8200             // are trying to simplify.
8201             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8202                 SplatBits0 == ~SplatBits1) {
8203                 // Canonicalize the vector type to make instruction selection
8204                 // simpler.
8205                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8206                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8207                                              N0->getOperand(1),
8208                                              N0->getOperand(0),
8209                                              N1->getOperand(0));
8210                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8211             }
8212         }
8213     }
8214   }
8215
8216   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8217   // reasonable.
8218
8219   // BFI is only available on V6T2+
8220   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8221     return SDValue();
8222
8223   SDLoc DL(N);
8224   // 1) or (and A, mask), val => ARMbfi A, val, mask
8225   //      iff (val & mask) == val
8226   //
8227   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8228   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8229   //          && mask == ~mask2
8230   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8231   //          && ~mask == mask2
8232   //  (i.e., copy a bitfield value into another bitfield of the same width)
8233
8234   if (VT != MVT::i32)
8235     return SDValue();
8236
8237   SDValue N00 = N0.getOperand(0);
8238
8239   // The value and the mask need to be constants so we can verify this is
8240   // actually a bitfield set. If the mask is 0xffff, we can do better
8241   // via a movt instruction, so don't use BFI in that case.
8242   SDValue MaskOp = N0.getOperand(1);
8243   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8244   if (!MaskC)
8245     return SDValue();
8246   unsigned Mask = MaskC->getZExtValue();
8247   if (Mask == 0xffff)
8248     return SDValue();
8249   SDValue Res;
8250   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8251   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8252   if (N1C) {
8253     unsigned Val = N1C->getZExtValue();
8254     if ((Val & ~Mask) != Val)
8255       return SDValue();
8256
8257     if (ARM::isBitFieldInvertedMask(Mask)) {
8258       Val >>= countTrailingZeros(~Mask);
8259
8260       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8261                         DAG.getConstant(Val, MVT::i32),
8262                         DAG.getConstant(Mask, MVT::i32));
8263
8264       // Do not add new nodes to DAG combiner worklist.
8265       DCI.CombineTo(N, Res, false);
8266       return SDValue();
8267     }
8268   } else if (N1.getOpcode() == ISD::AND) {
8269     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8270     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8271     if (!N11C)
8272       return SDValue();
8273     unsigned Mask2 = N11C->getZExtValue();
8274
8275     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8276     // as is to match.
8277     if (ARM::isBitFieldInvertedMask(Mask) &&
8278         (Mask == ~Mask2)) {
8279       // The pack halfword instruction works better for masks that fit it,
8280       // so use that when it's available.
8281       if (Subtarget->hasT2ExtractPack() &&
8282           (Mask == 0xffff || Mask == 0xffff0000))
8283         return SDValue();
8284       // 2a
8285       unsigned amt = countTrailingZeros(Mask2);
8286       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8287                         DAG.getConstant(amt, MVT::i32));
8288       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8289                         DAG.getConstant(Mask, MVT::i32));
8290       // Do not add new nodes to DAG combiner worklist.
8291       DCI.CombineTo(N, Res, false);
8292       return SDValue();
8293     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8294                (~Mask == Mask2)) {
8295       // The pack halfword instruction works better for masks that fit it,
8296       // so use that when it's available.
8297       if (Subtarget->hasT2ExtractPack() &&
8298           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8299         return SDValue();
8300       // 2b
8301       unsigned lsb = countTrailingZeros(Mask);
8302       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8303                         DAG.getConstant(lsb, MVT::i32));
8304       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8305                         DAG.getConstant(Mask2, MVT::i32));
8306       // Do not add new nodes to DAG combiner worklist.
8307       DCI.CombineTo(N, Res, false);
8308       return SDValue();
8309     }
8310   }
8311
8312   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8313       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8314       ARM::isBitFieldInvertedMask(~Mask)) {
8315     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8316     // where lsb(mask) == #shamt and masked bits of B are known zero.
8317     SDValue ShAmt = N00.getOperand(1);
8318     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8319     unsigned LSB = countTrailingZeros(Mask);
8320     if (ShAmtC != LSB)
8321       return SDValue();
8322
8323     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8324                       DAG.getConstant(~Mask, MVT::i32));
8325
8326     // Do not add new nodes to DAG combiner worklist.
8327     DCI.CombineTo(N, Res, false);
8328   }
8329
8330   return SDValue();
8331 }
8332
8333 static SDValue PerformXORCombine(SDNode *N,
8334                                  TargetLowering::DAGCombinerInfo &DCI,
8335                                  const ARMSubtarget *Subtarget) {
8336   EVT VT = N->getValueType(0);
8337   SelectionDAG &DAG = DCI.DAG;
8338
8339   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8340     return SDValue();
8341
8342   if (!Subtarget->isThumb1Only()) {
8343     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8344     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8345     if (Result.getNode())
8346       return Result;
8347   }
8348
8349   return SDValue();
8350 }
8351
8352 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8353 /// the bits being cleared by the AND are not demanded by the BFI.
8354 static SDValue PerformBFICombine(SDNode *N,
8355                                  TargetLowering::DAGCombinerInfo &DCI) {
8356   SDValue N1 = N->getOperand(1);
8357   if (N1.getOpcode() == ISD::AND) {
8358     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8359     if (!N11C)
8360       return SDValue();
8361     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8362     unsigned LSB = countTrailingZeros(~InvMask);
8363     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8364     unsigned Mask = (1 << Width)-1;
8365     unsigned Mask2 = N11C->getZExtValue();
8366     if ((Mask & (~Mask2)) == 0)
8367       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8368                              N->getOperand(0), N1.getOperand(0),
8369                              N->getOperand(2));
8370   }
8371   return SDValue();
8372 }
8373
8374 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8375 /// ARMISD::VMOVRRD.
8376 static SDValue PerformVMOVRRDCombine(SDNode *N,
8377                                      TargetLowering::DAGCombinerInfo &DCI) {
8378   // vmovrrd(vmovdrr x, y) -> x,y
8379   SDValue InDouble = N->getOperand(0);
8380   if (InDouble.getOpcode() == ARMISD::VMOVDRR)
8381     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8382
8383   // vmovrrd(load f64) -> (load i32), (load i32)
8384   SDNode *InNode = InDouble.getNode();
8385   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8386       InNode->getValueType(0) == MVT::f64 &&
8387       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8388       !cast<LoadSDNode>(InNode)->isVolatile()) {
8389     // TODO: Should this be done for non-FrameIndex operands?
8390     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8391
8392     SelectionDAG &DAG = DCI.DAG;
8393     SDLoc DL(LD);
8394     SDValue BasePtr = LD->getBasePtr();
8395     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8396                                  LD->getPointerInfo(), LD->isVolatile(),
8397                                  LD->isNonTemporal(), LD->isInvariant(),
8398                                  LD->getAlignment());
8399
8400     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8401                                     DAG.getConstant(4, MVT::i32));
8402     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8403                                  LD->getPointerInfo(), LD->isVolatile(),
8404                                  LD->isNonTemporal(), LD->isInvariant(),
8405                                  std::min(4U, LD->getAlignment() / 2));
8406
8407     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8408     if (DCI.DAG.getTargetLoweringInfo().isBigEndian())
8409       std::swap (NewLD1, NewLD2);
8410     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8411     DCI.RemoveFromWorklist(LD);
8412     DAG.DeleteNode(LD);
8413     return Result;
8414   }
8415
8416   return SDValue();
8417 }
8418
8419 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8420 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8421 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8422   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8423   SDValue Op0 = N->getOperand(0);
8424   SDValue Op1 = N->getOperand(1);
8425   if (Op0.getOpcode() == ISD::BITCAST)
8426     Op0 = Op0.getOperand(0);
8427   if (Op1.getOpcode() == ISD::BITCAST)
8428     Op1 = Op1.getOperand(0);
8429   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8430       Op0.getNode() == Op1.getNode() &&
8431       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8432     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8433                        N->getValueType(0), Op0.getOperand(0));
8434   return SDValue();
8435 }
8436
8437 /// PerformSTORECombine - Target-specific dag combine xforms for
8438 /// ISD::STORE.
8439 static SDValue PerformSTORECombine(SDNode *N,
8440                                    TargetLowering::DAGCombinerInfo &DCI) {
8441   StoreSDNode *St = cast<StoreSDNode>(N);
8442   if (St->isVolatile())
8443     return SDValue();
8444
8445   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
8446   // pack all of the elements in one place.  Next, store to memory in fewer
8447   // chunks.
8448   SDValue StVal = St->getValue();
8449   EVT VT = StVal.getValueType();
8450   if (St->isTruncatingStore() && VT.isVector()) {
8451     SelectionDAG &DAG = DCI.DAG;
8452     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8453     EVT StVT = St->getMemoryVT();
8454     unsigned NumElems = VT.getVectorNumElements();
8455     assert(StVT != VT && "Cannot truncate to the same type");
8456     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
8457     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
8458
8459     // From, To sizes and ElemCount must be pow of two
8460     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
8461
8462     // We are going to use the original vector elt for storing.
8463     // Accumulated smaller vector elements must be a multiple of the store size.
8464     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
8465
8466     unsigned SizeRatio  = FromEltSz / ToEltSz;
8467     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
8468
8469     // Create a type on which we perform the shuffle.
8470     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
8471                                      NumElems*SizeRatio);
8472     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
8473
8474     SDLoc DL(St);
8475     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
8476     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
8477     for (unsigned i = 0; i < NumElems; ++i)
8478       ShuffleVec[i] = TLI.isBigEndian() ? (i+1) * SizeRatio - 1 : i * SizeRatio;
8479
8480     // Can't shuffle using an illegal type.
8481     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
8482
8483     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
8484                                 DAG.getUNDEF(WideVec.getValueType()),
8485                                 ShuffleVec.data());
8486     // At this point all of the data is stored at the bottom of the
8487     // register. We now need to save it to mem.
8488
8489     // Find the largest store unit
8490     MVT StoreType = MVT::i8;
8491     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
8492          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
8493       MVT Tp = (MVT::SimpleValueType)tp;
8494       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
8495         StoreType = Tp;
8496     }
8497     // Didn't find a legal store type.
8498     if (!TLI.isTypeLegal(StoreType))
8499       return SDValue();
8500
8501     // Bitcast the original vector into a vector of store-size units
8502     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
8503             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
8504     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
8505     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
8506     SmallVector<SDValue, 8> Chains;
8507     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
8508                                         TLI.getPointerTy());
8509     SDValue BasePtr = St->getBasePtr();
8510
8511     // Perform one or more big stores into memory.
8512     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
8513     for (unsigned I = 0; I < E; I++) {
8514       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
8515                                    StoreType, ShuffWide,
8516                                    DAG.getIntPtrConstant(I));
8517       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
8518                                 St->getPointerInfo(), St->isVolatile(),
8519                                 St->isNonTemporal(), St->getAlignment());
8520       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
8521                             Increment);
8522       Chains.push_back(Ch);
8523     }
8524     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
8525   }
8526
8527   if (!ISD::isNormalStore(St))
8528     return SDValue();
8529
8530   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
8531   // ARM stores of arguments in the same cache line.
8532   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
8533       StVal.getNode()->hasOneUse()) {
8534     SelectionDAG  &DAG = DCI.DAG;
8535     bool isBigEndian = DAG.getTargetLoweringInfo().isBigEndian();
8536     SDLoc DL(St);
8537     SDValue BasePtr = St->getBasePtr();
8538     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
8539                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
8540                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
8541                                   St->isNonTemporal(), St->getAlignment());
8542
8543     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8544                                     DAG.getConstant(4, MVT::i32));
8545     return DAG.getStore(NewST1.getValue(0), DL,
8546                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
8547                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
8548                         St->isNonTemporal(),
8549                         std::min(4U, St->getAlignment() / 2));
8550   }
8551
8552   if (StVal.getValueType() != MVT::i64 ||
8553       StVal.getNode()->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8554     return SDValue();
8555
8556   // Bitcast an i64 store extracted from a vector to f64.
8557   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8558   SelectionDAG &DAG = DCI.DAG;
8559   SDLoc dl(StVal);
8560   SDValue IntVec = StVal.getOperand(0);
8561   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8562                                  IntVec.getValueType().getVectorNumElements());
8563   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
8564   SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
8565                                Vec, StVal.getOperand(1));
8566   dl = SDLoc(N);
8567   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
8568   // Make the DAGCombiner fold the bitcasts.
8569   DCI.AddToWorklist(Vec.getNode());
8570   DCI.AddToWorklist(ExtElt.getNode());
8571   DCI.AddToWorklist(V.getNode());
8572   return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
8573                       St->getPointerInfo(), St->isVolatile(),
8574                       St->isNonTemporal(), St->getAlignment(),
8575                       St->getTBAAInfo());
8576 }
8577
8578 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8579 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8580 /// i64 vector to have f64 elements, since the value can then be loaded
8581 /// directly into a VFP register.
8582 static bool hasNormalLoadOperand(SDNode *N) {
8583   unsigned NumElts = N->getValueType(0).getVectorNumElements();
8584   for (unsigned i = 0; i < NumElts; ++i) {
8585     SDNode *Elt = N->getOperand(i).getNode();
8586     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
8587       return true;
8588   }
8589   return false;
8590 }
8591
8592 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
8593 /// ISD::BUILD_VECTOR.
8594 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
8595                                           TargetLowering::DAGCombinerInfo &DCI){
8596   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
8597   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
8598   // into a pair of GPRs, which is fine when the value is used as a scalar,
8599   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
8600   SelectionDAG &DAG = DCI.DAG;
8601   if (N->getNumOperands() == 2) {
8602     SDValue RV = PerformVMOVDRRCombine(N, DAG);
8603     if (RV.getNode())
8604       return RV;
8605   }
8606
8607   // Load i64 elements as f64 values so that type legalization does not split
8608   // them up into i32 values.
8609   EVT VT = N->getValueType(0);
8610   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
8611     return SDValue();
8612   SDLoc dl(N);
8613   SmallVector<SDValue, 8> Ops;
8614   unsigned NumElts = VT.getVectorNumElements();
8615   for (unsigned i = 0; i < NumElts; ++i) {
8616     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
8617     Ops.push_back(V);
8618     // Make the DAGCombiner fold the bitcast.
8619     DCI.AddToWorklist(V.getNode());
8620   }
8621   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
8622   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
8623   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8624 }
8625
8626 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
8627 static SDValue
8628 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8629   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
8630   // At that time, we may have inserted bitcasts from integer to float.
8631   // If these bitcasts have survived DAGCombine, change the lowering of this
8632   // BUILD_VECTOR in something more vector friendly, i.e., that does not
8633   // force to use floating point types.
8634
8635   // Make sure we can change the type of the vector.
8636   // This is possible iff:
8637   // 1. The vector is only used in a bitcast to a integer type. I.e.,
8638   //    1.1. Vector is used only once.
8639   //    1.2. Use is a bit convert to an integer type.
8640   // 2. The size of its operands are 32-bits (64-bits are not legal).
8641   EVT VT = N->getValueType(0);
8642   EVT EltVT = VT.getVectorElementType();
8643
8644   // Check 1.1. and 2.
8645   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
8646     return SDValue();
8647
8648   // By construction, the input type must be float.
8649   assert(EltVT == MVT::f32 && "Unexpected type!");
8650
8651   // Check 1.2.
8652   SDNode *Use = *N->use_begin();
8653   if (Use->getOpcode() != ISD::BITCAST ||
8654       Use->getValueType(0).isFloatingPoint())
8655     return SDValue();
8656
8657   // Check profitability.
8658   // Model is, if more than half of the relevant operands are bitcast from
8659   // i32, turn the build_vector into a sequence of insert_vector_elt.
8660   // Relevant operands are everything that is not statically
8661   // (i.e., at compile time) bitcasted.
8662   unsigned NumOfBitCastedElts = 0;
8663   unsigned NumElts = VT.getVectorNumElements();
8664   unsigned NumOfRelevantElts = NumElts;
8665   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
8666     SDValue Elt = N->getOperand(Idx);
8667     if (Elt->getOpcode() == ISD::BITCAST) {
8668       // Assume only bit cast to i32 will go away.
8669       if (Elt->getOperand(0).getValueType() == MVT::i32)
8670         ++NumOfBitCastedElts;
8671     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
8672       // Constants are statically casted, thus do not count them as
8673       // relevant operands.
8674       --NumOfRelevantElts;
8675   }
8676
8677   // Check if more than half of the elements require a non-free bitcast.
8678   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
8679     return SDValue();
8680
8681   SelectionDAG &DAG = DCI.DAG;
8682   // Create the new vector type.
8683   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
8684   // Check if the type is legal.
8685   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8686   if (!TLI.isTypeLegal(VecVT))
8687     return SDValue();
8688
8689   // Combine:
8690   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
8691   // => BITCAST INSERT_VECTOR_ELT
8692   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
8693   //                      (BITCAST EN), N.
8694   SDValue Vec = DAG.getUNDEF(VecVT);
8695   SDLoc dl(N);
8696   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
8697     SDValue V = N->getOperand(Idx);
8698     if (V.getOpcode() == ISD::UNDEF)
8699       continue;
8700     if (V.getOpcode() == ISD::BITCAST &&
8701         V->getOperand(0).getValueType() == MVT::i32)
8702       // Fold obvious case.
8703       V = V.getOperand(0);
8704     else {
8705       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
8706       // Make the DAGCombiner fold the bitcasts.
8707       DCI.AddToWorklist(V.getNode());
8708     }
8709     SDValue LaneIdx = DAG.getConstant(Idx, MVT::i32);
8710     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
8711   }
8712   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
8713   // Make the DAGCombiner fold the bitcasts.
8714   DCI.AddToWorklist(Vec.getNode());
8715   return Vec;
8716 }
8717
8718 /// PerformInsertEltCombine - Target-specific dag combine xforms for
8719 /// ISD::INSERT_VECTOR_ELT.
8720 static SDValue PerformInsertEltCombine(SDNode *N,
8721                                        TargetLowering::DAGCombinerInfo &DCI) {
8722   // Bitcast an i64 load inserted into a vector to f64.
8723   // Otherwise, the i64 value will be legalized to a pair of i32 values.
8724   EVT VT = N->getValueType(0);
8725   SDNode *Elt = N->getOperand(1).getNode();
8726   if (VT.getVectorElementType() != MVT::i64 ||
8727       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
8728     return SDValue();
8729
8730   SelectionDAG &DAG = DCI.DAG;
8731   SDLoc dl(N);
8732   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
8733                                  VT.getVectorNumElements());
8734   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
8735   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
8736   // Make the DAGCombiner fold the bitcasts.
8737   DCI.AddToWorklist(Vec.getNode());
8738   DCI.AddToWorklist(V.getNode());
8739   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
8740                                Vec, V, N->getOperand(2));
8741   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
8742 }
8743
8744 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
8745 /// ISD::VECTOR_SHUFFLE.
8746 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
8747   // The LLVM shufflevector instruction does not require the shuffle mask
8748   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
8749   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
8750   // operands do not match the mask length, they are extended by concatenating
8751   // them with undef vectors.  That is probably the right thing for other
8752   // targets, but for NEON it is better to concatenate two double-register
8753   // size vector operands into a single quad-register size vector.  Do that
8754   // transformation here:
8755   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
8756   //   shuffle(concat(v1, v2), undef)
8757   SDValue Op0 = N->getOperand(0);
8758   SDValue Op1 = N->getOperand(1);
8759   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
8760       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
8761       Op0.getNumOperands() != 2 ||
8762       Op1.getNumOperands() != 2)
8763     return SDValue();
8764   SDValue Concat0Op1 = Op0.getOperand(1);
8765   SDValue Concat1Op1 = Op1.getOperand(1);
8766   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
8767       Concat1Op1.getOpcode() != ISD::UNDEF)
8768     return SDValue();
8769   // Skip the transformation if any of the types are illegal.
8770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8771   EVT VT = N->getValueType(0);
8772   if (!TLI.isTypeLegal(VT) ||
8773       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
8774       !TLI.isTypeLegal(Concat1Op1.getValueType()))
8775     return SDValue();
8776
8777   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
8778                                   Op0.getOperand(0), Op1.getOperand(0));
8779   // Translate the shuffle mask.
8780   SmallVector<int, 16> NewMask;
8781   unsigned NumElts = VT.getVectorNumElements();
8782   unsigned HalfElts = NumElts/2;
8783   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8784   for (unsigned n = 0; n < NumElts; ++n) {
8785     int MaskElt = SVN->getMaskElt(n);
8786     int NewElt = -1;
8787     if (MaskElt < (int)HalfElts)
8788       NewElt = MaskElt;
8789     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
8790       NewElt = HalfElts + MaskElt - NumElts;
8791     NewMask.push_back(NewElt);
8792   }
8793   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
8794                               DAG.getUNDEF(VT), NewMask.data());
8795 }
8796
8797 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP and
8798 /// NEON load/store intrinsics to merge base address updates.
8799 static SDValue CombineBaseUpdate(SDNode *N,
8800                                  TargetLowering::DAGCombinerInfo &DCI) {
8801   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8802     return SDValue();
8803
8804   SelectionDAG &DAG = DCI.DAG;
8805   bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
8806                       N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
8807   unsigned AddrOpIdx = (isIntrinsic ? 2 : 1);
8808   SDValue Addr = N->getOperand(AddrOpIdx);
8809
8810   // Search for a use of the address operand that is an increment.
8811   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8812          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8813     SDNode *User = *UI;
8814     if (User->getOpcode() != ISD::ADD ||
8815         UI.getUse().getResNo() != Addr.getResNo())
8816       continue;
8817
8818     // Check that the add is independent of the load/store.  Otherwise, folding
8819     // it would create a cycle.
8820     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8821       continue;
8822
8823     // Find the new opcode for the updating load/store.
8824     bool isLoad = true;
8825     bool isLaneOp = false;
8826     unsigned NewOpc = 0;
8827     unsigned NumVecs = 0;
8828     if (isIntrinsic) {
8829       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8830       switch (IntNo) {
8831       default: llvm_unreachable("unexpected intrinsic for Neon base update");
8832       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
8833         NumVecs = 1; break;
8834       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
8835         NumVecs = 2; break;
8836       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
8837         NumVecs = 3; break;
8838       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
8839         NumVecs = 4; break;
8840       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
8841         NumVecs = 2; isLaneOp = true; break;
8842       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
8843         NumVecs = 3; isLaneOp = true; break;
8844       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
8845         NumVecs = 4; isLaneOp = true; break;
8846       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
8847         NumVecs = 1; isLoad = false; break;
8848       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
8849         NumVecs = 2; isLoad = false; break;
8850       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
8851         NumVecs = 3; isLoad = false; break;
8852       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
8853         NumVecs = 4; isLoad = false; break;
8854       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
8855         NumVecs = 2; isLoad = false; isLaneOp = true; break;
8856       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
8857         NumVecs = 3; isLoad = false; isLaneOp = true; break;
8858       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
8859         NumVecs = 4; isLoad = false; isLaneOp = true; break;
8860       }
8861     } else {
8862       isLaneOp = true;
8863       switch (N->getOpcode()) {
8864       default: llvm_unreachable("unexpected opcode for Neon base update");
8865       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
8866       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
8867       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
8868       }
8869     }
8870
8871     // Find the size of memory referenced by the load/store.
8872     EVT VecTy;
8873     if (isLoad)
8874       VecTy = N->getValueType(0);
8875     else
8876       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
8877     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8878     if (isLaneOp)
8879       NumBytes /= VecTy.getVectorNumElements();
8880
8881     // If the increment is a constant, it must match the memory ref size.
8882     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8883     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8884       uint64_t IncVal = CInc->getZExtValue();
8885       if (IncVal != NumBytes)
8886         continue;
8887     } else if (NumBytes >= 3 * 16) {
8888       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
8889       // separate instructions that make it harder to use a non-constant update.
8890       continue;
8891     }
8892
8893     // Create the new updating load/store node.
8894     EVT Tys[6];
8895     unsigned NumResultVecs = (isLoad ? NumVecs : 0);
8896     unsigned n;
8897     for (n = 0; n < NumResultVecs; ++n)
8898       Tys[n] = VecTy;
8899     Tys[n++] = MVT::i32;
8900     Tys[n] = MVT::Other;
8901     SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumResultVecs+2));
8902     SmallVector<SDValue, 8> Ops;
8903     Ops.push_back(N->getOperand(0)); // incoming chain
8904     Ops.push_back(N->getOperand(AddrOpIdx));
8905     Ops.push_back(Inc);
8906     for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands(); ++i) {
8907       Ops.push_back(N->getOperand(i));
8908     }
8909     MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8910     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys,
8911                                            Ops, MemInt->getMemoryVT(),
8912                                            MemInt->getMemOperand());
8913
8914     // Update the uses.
8915     std::vector<SDValue> NewResults;
8916     for (unsigned i = 0; i < NumResultVecs; ++i) {
8917       NewResults.push_back(SDValue(UpdN.getNode(), i));
8918     }
8919     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
8920     DCI.CombineTo(N, NewResults);
8921     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8922
8923     break;
8924   }
8925   return SDValue();
8926 }
8927
8928 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
8929 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
8930 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
8931 /// return true.
8932 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
8933   SelectionDAG &DAG = DCI.DAG;
8934   EVT VT = N->getValueType(0);
8935   // vldN-dup instructions only support 64-bit vectors for N > 1.
8936   if (!VT.is64BitVector())
8937     return false;
8938
8939   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
8940   SDNode *VLD = N->getOperand(0).getNode();
8941   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
8942     return false;
8943   unsigned NumVecs = 0;
8944   unsigned NewOpc = 0;
8945   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
8946   if (IntNo == Intrinsic::arm_neon_vld2lane) {
8947     NumVecs = 2;
8948     NewOpc = ARMISD::VLD2DUP;
8949   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
8950     NumVecs = 3;
8951     NewOpc = ARMISD::VLD3DUP;
8952   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
8953     NumVecs = 4;
8954     NewOpc = ARMISD::VLD4DUP;
8955   } else {
8956     return false;
8957   }
8958
8959   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
8960   // numbers match the load.
8961   unsigned VLDLaneNo =
8962     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
8963   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8964        UI != UE; ++UI) {
8965     // Ignore uses of the chain result.
8966     if (UI.getUse().getResNo() == NumVecs)
8967       continue;
8968     SDNode *User = *UI;
8969     if (User->getOpcode() != ARMISD::VDUPLANE ||
8970         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
8971       return false;
8972   }
8973
8974   // Create the vldN-dup node.
8975   EVT Tys[5];
8976   unsigned n;
8977   for (n = 0; n < NumVecs; ++n)
8978     Tys[n] = VT;
8979   Tys[n] = MVT::Other;
8980   SDVTList SDTys = DAG.getVTList(ArrayRef<EVT>(Tys, NumVecs+1));
8981   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
8982   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
8983   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
8984                                            Ops, VLDMemInt->getMemoryVT(),
8985                                            VLDMemInt->getMemOperand());
8986
8987   // Update the uses.
8988   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
8989        UI != UE; ++UI) {
8990     unsigned ResNo = UI.getUse().getResNo();
8991     // Ignore uses of the chain result.
8992     if (ResNo == NumVecs)
8993       continue;
8994     SDNode *User = *UI;
8995     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
8996   }
8997
8998   // Now the vldN-lane intrinsic is dead except for its chain result.
8999   // Update uses of the chain.
9000   std::vector<SDValue> VLDDupResults;
9001   for (unsigned n = 0; n < NumVecs; ++n)
9002     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9003   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9004   DCI.CombineTo(VLD, VLDDupResults);
9005
9006   return true;
9007 }
9008
9009 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9010 /// ARMISD::VDUPLANE.
9011 static SDValue PerformVDUPLANECombine(SDNode *N,
9012                                       TargetLowering::DAGCombinerInfo &DCI) {
9013   SDValue Op = N->getOperand(0);
9014
9015   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9016   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9017   if (CombineVLDDUP(N, DCI))
9018     return SDValue(N, 0);
9019
9020   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9021   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9022   while (Op.getOpcode() == ISD::BITCAST)
9023     Op = Op.getOperand(0);
9024   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9025     return SDValue();
9026
9027   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9028   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9029   // The canonical VMOV for a zero vector uses a 32-bit element size.
9030   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9031   unsigned EltBits;
9032   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9033     EltSize = 8;
9034   EVT VT = N->getValueType(0);
9035   if (EltSize > VT.getVectorElementType().getSizeInBits())
9036     return SDValue();
9037
9038   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9039 }
9040
9041 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9042 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9043 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9044 {
9045   integerPart cN;
9046   integerPart c0 = 0;
9047   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9048        I != E; I++) {
9049     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9050     if (!C)
9051       return false;
9052
9053     bool isExact;
9054     APFloat APF = C->getValueAPF();
9055     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9056         != APFloat::opOK || !isExact)
9057       return false;
9058
9059     c0 = (I == 0) ? cN : c0;
9060     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9061       return false;
9062   }
9063   C = c0;
9064   return true;
9065 }
9066
9067 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9068 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9069 /// when the VMUL has a constant operand that is a power of 2.
9070 ///
9071 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9072 ///  vmul.f32        d16, d17, d16
9073 ///  vcvt.s32.f32    d16, d16
9074 /// becomes:
9075 ///  vcvt.s32.f32    d16, d16, #3
9076 static SDValue PerformVCVTCombine(SDNode *N,
9077                                   TargetLowering::DAGCombinerInfo &DCI,
9078                                   const ARMSubtarget *Subtarget) {
9079   SelectionDAG &DAG = DCI.DAG;
9080   SDValue Op = N->getOperand(0);
9081
9082   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9083       Op.getOpcode() != ISD::FMUL)
9084     return SDValue();
9085
9086   uint64_t C;
9087   SDValue N0 = Op->getOperand(0);
9088   SDValue ConstVec = Op->getOperand(1);
9089   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9090
9091   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9092       !isConstVecPow2(ConstVec, isSigned, C))
9093     return SDValue();
9094
9095   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9096   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9097   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9098     // These instructions only exist converting from f32 to i32. We can handle
9099     // smaller integers by generating an extra truncate, but larger ones would
9100     // be lossy.
9101     return SDValue();
9102   }
9103
9104   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9105     Intrinsic::arm_neon_vcvtfp2fxu;
9106   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9107   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9108                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9109                                  DAG.getConstant(IntrinsicOpcode, MVT::i32), N0,
9110                                  DAG.getConstant(Log2_64(C), MVT::i32));
9111
9112   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9113     FixConv = DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), FixConv);
9114
9115   return FixConv;
9116 }
9117
9118 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9119 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9120 /// when the VDIV has a constant operand that is a power of 2.
9121 ///
9122 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9123 ///  vcvt.f32.s32    d16, d16
9124 ///  vdiv.f32        d16, d17, d16
9125 /// becomes:
9126 ///  vcvt.f32.s32    d16, d16, #3
9127 static SDValue PerformVDIVCombine(SDNode *N,
9128                                   TargetLowering::DAGCombinerInfo &DCI,
9129                                   const ARMSubtarget *Subtarget) {
9130   SelectionDAG &DAG = DCI.DAG;
9131   SDValue Op = N->getOperand(0);
9132   unsigned OpOpcode = Op.getNode()->getOpcode();
9133
9134   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9135       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9136     return SDValue();
9137
9138   uint64_t C;
9139   SDValue ConstVec = N->getOperand(1);
9140   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9141
9142   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9143       !isConstVecPow2(ConstVec, isSigned, C))
9144     return SDValue();
9145
9146   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9147   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9148   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9149     // These instructions only exist converting from i32 to f32. We can handle
9150     // smaller integers by generating an extra extend, but larger ones would
9151     // be lossy.
9152     return SDValue();
9153   }
9154
9155   SDValue ConvInput = Op.getOperand(0);
9156   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9157   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9158     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9159                             SDLoc(N), NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9160                             ConvInput);
9161
9162   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9163     Intrinsic::arm_neon_vcvtfxu2fp;
9164   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N),
9165                      Op.getValueType(),
9166                      DAG.getConstant(IntrinsicOpcode, MVT::i32),
9167                      ConvInput, DAG.getConstant(Log2_64(C), MVT::i32));
9168 }
9169
9170 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9171 /// operand of a vector shift operation, where all the elements of the
9172 /// build_vector must have the same constant integer value.
9173 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9174   // Ignore bit_converts.
9175   while (Op.getOpcode() == ISD::BITCAST)
9176     Op = Op.getOperand(0);
9177   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9178   APInt SplatBits, SplatUndef;
9179   unsigned SplatBitSize;
9180   bool HasAnyUndefs;
9181   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9182                                       HasAnyUndefs, ElementBits) ||
9183       SplatBitSize > ElementBits)
9184     return false;
9185   Cnt = SplatBits.getSExtValue();
9186   return true;
9187 }
9188
9189 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9190 /// operand of a vector shift left operation.  That value must be in the range:
9191 ///   0 <= Value < ElementBits for a left shift; or
9192 ///   0 <= Value <= ElementBits for a long left shift.
9193 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9194   assert(VT.isVector() && "vector shift count is not a vector type");
9195   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9196   if (! getVShiftImm(Op, ElementBits, Cnt))
9197     return false;
9198   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9199 }
9200
9201 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9202 /// operand of a vector shift right operation.  For a shift opcode, the value
9203 /// is positive, but for an intrinsic the value count must be negative. The
9204 /// absolute value must be in the range:
9205 ///   1 <= |Value| <= ElementBits for a right shift; or
9206 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9207 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9208                          int64_t &Cnt) {
9209   assert(VT.isVector() && "vector shift count is not a vector type");
9210   unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
9211   if (! getVShiftImm(Op, ElementBits, Cnt))
9212     return false;
9213   if (isIntrinsic)
9214     Cnt = -Cnt;
9215   return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9216 }
9217
9218 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9219 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9220   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9221   switch (IntNo) {
9222   default:
9223     // Don't do anything for most intrinsics.
9224     break;
9225
9226   // Vector shifts: check for immediate versions and lower them.
9227   // Note: This is done during DAG combining instead of DAG legalizing because
9228   // the build_vectors for 64-bit vector element shift counts are generally
9229   // not legal, and it is hard to see their values after they get legalized to
9230   // loads from a constant pool.
9231   case Intrinsic::arm_neon_vshifts:
9232   case Intrinsic::arm_neon_vshiftu:
9233   case Intrinsic::arm_neon_vrshifts:
9234   case Intrinsic::arm_neon_vrshiftu:
9235   case Intrinsic::arm_neon_vrshiftn:
9236   case Intrinsic::arm_neon_vqshifts:
9237   case Intrinsic::arm_neon_vqshiftu:
9238   case Intrinsic::arm_neon_vqshiftsu:
9239   case Intrinsic::arm_neon_vqshiftns:
9240   case Intrinsic::arm_neon_vqshiftnu:
9241   case Intrinsic::arm_neon_vqshiftnsu:
9242   case Intrinsic::arm_neon_vqrshiftns:
9243   case Intrinsic::arm_neon_vqrshiftnu:
9244   case Intrinsic::arm_neon_vqrshiftnsu: {
9245     EVT VT = N->getOperand(1).getValueType();
9246     int64_t Cnt;
9247     unsigned VShiftOpc = 0;
9248
9249     switch (IntNo) {
9250     case Intrinsic::arm_neon_vshifts:
9251     case Intrinsic::arm_neon_vshiftu:
9252       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9253         VShiftOpc = ARMISD::VSHL;
9254         break;
9255       }
9256       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9257         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9258                      ARMISD::VSHRs : ARMISD::VSHRu);
9259         break;
9260       }
9261       return SDValue();
9262
9263     case Intrinsic::arm_neon_vrshifts:
9264     case Intrinsic::arm_neon_vrshiftu:
9265       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9266         break;
9267       return SDValue();
9268
9269     case Intrinsic::arm_neon_vqshifts:
9270     case Intrinsic::arm_neon_vqshiftu:
9271       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9272         break;
9273       return SDValue();
9274
9275     case Intrinsic::arm_neon_vqshiftsu:
9276       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9277         break;
9278       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9279
9280     case Intrinsic::arm_neon_vrshiftn:
9281     case Intrinsic::arm_neon_vqshiftns:
9282     case Intrinsic::arm_neon_vqshiftnu:
9283     case Intrinsic::arm_neon_vqshiftnsu:
9284     case Intrinsic::arm_neon_vqrshiftns:
9285     case Intrinsic::arm_neon_vqrshiftnu:
9286     case Intrinsic::arm_neon_vqrshiftnsu:
9287       // Narrowing shifts require an immediate right shift.
9288       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9289         break;
9290       llvm_unreachable("invalid shift count for narrowing vector shift "
9291                        "intrinsic");
9292
9293     default:
9294       llvm_unreachable("unhandled vector shift");
9295     }
9296
9297     switch (IntNo) {
9298     case Intrinsic::arm_neon_vshifts:
9299     case Intrinsic::arm_neon_vshiftu:
9300       // Opcode already set above.
9301       break;
9302     case Intrinsic::arm_neon_vrshifts:
9303       VShiftOpc = ARMISD::VRSHRs; break;
9304     case Intrinsic::arm_neon_vrshiftu:
9305       VShiftOpc = ARMISD::VRSHRu; break;
9306     case Intrinsic::arm_neon_vrshiftn:
9307       VShiftOpc = ARMISD::VRSHRN; break;
9308     case Intrinsic::arm_neon_vqshifts:
9309       VShiftOpc = ARMISD::VQSHLs; break;
9310     case Intrinsic::arm_neon_vqshiftu:
9311       VShiftOpc = ARMISD::VQSHLu; break;
9312     case Intrinsic::arm_neon_vqshiftsu:
9313       VShiftOpc = ARMISD::VQSHLsu; break;
9314     case Intrinsic::arm_neon_vqshiftns:
9315       VShiftOpc = ARMISD::VQSHRNs; break;
9316     case Intrinsic::arm_neon_vqshiftnu:
9317       VShiftOpc = ARMISD::VQSHRNu; break;
9318     case Intrinsic::arm_neon_vqshiftnsu:
9319       VShiftOpc = ARMISD::VQSHRNsu; break;
9320     case Intrinsic::arm_neon_vqrshiftns:
9321       VShiftOpc = ARMISD::VQRSHRNs; break;
9322     case Intrinsic::arm_neon_vqrshiftnu:
9323       VShiftOpc = ARMISD::VQRSHRNu; break;
9324     case Intrinsic::arm_neon_vqrshiftnsu:
9325       VShiftOpc = ARMISD::VQRSHRNsu; break;
9326     }
9327
9328     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9329                        N->getOperand(1), DAG.getConstant(Cnt, MVT::i32));
9330   }
9331
9332   case Intrinsic::arm_neon_vshiftins: {
9333     EVT VT = N->getOperand(1).getValueType();
9334     int64_t Cnt;
9335     unsigned VShiftOpc = 0;
9336
9337     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
9338       VShiftOpc = ARMISD::VSLI;
9339     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
9340       VShiftOpc = ARMISD::VSRI;
9341     else {
9342       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
9343     }
9344
9345     return DAG.getNode(VShiftOpc, SDLoc(N), N->getValueType(0),
9346                        N->getOperand(1), N->getOperand(2),
9347                        DAG.getConstant(Cnt, MVT::i32));
9348   }
9349
9350   case Intrinsic::arm_neon_vqrshifts:
9351   case Intrinsic::arm_neon_vqrshiftu:
9352     // No immediate versions of these to check for.
9353     break;
9354   }
9355
9356   return SDValue();
9357 }
9358
9359 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
9360 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
9361 /// combining instead of DAG legalizing because the build_vectors for 64-bit
9362 /// vector element shift counts are generally not legal, and it is hard to see
9363 /// their values after they get legalized to loads from a constant pool.
9364 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
9365                                    const ARMSubtarget *ST) {
9366   EVT VT = N->getValueType(0);
9367   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
9368     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
9369     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
9370     SDValue N1 = N->getOperand(1);
9371     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
9372       SDValue N0 = N->getOperand(0);
9373       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
9374           DAG.MaskedValueIsZero(N0.getOperand(0),
9375                                 APInt::getHighBitsSet(32, 16)))
9376         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
9377     }
9378   }
9379
9380   // Nothing to be done for scalar shifts.
9381   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9382   if (!VT.isVector() || !TLI.isTypeLegal(VT))
9383     return SDValue();
9384
9385   assert(ST->hasNEON() && "unexpected vector shift");
9386   int64_t Cnt;
9387
9388   switch (N->getOpcode()) {
9389   default: llvm_unreachable("unexpected shift opcode");
9390
9391   case ISD::SHL:
9392     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
9393       return DAG.getNode(ARMISD::VSHL, SDLoc(N), VT, N->getOperand(0),
9394                          DAG.getConstant(Cnt, MVT::i32));
9395     break;
9396
9397   case ISD::SRA:
9398   case ISD::SRL:
9399     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
9400       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
9401                             ARMISD::VSHRs : ARMISD::VSHRu);
9402       return DAG.getNode(VShiftOpc, SDLoc(N), VT, N->getOperand(0),
9403                          DAG.getConstant(Cnt, MVT::i32));
9404     }
9405   }
9406   return SDValue();
9407 }
9408
9409 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
9410 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
9411 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
9412                                     const ARMSubtarget *ST) {
9413   SDValue N0 = N->getOperand(0);
9414
9415   // Check for sign- and zero-extensions of vector extract operations of 8-
9416   // and 16-bit vector elements.  NEON supports these directly.  They are
9417   // handled during DAG combining because type legalization will promote them
9418   // to 32-bit types and it is messy to recognize the operations after that.
9419   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9420     SDValue Vec = N0.getOperand(0);
9421     SDValue Lane = N0.getOperand(1);
9422     EVT VT = N->getValueType(0);
9423     EVT EltVT = N0.getValueType();
9424     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9425
9426     if (VT == MVT::i32 &&
9427         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
9428         TLI.isTypeLegal(Vec.getValueType()) &&
9429         isa<ConstantSDNode>(Lane)) {
9430
9431       unsigned Opc = 0;
9432       switch (N->getOpcode()) {
9433       default: llvm_unreachable("unexpected opcode");
9434       case ISD::SIGN_EXTEND:
9435         Opc = ARMISD::VGETLANEs;
9436         break;
9437       case ISD::ZERO_EXTEND:
9438       case ISD::ANY_EXTEND:
9439         Opc = ARMISD::VGETLANEu;
9440         break;
9441       }
9442       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
9443     }
9444   }
9445
9446   return SDValue();
9447 }
9448
9449 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
9450 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
9451 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
9452                                        const ARMSubtarget *ST) {
9453   // If the target supports NEON, try to use vmax/vmin instructions for f32
9454   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
9455   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
9456   // a NaN; only do the transformation when it matches that behavior.
9457
9458   // For now only do this when using NEON for FP operations; if using VFP, it
9459   // is not obvious that the benefit outweighs the cost of switching to the
9460   // NEON pipeline.
9461   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
9462       N->getValueType(0) != MVT::f32)
9463     return SDValue();
9464
9465   SDValue CondLHS = N->getOperand(0);
9466   SDValue CondRHS = N->getOperand(1);
9467   SDValue LHS = N->getOperand(2);
9468   SDValue RHS = N->getOperand(3);
9469   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9470
9471   unsigned Opcode = 0;
9472   bool IsReversed;
9473   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
9474     IsReversed = false; // x CC y ? x : y
9475   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
9476     IsReversed = true ; // x CC y ? y : x
9477   } else {
9478     return SDValue();
9479   }
9480
9481   bool IsUnordered;
9482   switch (CC) {
9483   default: break;
9484   case ISD::SETOLT:
9485   case ISD::SETOLE:
9486   case ISD::SETLT:
9487   case ISD::SETLE:
9488   case ISD::SETULT:
9489   case ISD::SETULE:
9490     // If LHS is NaN, an ordered comparison will be false and the result will
9491     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
9492     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9493     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
9494     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9495       break;
9496     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
9497     // will return -0, so vmin can only be used for unsafe math or if one of
9498     // the operands is known to be nonzero.
9499     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
9500         !DAG.getTarget().Options.UnsafeFPMath &&
9501         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9502       break;
9503     Opcode = IsReversed ? ARMISD::FMAX : ARMISD::FMIN;
9504     break;
9505
9506   case ISD::SETOGT:
9507   case ISD::SETOGE:
9508   case ISD::SETGT:
9509   case ISD::SETGE:
9510   case ISD::SETUGT:
9511   case ISD::SETUGE:
9512     // If LHS is NaN, an ordered comparison will be false and the result will
9513     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
9514     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
9515     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
9516     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9517       break;
9518     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
9519     // will return +0, so vmax can only be used for unsafe math or if one of
9520     // the operands is known to be nonzero.
9521     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
9522         !DAG.getTarget().Options.UnsafeFPMath &&
9523         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9524       break;
9525     Opcode = IsReversed ? ARMISD::FMIN : ARMISD::FMAX;
9526     break;
9527   }
9528
9529   if (!Opcode)
9530     return SDValue();
9531   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9532 }
9533
9534 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
9535 SDValue
9536 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
9537   SDValue Cmp = N->getOperand(4);
9538   if (Cmp.getOpcode() != ARMISD::CMPZ)
9539     // Only looking at EQ and NE cases.
9540     return SDValue();
9541
9542   EVT VT = N->getValueType(0);
9543   SDLoc dl(N);
9544   SDValue LHS = Cmp.getOperand(0);
9545   SDValue RHS = Cmp.getOperand(1);
9546   SDValue FalseVal = N->getOperand(0);
9547   SDValue TrueVal = N->getOperand(1);
9548   SDValue ARMcc = N->getOperand(2);
9549   ARMCC::CondCodes CC =
9550     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
9551
9552   // Simplify
9553   //   mov     r1, r0
9554   //   cmp     r1, x
9555   //   mov     r0, y
9556   //   moveq   r0, x
9557   // to
9558   //   cmp     r0, x
9559   //   movne   r0, y
9560   //
9561   //   mov     r1, r0
9562   //   cmp     r1, x
9563   //   mov     r0, x
9564   //   movne   r0, y
9565   // to
9566   //   cmp     r0, x
9567   //   movne   r0, y
9568   /// FIXME: Turn this into a target neutral optimization?
9569   SDValue Res;
9570   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
9571     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
9572                       N->getOperand(3), Cmp);
9573   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
9574     SDValue ARMcc;
9575     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
9576     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
9577                       N->getOperand(3), NewCmp);
9578   }
9579
9580   if (Res.getNode()) {
9581     APInt KnownZero, KnownOne;
9582     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
9583     // Capture demanded bits information that would be otherwise lost.
9584     if (KnownZero == 0xfffffffe)
9585       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9586                         DAG.getValueType(MVT::i1));
9587     else if (KnownZero == 0xffffff00)
9588       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9589                         DAG.getValueType(MVT::i8));
9590     else if (KnownZero == 0xffff0000)
9591       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
9592                         DAG.getValueType(MVT::i16));
9593   }
9594
9595   return Res;
9596 }
9597
9598 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
9599                                              DAGCombinerInfo &DCI) const {
9600   switch (N->getOpcode()) {
9601   default: break;
9602   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
9603   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
9604   case ISD::SUB:        return PerformSUBCombine(N, DCI);
9605   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
9606   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
9607   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
9608   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
9609   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
9610   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI);
9611   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
9612   case ISD::STORE:      return PerformSTORECombine(N, DCI);
9613   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI);
9614   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
9615   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
9616   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
9617   case ISD::FP_TO_SINT:
9618   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
9619   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
9620   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
9621   case ISD::SHL:
9622   case ISD::SRA:
9623   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
9624   case ISD::SIGN_EXTEND:
9625   case ISD::ZERO_EXTEND:
9626   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
9627   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
9628   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
9629   case ARMISD::VLD2DUP:
9630   case ARMISD::VLD3DUP:
9631   case ARMISD::VLD4DUP:
9632     return CombineBaseUpdate(N, DCI);
9633   case ARMISD::BUILD_VECTOR:
9634     return PerformARMBUILD_VECTORCombine(N, DCI);
9635   case ISD::INTRINSIC_VOID:
9636   case ISD::INTRINSIC_W_CHAIN:
9637     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9638     case Intrinsic::arm_neon_vld1:
9639     case Intrinsic::arm_neon_vld2:
9640     case Intrinsic::arm_neon_vld3:
9641     case Intrinsic::arm_neon_vld4:
9642     case Intrinsic::arm_neon_vld2lane:
9643     case Intrinsic::arm_neon_vld3lane:
9644     case Intrinsic::arm_neon_vld4lane:
9645     case Intrinsic::arm_neon_vst1:
9646     case Intrinsic::arm_neon_vst2:
9647     case Intrinsic::arm_neon_vst3:
9648     case Intrinsic::arm_neon_vst4:
9649     case Intrinsic::arm_neon_vst2lane:
9650     case Intrinsic::arm_neon_vst3lane:
9651     case Intrinsic::arm_neon_vst4lane:
9652       return CombineBaseUpdate(N, DCI);
9653     default: break;
9654     }
9655     break;
9656   }
9657   return SDValue();
9658 }
9659
9660 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
9661                                                           EVT VT) const {
9662   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
9663 }
9664
9665 bool ARMTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, unsigned,
9666                                                       bool *Fast) const {
9667   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
9668   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
9669
9670   switch (VT.getSimpleVT().SimpleTy) {
9671   default:
9672     return false;
9673   case MVT::i8:
9674   case MVT::i16:
9675   case MVT::i32: {
9676     // Unaligned access can use (for example) LRDB, LRDH, LDR
9677     if (AllowsUnaligned) {
9678       if (Fast)
9679         *Fast = Subtarget->hasV7Ops();
9680       return true;
9681     }
9682     return false;
9683   }
9684   case MVT::f64:
9685   case MVT::v2f64: {
9686     // For any little-endian targets with neon, we can support unaligned ld/st
9687     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
9688     // A big-endian target may also explicitly support unaligned accesses
9689     if (Subtarget->hasNEON() && (AllowsUnaligned || isLittleEndian())) {
9690       if (Fast)
9691         *Fast = true;
9692       return true;
9693     }
9694     return false;
9695   }
9696   }
9697 }
9698
9699 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
9700                        unsigned AlignCheck) {
9701   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
9702           (DstAlign == 0 || DstAlign % AlignCheck == 0));
9703 }
9704
9705 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
9706                                            unsigned DstAlign, unsigned SrcAlign,
9707                                            bool IsMemset, bool ZeroMemset,
9708                                            bool MemcpyStrSrc,
9709                                            MachineFunction &MF) const {
9710   const Function *F = MF.getFunction();
9711
9712   // See if we can use NEON instructions for this...
9713   if ((!IsMemset || ZeroMemset) &&
9714       Subtarget->hasNEON() &&
9715       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
9716                                        Attribute::NoImplicitFloat)) {
9717     bool Fast;
9718     if (Size >= 16 &&
9719         (memOpAlign(SrcAlign, DstAlign, 16) ||
9720          (allowsUnalignedMemoryAccesses(MVT::v2f64, 0, &Fast) && Fast))) {
9721       return MVT::v2f64;
9722     } else if (Size >= 8 &&
9723                (memOpAlign(SrcAlign, DstAlign, 8) ||
9724                 (allowsUnalignedMemoryAccesses(MVT::f64, 0, &Fast) && Fast))) {
9725       return MVT::f64;
9726     }
9727   }
9728
9729   // Lowering to i32/i16 if the size permits.
9730   if (Size >= 4)
9731     return MVT::i32;
9732   else if (Size >= 2)
9733     return MVT::i16;
9734
9735   // Let the target-independent logic figure it out.
9736   return MVT::Other;
9737 }
9738
9739 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9740   if (Val.getOpcode() != ISD::LOAD)
9741     return false;
9742
9743   EVT VT1 = Val.getValueType();
9744   if (!VT1.isSimple() || !VT1.isInteger() ||
9745       !VT2.isSimple() || !VT2.isInteger())
9746     return false;
9747
9748   switch (VT1.getSimpleVT().SimpleTy) {
9749   default: break;
9750   case MVT::i1:
9751   case MVT::i8:
9752   case MVT::i16:
9753     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
9754     return true;
9755   }
9756
9757   return false;
9758 }
9759
9760 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
9761   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9762     return false;
9763
9764   if (!isTypeLegal(EVT::getEVT(Ty1)))
9765     return false;
9766
9767   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
9768
9769   // Assuming the caller doesn't have a zeroext or signext return parameter,
9770   // truncation all the way down to i1 is valid.
9771   return true;
9772 }
9773
9774
9775 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
9776   if (V < 0)
9777     return false;
9778
9779   unsigned Scale = 1;
9780   switch (VT.getSimpleVT().SimpleTy) {
9781   default: return false;
9782   case MVT::i1:
9783   case MVT::i8:
9784     // Scale == 1;
9785     break;
9786   case MVT::i16:
9787     // Scale == 2;
9788     Scale = 2;
9789     break;
9790   case MVT::i32:
9791     // Scale == 4;
9792     Scale = 4;
9793     break;
9794   }
9795
9796   if ((V & (Scale - 1)) != 0)
9797     return false;
9798   V /= Scale;
9799   return V == (V & ((1LL << 5) - 1));
9800 }
9801
9802 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
9803                                       const ARMSubtarget *Subtarget) {
9804   bool isNeg = false;
9805   if (V < 0) {
9806     isNeg = true;
9807     V = - V;
9808   }
9809
9810   switch (VT.getSimpleVT().SimpleTy) {
9811   default: return false;
9812   case MVT::i1:
9813   case MVT::i8:
9814   case MVT::i16:
9815   case MVT::i32:
9816     // + imm12 or - imm8
9817     if (isNeg)
9818       return V == (V & ((1LL << 8) - 1));
9819     return V == (V & ((1LL << 12) - 1));
9820   case MVT::f32:
9821   case MVT::f64:
9822     // Same as ARM mode. FIXME: NEON?
9823     if (!Subtarget->hasVFP2())
9824       return false;
9825     if ((V & 3) != 0)
9826       return false;
9827     V >>= 2;
9828     return V == (V & ((1LL << 8) - 1));
9829   }
9830 }
9831
9832 /// isLegalAddressImmediate - Return true if the integer value can be used
9833 /// as the offset of the target addressing mode for load / store of the
9834 /// given type.
9835 static bool isLegalAddressImmediate(int64_t V, EVT VT,
9836                                     const ARMSubtarget *Subtarget) {
9837   if (V == 0)
9838     return true;
9839
9840   if (!VT.isSimple())
9841     return false;
9842
9843   if (Subtarget->isThumb1Only())
9844     return isLegalT1AddressImmediate(V, VT);
9845   else if (Subtarget->isThumb2())
9846     return isLegalT2AddressImmediate(V, VT, Subtarget);
9847
9848   // ARM mode.
9849   if (V < 0)
9850     V = - V;
9851   switch (VT.getSimpleVT().SimpleTy) {
9852   default: return false;
9853   case MVT::i1:
9854   case MVT::i8:
9855   case MVT::i32:
9856     // +- imm12
9857     return V == (V & ((1LL << 12) - 1));
9858   case MVT::i16:
9859     // +- imm8
9860     return V == (V & ((1LL << 8) - 1));
9861   case MVT::f32:
9862   case MVT::f64:
9863     if (!Subtarget->hasVFP2()) // FIXME: NEON?
9864       return false;
9865     if ((V & 3) != 0)
9866       return false;
9867     V >>= 2;
9868     return V == (V & ((1LL << 8) - 1));
9869   }
9870 }
9871
9872 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
9873                                                       EVT VT) const {
9874   int Scale = AM.Scale;
9875   if (Scale < 0)
9876     return false;
9877
9878   switch (VT.getSimpleVT().SimpleTy) {
9879   default: return false;
9880   case MVT::i1:
9881   case MVT::i8:
9882   case MVT::i16:
9883   case MVT::i32:
9884     if (Scale == 1)
9885       return true;
9886     // r + r << imm
9887     Scale = Scale & ~1;
9888     return Scale == 2 || Scale == 4 || Scale == 8;
9889   case MVT::i64:
9890     // r + r
9891     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9892       return true;
9893     return false;
9894   case MVT::isVoid:
9895     // Note, we allow "void" uses (basically, uses that aren't loads or
9896     // stores), because arm allows folding a scale into many arithmetic
9897     // operations.  This should be made more precise and revisited later.
9898
9899     // Allow r << imm, but the imm has to be a multiple of two.
9900     if (Scale & 1) return false;
9901     return isPowerOf2_32(Scale);
9902   }
9903 }
9904
9905 /// isLegalAddressingMode - Return true if the addressing mode represented
9906 /// by AM is legal for this target, for a load/store of the specified type.
9907 bool ARMTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9908                                               Type *Ty) const {
9909   EVT VT = getValueType(Ty, true);
9910   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
9911     return false;
9912
9913   // Can never fold addr of global into load/store.
9914   if (AM.BaseGV)
9915     return false;
9916
9917   switch (AM.Scale) {
9918   case 0:  // no scale reg, must be "r+i" or "r", or "i".
9919     break;
9920   case 1:
9921     if (Subtarget->isThumb1Only())
9922       return false;
9923     // FALL THROUGH.
9924   default:
9925     // ARM doesn't support any R+R*scale+imm addr modes.
9926     if (AM.BaseOffs)
9927       return false;
9928
9929     if (!VT.isSimple())
9930       return false;
9931
9932     if (Subtarget->isThumb2())
9933       return isLegalT2ScaledAddressingMode(AM, VT);
9934
9935     int Scale = AM.Scale;
9936     switch (VT.getSimpleVT().SimpleTy) {
9937     default: return false;
9938     case MVT::i1:
9939     case MVT::i8:
9940     case MVT::i32:
9941       if (Scale < 0) Scale = -Scale;
9942       if (Scale == 1)
9943         return true;
9944       // r + r << imm
9945       return isPowerOf2_32(Scale & ~1);
9946     case MVT::i16:
9947     case MVT::i64:
9948       // r + r
9949       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
9950         return true;
9951       return false;
9952
9953     case MVT::isVoid:
9954       // Note, we allow "void" uses (basically, uses that aren't loads or
9955       // stores), because arm allows folding a scale into many arithmetic
9956       // operations.  This should be made more precise and revisited later.
9957
9958       // Allow r << imm, but the imm has to be a multiple of two.
9959       if (Scale & 1) return false;
9960       return isPowerOf2_32(Scale);
9961     }
9962   }
9963   return true;
9964 }
9965
9966 /// isLegalICmpImmediate - Return true if the specified immediate is legal
9967 /// icmp immediate, that is the target has icmp instructions which can compare
9968 /// a register against the immediate without having to materialize the
9969 /// immediate into a register.
9970 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9971   // Thumb2 and ARM modes can use cmn for negative immediates.
9972   if (!Subtarget->isThumb())
9973     return ARM_AM::getSOImmVal(llvm::abs64(Imm)) != -1;
9974   if (Subtarget->isThumb2())
9975     return ARM_AM::getT2SOImmVal(llvm::abs64(Imm)) != -1;
9976   // Thumb1 doesn't have cmn, and only 8-bit immediates.
9977   return Imm >= 0 && Imm <= 255;
9978 }
9979
9980 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
9981 /// *or sub* immediate, that is the target has add or sub instructions which can
9982 /// add a register with the immediate without having to materialize the
9983 /// immediate into a register.
9984 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9985   // Same encoding for add/sub, just flip the sign.
9986   int64_t AbsImm = llvm::abs64(Imm);
9987   if (!Subtarget->isThumb())
9988     return ARM_AM::getSOImmVal(AbsImm) != -1;
9989   if (Subtarget->isThumb2())
9990     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
9991   // Thumb1 only has 8-bit unsigned immediate.
9992   return AbsImm >= 0 && AbsImm <= 255;
9993 }
9994
9995 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
9996                                       bool isSEXTLoad, SDValue &Base,
9997                                       SDValue &Offset, bool &isInc,
9998                                       SelectionDAG &DAG) {
9999   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10000     return false;
10001
10002   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10003     // AddressingMode 3
10004     Base = Ptr->getOperand(0);
10005     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10006       int RHSC = (int)RHS->getZExtValue();
10007       if (RHSC < 0 && RHSC > -256) {
10008         assert(Ptr->getOpcode() == ISD::ADD);
10009         isInc = false;
10010         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10011         return true;
10012       }
10013     }
10014     isInc = (Ptr->getOpcode() == ISD::ADD);
10015     Offset = Ptr->getOperand(1);
10016     return true;
10017   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10018     // AddressingMode 2
10019     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10020       int RHSC = (int)RHS->getZExtValue();
10021       if (RHSC < 0 && RHSC > -0x1000) {
10022         assert(Ptr->getOpcode() == ISD::ADD);
10023         isInc = false;
10024         Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10025         Base = Ptr->getOperand(0);
10026         return true;
10027       }
10028     }
10029
10030     if (Ptr->getOpcode() == ISD::ADD) {
10031       isInc = true;
10032       ARM_AM::ShiftOpc ShOpcVal=
10033         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10034       if (ShOpcVal != ARM_AM::no_shift) {
10035         Base = Ptr->getOperand(1);
10036         Offset = Ptr->getOperand(0);
10037       } else {
10038         Base = Ptr->getOperand(0);
10039         Offset = Ptr->getOperand(1);
10040       }
10041       return true;
10042     }
10043
10044     isInc = (Ptr->getOpcode() == ISD::ADD);
10045     Base = Ptr->getOperand(0);
10046     Offset = Ptr->getOperand(1);
10047     return true;
10048   }
10049
10050   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10051   return false;
10052 }
10053
10054 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10055                                      bool isSEXTLoad, SDValue &Base,
10056                                      SDValue &Offset, bool &isInc,
10057                                      SelectionDAG &DAG) {
10058   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10059     return false;
10060
10061   Base = Ptr->getOperand(0);
10062   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10063     int RHSC = (int)RHS->getZExtValue();
10064     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10065       assert(Ptr->getOpcode() == ISD::ADD);
10066       isInc = false;
10067       Offset = DAG.getConstant(-RHSC, RHS->getValueType(0));
10068       return true;
10069     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10070       isInc = Ptr->getOpcode() == ISD::ADD;
10071       Offset = DAG.getConstant(RHSC, RHS->getValueType(0));
10072       return true;
10073     }
10074   }
10075
10076   return false;
10077 }
10078
10079 /// getPreIndexedAddressParts - returns true by value, base pointer and
10080 /// offset pointer and addressing mode by reference if the node's address
10081 /// can be legally represented as pre-indexed load / store address.
10082 bool
10083 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10084                                              SDValue &Offset,
10085                                              ISD::MemIndexedMode &AM,
10086                                              SelectionDAG &DAG) const {
10087   if (Subtarget->isThumb1Only())
10088     return false;
10089
10090   EVT VT;
10091   SDValue Ptr;
10092   bool isSEXTLoad = false;
10093   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10094     Ptr = LD->getBasePtr();
10095     VT  = LD->getMemoryVT();
10096     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10097   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10098     Ptr = ST->getBasePtr();
10099     VT  = ST->getMemoryVT();
10100   } else
10101     return false;
10102
10103   bool isInc;
10104   bool isLegal = false;
10105   if (Subtarget->isThumb2())
10106     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10107                                        Offset, isInc, DAG);
10108   else
10109     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10110                                         Offset, isInc, DAG);
10111   if (!isLegal)
10112     return false;
10113
10114   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10115   return true;
10116 }
10117
10118 /// getPostIndexedAddressParts - returns true by value, base pointer and
10119 /// offset pointer and addressing mode by reference if this node can be
10120 /// combined with a load / store to form a post-indexed load / store.
10121 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10122                                                    SDValue &Base,
10123                                                    SDValue &Offset,
10124                                                    ISD::MemIndexedMode &AM,
10125                                                    SelectionDAG &DAG) const {
10126   if (Subtarget->isThumb1Only())
10127     return false;
10128
10129   EVT VT;
10130   SDValue Ptr;
10131   bool isSEXTLoad = false;
10132   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10133     VT  = LD->getMemoryVT();
10134     Ptr = LD->getBasePtr();
10135     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10136   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10137     VT  = ST->getMemoryVT();
10138     Ptr = ST->getBasePtr();
10139   } else
10140     return false;
10141
10142   bool isInc;
10143   bool isLegal = false;
10144   if (Subtarget->isThumb2())
10145     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10146                                        isInc, DAG);
10147   else
10148     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10149                                         isInc, DAG);
10150   if (!isLegal)
10151     return false;
10152
10153   if (Ptr != Base) {
10154     // Swap base ptr and offset to catch more post-index load / store when
10155     // it's legal. In Thumb2 mode, offset must be an immediate.
10156     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10157         !Subtarget->isThumb2())
10158       std::swap(Base, Offset);
10159
10160     // Post-indexed load / store update the base pointer.
10161     if (Ptr != Base)
10162       return false;
10163   }
10164
10165   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10166   return true;
10167 }
10168
10169 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10170                                                       APInt &KnownZero,
10171                                                       APInt &KnownOne,
10172                                                       const SelectionDAG &DAG,
10173                                                       unsigned Depth) const {
10174   unsigned BitWidth = KnownOne.getBitWidth();
10175   KnownZero = KnownOne = APInt(BitWidth, 0);
10176   switch (Op.getOpcode()) {
10177   default: break;
10178   case ARMISD::ADDC:
10179   case ARMISD::ADDE:
10180   case ARMISD::SUBC:
10181   case ARMISD::SUBE:
10182     // These nodes' second result is a boolean
10183     if (Op.getResNo() == 0)
10184       break;
10185     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10186     break;
10187   case ARMISD::CMOV: {
10188     // Bits are known zero/one if known on the LHS and RHS.
10189     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10190     if (KnownZero == 0 && KnownOne == 0) return;
10191
10192     APInt KnownZeroRHS, KnownOneRHS;
10193     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10194     KnownZero &= KnownZeroRHS;
10195     KnownOne  &= KnownOneRHS;
10196     return;
10197   }
10198   case ISD::INTRINSIC_W_CHAIN: {
10199     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10200     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10201     switch (IntID) {
10202     default: return;
10203     case Intrinsic::arm_ldaex:
10204     case Intrinsic::arm_ldrex: {
10205       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10206       unsigned MemBits = VT.getScalarType().getSizeInBits();
10207       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10208       return;
10209     }
10210     }
10211   }
10212   }
10213 }
10214
10215 //===----------------------------------------------------------------------===//
10216 //                           ARM Inline Assembly Support
10217 //===----------------------------------------------------------------------===//
10218
10219 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10220   // Looking for "rev" which is V6+.
10221   if (!Subtarget->hasV6Ops())
10222     return false;
10223
10224   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10225   std::string AsmStr = IA->getAsmString();
10226   SmallVector<StringRef, 4> AsmPieces;
10227   SplitString(AsmStr, AsmPieces, ";\n");
10228
10229   switch (AsmPieces.size()) {
10230   default: return false;
10231   case 1:
10232     AsmStr = AsmPieces[0];
10233     AsmPieces.clear();
10234     SplitString(AsmStr, AsmPieces, " \t,");
10235
10236     // rev $0, $1
10237     if (AsmPieces.size() == 3 &&
10238         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10239         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10240       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10241       if (Ty && Ty->getBitWidth() == 32)
10242         return IntrinsicLowering::LowerToByteSwap(CI);
10243     }
10244     break;
10245   }
10246
10247   return false;
10248 }
10249
10250 /// getConstraintType - Given a constraint letter, return the type of
10251 /// constraint it is for this target.
10252 ARMTargetLowering::ConstraintType
10253 ARMTargetLowering::getConstraintType(const std::string &Constraint) const {
10254   if (Constraint.size() == 1) {
10255     switch (Constraint[0]) {
10256     default:  break;
10257     case 'l': return C_RegisterClass;
10258     case 'w': return C_RegisterClass;
10259     case 'h': return C_RegisterClass;
10260     case 'x': return C_RegisterClass;
10261     case 't': return C_RegisterClass;
10262     case 'j': return C_Other; // Constant for movw.
10263       // An address with a single base register. Due to the way we
10264       // currently handle addresses it is the same as an 'r' memory constraint.
10265     case 'Q': return C_Memory;
10266     }
10267   } else if (Constraint.size() == 2) {
10268     switch (Constraint[0]) {
10269     default: break;
10270     // All 'U+' constraints are addresses.
10271     case 'U': return C_Memory;
10272     }
10273   }
10274   return TargetLowering::getConstraintType(Constraint);
10275 }
10276
10277 /// Examine constraint type and operand type and determine a weight value.
10278 /// This object must already have been set up with the operand type
10279 /// and the current alternative constraint selected.
10280 TargetLowering::ConstraintWeight
10281 ARMTargetLowering::getSingleConstraintMatchWeight(
10282     AsmOperandInfo &info, const char *constraint) const {
10283   ConstraintWeight weight = CW_Invalid;
10284   Value *CallOperandVal = info.CallOperandVal;
10285     // If we don't have a value, we can't do a match,
10286     // but allow it at the lowest weight.
10287   if (!CallOperandVal)
10288     return CW_Default;
10289   Type *type = CallOperandVal->getType();
10290   // Look at the constraint type.
10291   switch (*constraint) {
10292   default:
10293     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
10294     break;
10295   case 'l':
10296     if (type->isIntegerTy()) {
10297       if (Subtarget->isThumb())
10298         weight = CW_SpecificReg;
10299       else
10300         weight = CW_Register;
10301     }
10302     break;
10303   case 'w':
10304     if (type->isFloatingPointTy())
10305       weight = CW_Register;
10306     break;
10307   }
10308   return weight;
10309 }
10310
10311 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
10312 RCPair
10313 ARMTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10314                                                 MVT VT) const {
10315   if (Constraint.size() == 1) {
10316     // GCC ARM Constraint Letters
10317     switch (Constraint[0]) {
10318     case 'l': // Low regs or general regs.
10319       if (Subtarget->isThumb())
10320         return RCPair(0U, &ARM::tGPRRegClass);
10321       return RCPair(0U, &ARM::GPRRegClass);
10322     case 'h': // High regs or no regs.
10323       if (Subtarget->isThumb())
10324         return RCPair(0U, &ARM::hGPRRegClass);
10325       break;
10326     case 'r':
10327       return RCPair(0U, &ARM::GPRRegClass);
10328     case 'w':
10329       if (VT == MVT::Other)
10330         break;
10331       if (VT == MVT::f32)
10332         return RCPair(0U, &ARM::SPRRegClass);
10333       if (VT.getSizeInBits() == 64)
10334         return RCPair(0U, &ARM::DPRRegClass);
10335       if (VT.getSizeInBits() == 128)
10336         return RCPair(0U, &ARM::QPRRegClass);
10337       break;
10338     case 'x':
10339       if (VT == MVT::Other)
10340         break;
10341       if (VT == MVT::f32)
10342         return RCPair(0U, &ARM::SPR_8RegClass);
10343       if (VT.getSizeInBits() == 64)
10344         return RCPair(0U, &ARM::DPR_8RegClass);
10345       if (VT.getSizeInBits() == 128)
10346         return RCPair(0U, &ARM::QPR_8RegClass);
10347       break;
10348     case 't':
10349       if (VT == MVT::f32)
10350         return RCPair(0U, &ARM::SPRRegClass);
10351       break;
10352     }
10353   }
10354   if (StringRef("{cc}").equals_lower(Constraint))
10355     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
10356
10357   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10358 }
10359
10360 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10361 /// vector.  If it is invalid, don't add anything to Ops.
10362 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10363                                                      std::string &Constraint,
10364                                                      std::vector<SDValue>&Ops,
10365                                                      SelectionDAG &DAG) const {
10366   SDValue Result;
10367
10368   // Currently only support length 1 constraints.
10369   if (Constraint.length() != 1) return;
10370
10371   char ConstraintLetter = Constraint[0];
10372   switch (ConstraintLetter) {
10373   default: break;
10374   case 'j':
10375   case 'I': case 'J': case 'K': case 'L':
10376   case 'M': case 'N': case 'O':
10377     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
10378     if (!C)
10379       return;
10380
10381     int64_t CVal64 = C->getSExtValue();
10382     int CVal = (int) CVal64;
10383     // None of these constraints allow values larger than 32 bits.  Check
10384     // that the value fits in an int.
10385     if (CVal != CVal64)
10386       return;
10387
10388     switch (ConstraintLetter) {
10389       case 'j':
10390         // Constant suitable for movw, must be between 0 and
10391         // 65535.
10392         if (Subtarget->hasV6T2Ops())
10393           if (CVal >= 0 && CVal <= 65535)
10394             break;
10395         return;
10396       case 'I':
10397         if (Subtarget->isThumb1Only()) {
10398           // This must be a constant between 0 and 255, for ADD
10399           // immediates.
10400           if (CVal >= 0 && CVal <= 255)
10401             break;
10402         } else if (Subtarget->isThumb2()) {
10403           // A constant that can be used as an immediate value in a
10404           // data-processing instruction.
10405           if (ARM_AM::getT2SOImmVal(CVal) != -1)
10406             break;
10407         } else {
10408           // A constant that can be used as an immediate value in a
10409           // data-processing instruction.
10410           if (ARM_AM::getSOImmVal(CVal) != -1)
10411             break;
10412         }
10413         return;
10414
10415       case 'J':
10416         if (Subtarget->isThumb()) {  // FIXME thumb2
10417           // This must be a constant between -255 and -1, for negated ADD
10418           // immediates. This can be used in GCC with an "n" modifier that
10419           // prints the negated value, for use with SUB instructions. It is
10420           // not useful otherwise but is implemented for compatibility.
10421           if (CVal >= -255 && CVal <= -1)
10422             break;
10423         } else {
10424           // This must be a constant between -4095 and 4095. It is not clear
10425           // what this constraint is intended for. Implemented for
10426           // compatibility with GCC.
10427           if (CVal >= -4095 && CVal <= 4095)
10428             break;
10429         }
10430         return;
10431
10432       case 'K':
10433         if (Subtarget->isThumb1Only()) {
10434           // A 32-bit value where only one byte has a nonzero value. Exclude
10435           // zero to match GCC. This constraint is used by GCC internally for
10436           // constants that can be loaded with a move/shift combination.
10437           // It is not useful otherwise but is implemented for compatibility.
10438           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
10439             break;
10440         } else if (Subtarget->isThumb2()) {
10441           // A constant whose bitwise inverse can be used as an immediate
10442           // value in a data-processing instruction. This can be used in GCC
10443           // with a "B" modifier that prints the inverted value, for use with
10444           // BIC and MVN instructions. It is not useful otherwise but is
10445           // implemented for compatibility.
10446           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
10447             break;
10448         } else {
10449           // A constant whose bitwise inverse can be used as an immediate
10450           // value in a data-processing instruction. This can be used in GCC
10451           // with a "B" modifier that prints the inverted value, for use with
10452           // BIC and MVN instructions. It is not useful otherwise but is
10453           // implemented for compatibility.
10454           if (ARM_AM::getSOImmVal(~CVal) != -1)
10455             break;
10456         }
10457         return;
10458
10459       case 'L':
10460         if (Subtarget->isThumb1Only()) {
10461           // This must be a constant between -7 and 7,
10462           // for 3-operand ADD/SUB immediate instructions.
10463           if (CVal >= -7 && CVal < 7)
10464             break;
10465         } else if (Subtarget->isThumb2()) {
10466           // A constant whose negation can be used as an immediate value in a
10467           // data-processing instruction. This can be used in GCC with an "n"
10468           // modifier that prints the negated value, for use with SUB
10469           // instructions. It is not useful otherwise but is implemented for
10470           // compatibility.
10471           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
10472             break;
10473         } else {
10474           // A constant whose negation can be used as an immediate value in a
10475           // data-processing instruction. This can be used in GCC with an "n"
10476           // modifier that prints the negated value, for use with SUB
10477           // instructions. It is not useful otherwise but is implemented for
10478           // compatibility.
10479           if (ARM_AM::getSOImmVal(-CVal) != -1)
10480             break;
10481         }
10482         return;
10483
10484       case 'M':
10485         if (Subtarget->isThumb()) { // FIXME thumb2
10486           // This must be a multiple of 4 between 0 and 1020, for
10487           // ADD sp + immediate.
10488           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
10489             break;
10490         } else {
10491           // A power of two or a constant between 0 and 32.  This is used in
10492           // GCC for the shift amount on shifted register operands, but it is
10493           // useful in general for any shift amounts.
10494           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
10495             break;
10496         }
10497         return;
10498
10499       case 'N':
10500         if (Subtarget->isThumb()) {  // FIXME thumb2
10501           // This must be a constant between 0 and 31, for shift amounts.
10502           if (CVal >= 0 && CVal <= 31)
10503             break;
10504         }
10505         return;
10506
10507       case 'O':
10508         if (Subtarget->isThumb()) {  // FIXME thumb2
10509           // This must be a multiple of 4 between -508 and 508, for
10510           // ADD/SUB sp = sp + immediate.
10511           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
10512             break;
10513         }
10514         return;
10515     }
10516     Result = DAG.getTargetConstant(CVal, Op.getValueType());
10517     break;
10518   }
10519
10520   if (Result.getNode()) {
10521     Ops.push_back(Result);
10522     return;
10523   }
10524   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10525 }
10526
10527 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
10528   assert(Subtarget->isTargetAEABI() && "Register-based DivRem lowering only");
10529   unsigned Opcode = Op->getOpcode();
10530   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
10531       "Invalid opcode for Div/Rem lowering");
10532   bool isSigned = (Opcode == ISD::SDIVREM);
10533   EVT VT = Op->getValueType(0);
10534   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
10535
10536   RTLIB::Libcall LC;
10537   switch (VT.getSimpleVT().SimpleTy) {
10538   default: llvm_unreachable("Unexpected request for libcall!");
10539   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
10540   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
10541   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
10542   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
10543   }
10544
10545   SDValue InChain = DAG.getEntryNode();
10546
10547   TargetLowering::ArgListTy Args;
10548   TargetLowering::ArgListEntry Entry;
10549   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
10550     EVT ArgVT = Op->getOperand(i).getValueType();
10551     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
10552     Entry.Node = Op->getOperand(i);
10553     Entry.Ty = ArgTy;
10554     Entry.isSExt = isSigned;
10555     Entry.isZExt = !isSigned;
10556     Args.push_back(Entry);
10557   }
10558
10559   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
10560                                          getPointerTy());
10561
10562   Type *RetTy = (Type*)StructType::get(Ty, Ty, NULL);
10563
10564   SDLoc dl(Op);
10565   TargetLowering::CallLoweringInfo CLI(DAG);
10566   CLI.setDebugLoc(dl).setChain(InChain)
10567     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, &Args, 0)
10568     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
10569
10570   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
10571   return CallInfo.first;
10572 }
10573
10574 SDValue
10575 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
10576   assert(Subtarget->isTargetWindows() && "unsupported target platform");
10577   SDLoc DL(Op);
10578
10579   // Get the inputs.
10580   SDValue Chain = Op.getOperand(0);
10581   SDValue Size  = Op.getOperand(1);
10582
10583   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
10584                               DAG.getConstant(2, MVT::i32));
10585
10586   SDValue Flag;
10587   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
10588   Flag = Chain.getValue(1);
10589
10590   SDVTList NodeTys = DAG.getVTList(MVT::i32, MVT::Glue);
10591   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
10592
10593   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
10594   Chain = NewSP.getValue(1);
10595
10596   SDValue Ops[2] = { NewSP, Chain };
10597   return DAG.getMergeValues(Ops, DL);
10598 }
10599
10600 bool
10601 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
10602   // The ARM target isn't yet aware of offsets.
10603   return false;
10604 }
10605
10606 bool ARM::isBitFieldInvertedMask(unsigned v) {
10607   if (v == 0xffffffff)
10608     return false;
10609
10610   // there can be 1's on either or both "outsides", all the "inside"
10611   // bits must be 0's
10612   unsigned TO = CountTrailingOnes_32(v);
10613   unsigned LO = CountLeadingOnes_32(v);
10614   v = (v >> TO) << TO;
10615   v = (v << LO) >> LO;
10616   return v == 0;
10617 }
10618
10619 /// isFPImmLegal - Returns true if the target can instruction select the
10620 /// specified FP immediate natively. If false, the legalizer will
10621 /// materialize the FP immediate as a load from a constant pool.
10622 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
10623   if (!Subtarget->hasVFP3())
10624     return false;
10625   if (VT == MVT::f32)
10626     return ARM_AM::getFP32Imm(Imm) != -1;
10627   if (VT == MVT::f64)
10628     return ARM_AM::getFP64Imm(Imm) != -1;
10629   return false;
10630 }
10631
10632 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
10633 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
10634 /// specified in the intrinsic calls.
10635 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
10636                                            const CallInst &I,
10637                                            unsigned Intrinsic) const {
10638   switch (Intrinsic) {
10639   case Intrinsic::arm_neon_vld1:
10640   case Intrinsic::arm_neon_vld2:
10641   case Intrinsic::arm_neon_vld3:
10642   case Intrinsic::arm_neon_vld4:
10643   case Intrinsic::arm_neon_vld2lane:
10644   case Intrinsic::arm_neon_vld3lane:
10645   case Intrinsic::arm_neon_vld4lane: {
10646     Info.opc = ISD::INTRINSIC_W_CHAIN;
10647     // Conservatively set memVT to the entire set of vectors loaded.
10648     uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
10649     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10650     Info.ptrVal = I.getArgOperand(0);
10651     Info.offset = 0;
10652     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10653     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10654     Info.vol = false; // volatile loads with NEON intrinsics not supported
10655     Info.readMem = true;
10656     Info.writeMem = false;
10657     return true;
10658   }
10659   case Intrinsic::arm_neon_vst1:
10660   case Intrinsic::arm_neon_vst2:
10661   case Intrinsic::arm_neon_vst3:
10662   case Intrinsic::arm_neon_vst4:
10663   case Intrinsic::arm_neon_vst2lane:
10664   case Intrinsic::arm_neon_vst3lane:
10665   case Intrinsic::arm_neon_vst4lane: {
10666     Info.opc = ISD::INTRINSIC_VOID;
10667     // Conservatively set memVT to the entire set of vectors stored.
10668     unsigned NumElts = 0;
10669     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
10670       Type *ArgTy = I.getArgOperand(ArgI)->getType();
10671       if (!ArgTy->isVectorTy())
10672         break;
10673       NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
10674     }
10675     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
10676     Info.ptrVal = I.getArgOperand(0);
10677     Info.offset = 0;
10678     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
10679     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
10680     Info.vol = false; // volatile stores with NEON intrinsics not supported
10681     Info.readMem = false;
10682     Info.writeMem = true;
10683     return true;
10684   }
10685   case Intrinsic::arm_ldaex:
10686   case Intrinsic::arm_ldrex: {
10687     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
10688     Info.opc = ISD::INTRINSIC_W_CHAIN;
10689     Info.memVT = MVT::getVT(PtrTy->getElementType());
10690     Info.ptrVal = I.getArgOperand(0);
10691     Info.offset = 0;
10692     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10693     Info.vol = true;
10694     Info.readMem = true;
10695     Info.writeMem = false;
10696     return true;
10697   }
10698   case Intrinsic::arm_stlex:
10699   case Intrinsic::arm_strex: {
10700     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
10701     Info.opc = ISD::INTRINSIC_W_CHAIN;
10702     Info.memVT = MVT::getVT(PtrTy->getElementType());
10703     Info.ptrVal = I.getArgOperand(1);
10704     Info.offset = 0;
10705     Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
10706     Info.vol = true;
10707     Info.readMem = false;
10708     Info.writeMem = true;
10709     return true;
10710   }
10711   case Intrinsic::arm_stlexd:
10712   case Intrinsic::arm_strexd: {
10713     Info.opc = ISD::INTRINSIC_W_CHAIN;
10714     Info.memVT = MVT::i64;
10715     Info.ptrVal = I.getArgOperand(2);
10716     Info.offset = 0;
10717     Info.align = 8;
10718     Info.vol = true;
10719     Info.readMem = false;
10720     Info.writeMem = true;
10721     return true;
10722   }
10723   case Intrinsic::arm_ldaexd:
10724   case Intrinsic::arm_ldrexd: {
10725     Info.opc = ISD::INTRINSIC_W_CHAIN;
10726     Info.memVT = MVT::i64;
10727     Info.ptrVal = I.getArgOperand(0);
10728     Info.offset = 0;
10729     Info.align = 8;
10730     Info.vol = true;
10731     Info.readMem = true;
10732     Info.writeMem = false;
10733     return true;
10734   }
10735   default:
10736     break;
10737   }
10738
10739   return false;
10740 }
10741
10742 /// \brief Returns true if it is beneficial to convert a load of a constant
10743 /// to just the constant itself.
10744 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
10745                                                           Type *Ty) const {
10746   assert(Ty->isIntegerTy());
10747
10748   unsigned Bits = Ty->getPrimitiveSizeInBits();
10749   if (Bits == 0 || Bits > 32)
10750     return false;
10751   return true;
10752 }
10753
10754 bool ARMTargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
10755   // Loads and stores less than 64-bits are already atomic; ones above that
10756   // are doomed anyway, so defer to the default libcall and blame the OS when
10757   // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
10758   // anything for those.
10759   bool IsMClass = Subtarget->isMClass();
10760   if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
10761     unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10762     return Size == 64 && !IsMClass;
10763   } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
10764     return LI->getType()->getPrimitiveSizeInBits() == 64 && !IsMClass;
10765   }
10766
10767   // For the real atomic operations, we have ldrex/strex up to 32 bits,
10768   // and up to 64 bits on the non-M profiles
10769   unsigned AtomicLimit = IsMClass ? 32 : 64;
10770   return Inst->getType()->getPrimitiveSizeInBits() <= AtomicLimit;
10771 }
10772
10773 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10774                                          AtomicOrdering Ord) const {
10775   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10776   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10777   bool IsAcquire =
10778       Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10779
10780   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
10781   // intrinsic must return {i32, i32} and we have to recombine them into a
10782   // single i64 here.
10783   if (ValTy->getPrimitiveSizeInBits() == 64) {
10784     Intrinsic::ID Int =
10785         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
10786     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
10787
10788     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10789     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
10790
10791     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10792     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10793     if (!Subtarget->isLittle())
10794       std::swap (Lo, Hi);
10795     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10796     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10797     return Builder.CreateOr(
10798         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
10799   }
10800
10801   Type *Tys[] = { Addr->getType() };
10802   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
10803   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10804
10805   return Builder.CreateTruncOrBitCast(
10806       Builder.CreateCall(Ldrex, Addr),
10807       cast<PointerType>(Addr->getType())->getElementType());
10808 }
10809
10810 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
10811                                                Value *Addr,
10812                                                AtomicOrdering Ord) const {
10813   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10814   bool IsRelease =
10815       Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
10816
10817   // Since the intrinsics must have legal type, the i64 intrinsics take two
10818   // parameters: "i32, i32". We must marshal Val into the appropriate form
10819   // before the call.
10820   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
10821     Intrinsic::ID Int =
10822         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
10823     Function *Strex = Intrinsic::getDeclaration(M, Int);
10824     Type *Int32Ty = Type::getInt32Ty(M->getContext());
10825
10826     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
10827     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
10828     if (!Subtarget->isLittle())
10829       std::swap (Lo, Hi);
10830     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10831     return Builder.CreateCall3(Strex, Lo, Hi, Addr);
10832   }
10833
10834   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
10835   Type *Tys[] = { Addr->getType() };
10836   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
10837
10838   return Builder.CreateCall2(
10839       Strex, Builder.CreateZExtOrBitCast(
10840                  Val, Strex->getFunctionType()->getParamType(0)),
10841       Addr);
10842 }
10843
10844 enum HABaseType {
10845   HA_UNKNOWN = 0,
10846   HA_FLOAT,
10847   HA_DOUBLE,
10848   HA_VECT64,
10849   HA_VECT128
10850 };
10851
10852 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
10853                                    uint64_t &Members) {
10854   if (const StructType *ST = dyn_cast<StructType>(Ty)) {
10855     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
10856       uint64_t SubMembers = 0;
10857       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
10858         return false;
10859       Members += SubMembers;
10860     }
10861   } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
10862     uint64_t SubMembers = 0;
10863     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
10864       return false;
10865     Members += SubMembers * AT->getNumElements();
10866   } else if (Ty->isFloatTy()) {
10867     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
10868       return false;
10869     Members = 1;
10870     Base = HA_FLOAT;
10871   } else if (Ty->isDoubleTy()) {
10872     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
10873       return false;
10874     Members = 1;
10875     Base = HA_DOUBLE;
10876   } else if (const VectorType *VT = dyn_cast<VectorType>(Ty)) {
10877     Members = 1;
10878     switch (Base) {
10879     case HA_FLOAT:
10880     case HA_DOUBLE:
10881       return false;
10882     case HA_VECT64:
10883       return VT->getBitWidth() == 64;
10884     case HA_VECT128:
10885       return VT->getBitWidth() == 128;
10886     case HA_UNKNOWN:
10887       switch (VT->getBitWidth()) {
10888       case 64:
10889         Base = HA_VECT64;
10890         return true;
10891       case 128:
10892         Base = HA_VECT128;
10893         return true;
10894       default:
10895         return false;
10896       }
10897     }
10898   }
10899
10900   return (Members > 0 && Members <= 4);
10901 }
10902
10903 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate.
10904 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
10905     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10906   if (getEffectiveCallingConv(CallConv, isVarArg) !=
10907       CallingConv::ARM_AAPCS_VFP)
10908     return false;
10909
10910   HABaseType Base = HA_UNKNOWN;
10911   uint64_t Members = 0;
10912   bool result = isHomogeneousAggregate(Ty, Base, Members);
10913   DEBUG(dbgs() << "isHA: " << result << " "; Ty->dump(); dbgs() << "\n");
10914   return result;
10915 }